diff --git a/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S001/reward.json b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S001/reward.json new file mode 100644 index 0000000000000000000000000000000000000000..201ea635dc8ce4ee91bec105e72fc97f392378d8 --- /dev/null +++ b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S001/reward.json @@ -0,0 +1,131 @@ +{ + "valid": 1.0, + "qm9_ma_rae": 0.43617580227724934, + "qm9_mean_spearman": 0.7569496414675415, + "compas1d_ma_rae": 0.9117029280709564, + "compas1d_mean_spearman": 0.25946280999311044, + "expansionrx_ma_rae": 1.0712069257208288, + "expansionrx_mean_spearman": 0.11021497070501299, + "asap_ma_rae": 1.3216491625281772, + "asap_mean_spearman": 0.18735888554493627, + "qm9dft_v2_mae": 0.031460551204370586, + "qm9dft_v2_rae": 1.0793471406130326, + "qm9dft_v2_r2": -0.13714757698386837, + "qm9dft_v2_spearman": 0.0, + "qm9dft_v2_kendall": 0.0, + "qm9dft_v2_alpha_mae": 1.4382298144032863, + "qm9dft_v2_alpha_rae": 0.2694694014923808, + "qm9dft_v2_alpha_r2": 0.9002137974313563, + "qm9dft_v2_alpha_spearman": 0.9477081514805884, + "qm9dft_v2_alpha_kendall": 0.8242724195607098, + "qm9dft_v2_cv_mae": 0.5076178557836722, + "qm9dft_v2_cv_rae": 0.23998254041262948, + "qm9dft_v2_cv_r2": 0.9282035211902653, + "qm9dft_v2_cv_spearman": 0.9633549872770778, + "qm9dft_v2_cv_kendall": 0.8490494583760366, + "qm9dft_v2_mu_mae": 0.8624877422747367, + "qm9dft_v2_mu_rae": 0.6754289178114469, + "qm9dft_v2_mu_r2": 0.36233943222534115, + "qm9dft_v2_mu_spearman": 0.6904614061151867, + "qm9dft_v2_mu_kendall": 0.5010895173988749, + "qm9dft_v2_r2_mae": 17.65358226875168, + "qm9dft_v2_r2_rae": 0.1494208093004624, + "qm9dft_v2_r2_r2": 0.9667340194359327, + "qm9dft_v2_r2_spearman": 0.9791729531601663, + "qm9dft_v2_r2_kendall": 0.9098025343373991, + "qm9dft_v2_zpve_mae": 0.004342632585553269, + "qm9dft_v2_zpve_rae": 0.20340600403354397, + "qm9dft_v2_zpve_r2": 0.9397173547188411, + "qm9dft_v2_zpve_spearman": 0.9610003507722298, + "qm9dft_v2_zpve_kendall": 0.8457673670608977, + "compas1d_aea_mae": 0.12538875097223715, + "compas1d_aea_rae": 0.7672064213619454, + "compas1d_aea_r2": 0.41253084223375014, + "compas1d_aea_spearman": 0.6080583791356737, + "compas1d_aea_kendall": 0.43704926115190834, + "compas1d_aip_mae": 0.12502298433874715, + "compas1d_aip_rae": 0.8452392498414383, + "compas1d_aip_r2": 0.3618014315649831, + "compas1d_aip_spearman": 0.42979286083676804, + "compas1d_aip_kendall": 0.30909048838604886, + "compas1d_disp_mae": 0.36967611658932714, + "compas1d_disp_rae": 1.04065663307627, + "compas1d_disp_r2": -0.0018988865235847197, + "compas1d_disp_spearman": 0.0, + "compas1d_disp_kendall": 0.0, + "compas1d_dipmom_mae": 0.0823594157845127, + "compas1d_dipmom_rae": 0.9937094080041721, + "compas1d_dipmom_r2": -0.05025207732631287, + "compas1d_dipmom_spearman": 0.0, + "compas1d_dipmom_kendall": 0.0, + "exrx_logd_mae": 0.8150718987785334, + "exrx_logd_rae": 1.0040645134028767, + "exrx_logd_r2": -0.0024486963709324794, + "exrx_logd_spearman": 0.06449137579995287, + "exrx_logd_kendall": 0.05327729610932751, + "exrx_ksol_mae": 0.5632680747546098, + "exrx_ksol_rae": 0.9803774713288496, + "exrx_ksol_r2": -0.002051957511927105, + "exrx_ksol_spearman": 0.0, + "exrx_ksol_kendall": 0.0, + "exrx_hlm_clint_mae": 0.39162257406480416, + "exrx_hlm_clint_rae": 1.0653746242360231, + "exrx_hlm_clint_r2": -0.1310307416195844, + "exrx_hlm_clint_spearman": 0.0, + "exrx_hlm_clint_kendall": 0.0, + "exrx_mlm_clint_mae": 0.4244715576292351, + "exrx_mlm_clint_rae": 1.002642730596974, + "exrx_mlm_clint_r2": -0.01450057279174266, + "exrx_mlm_clint_spearman": 0.0, + "exrx_mlm_clint_kendall": 0.0, + "exrx_caco_2_permeability_papp_a_b_mae": 0.447744421305829, + "exrx_caco_2_permeability_papp_a_b_rae": 1.2508772467359255, + "exrx_caco_2_permeability_papp_a_b_r2": -0.6827471087855492, + "exrx_caco_2_permeability_papp_a_b_spearman": 0.0, + "exrx_caco_2_permeability_papp_a_b_kendall": 0.0, + "exrx_caco_2_permeability_efflux_mae": 0.517485516659029, + "exrx_caco_2_permeability_efflux_rae": 1.0992425766461504, + "exrx_caco_2_permeability_efflux_r2": -0.6587544559824163, + "exrx_caco_2_permeability_efflux_spearman": 0.0, + "exrx_caco_2_permeability_efflux_kendall": 0.0, + "exrx_mppb_mae": 0.33917614227618, + "exrx_mppb_rae": 1.0565786472718948, + "exrx_mppb_r2": -0.07235765231547164, + "exrx_mppb_spearman": 0.13852862909538974, + "exrx_mppb_kendall": 0.11022812651160054, + "exrx_mbpb_mae": 0.355985016230667, + "exrx_mbpb_rae": 1.0126049685900387, + "exrx_mbpb_r2": -0.04857575920663981, + "exrx_mbpb_spearman": 0.17469202591624874, + "exrx_mbpb_kendall": 0.1415205157788797, + "exrx_mgmb_mae": 0.44272951765224217, + "exrx_mgmb_rae": 1.1690995526787247, + "exrx_mgmb_r2": -0.3588756275197842, + "exrx_mgmb_spearman": 0.6142227055335255, + "exrx_mgmb_kendall": 0.4315009625929443, + "asap_hlm_mae": 0.5226424178002005, + "asap_hlm_rae": 1.0445478959125163, + "asap_hlm_r2": -0.1445428686935808, + "asap_hlm_spearman": 0.10196233401169734, + "asap_hlm_kendall": 0.0798958210344005, + "asap_ksol_mae": 0.41924832691622355, + "asap_ksol_rae": 2.2292597470026183, + "asap_ksol_r2": -1.0028416706613301, + "asap_ksol_spearman": 0.06837733507860821, + "asap_ksol_kendall": 0.05297942052121686, + "asap_logd_mae": 0.763346548217834, + "asap_logd_rae": 1.0566748738567593, + "asap_logd_r2": -0.07561189588043615, + "asap_logd_spearman": 0.07213388134078015, + "asap_logd_kendall": 0.06427671257534519, + "asap_mdr1_mdckii_mae": 0.5751541266877147, + "asap_mdr1_mdckii_rae": 1.2015843036679585, + "asap_mdr1_mdckii_r2": -0.5527862739593241, + "asap_mdr1_mdckii_spearman": 0.7443054065100743, + "asap_mdr1_mdckii_kendall": 0.5940760729861716, + "asap_mlm_mae": 0.599476393665195, + "asap_mlm_rae": 1.076178992201034, + "asap_mlm_r2": -0.12489447876241133, + "asap_mlm_spearman": -0.04998452921647864, + "asap_mlm_kendall": -0.0158660122169541 +} diff --git a/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S003/report.json b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S003/report.json new file mode 100644 index 0000000000000000000000000000000000000000..dae6b4f8eb0b76db185241ff498950f16d5661e8 --- /dev/null +++ b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S003/report.json @@ -0,0 +1,438 @@ +{ + "groups": { + "qm9_ma_rae": 0.23459037448721873, + "qm9_mean_spearman": 0.9500934915794308, + "compas1d_ma_rae": 0.1983224806320354, + "compas1d_mean_spearman": 0.9621945228762312, + "expansionrx_ma_rae": 0.7869536139892782, + "expansionrx_mean_spearman": 0.6166640638015242, + "asap_ma_rae": 0.8827297476999233, + "asap_mean_spearman": 0.4558379579873595 + }, + "tasks": { + "qm9dft_v2": { + "mae": 0.009834592862257784, + "rae": 0.3532476149147217, + "r2": 0.8190658362317924, + "spearman": 0.9069786782000695, + "kendall": 0.7627488504581325, + "n": 13377 + }, + "qm9dft_v2_alpha": { + "mae": 0.9566759091248921, + "rae": 0.17924457000706914, + "r2": 0.9444597939158037, + "spearman": 0.9774378870726885, + "kendall": 0.8900874451400774, + "n": 13377 + }, + "qm9dft_v2_cv": { + "mae": 0.3939950126404204, + "rae": 0.1862659537406987, + "r2": 0.9528736581887455, + "spearman": 0.9770400703804685, + "kendall": 0.8881189771362948, + "n": 13377 + }, + "qm9dft_v2_mu": { + "mae": 0.5350666710734001, + "rae": 0.4190198711078724, + "r2": 0.7182541905465378, + "spearman": 0.8790282084872334, + "kendall": 0.7073511576781308, + "n": 13377 + }, + "qm9dft_v2_r2": { + "mae": 14.322782590878436, + "rae": 0.12122875309856088, + "r2": 0.9738472689526051, + "spearman": 0.9836168396179193, + "kendall": 0.9252522490377645, + "n": 13377 + }, + "qm9dft_v2_zpve": { + "mae": 0.003171170075486792, + "rae": 0.14853548405438963, + "r2": 0.9650193201849472, + "spearman": 0.9764592657182051, + "kendall": 0.8873175252144985, + "n": 13377 + }, + "compas1d_aea": { + "mae": 0.02556919937117695, + "rae": 0.15644827621733168, + "r2": 0.8809439632256538, + "spearman": 0.9775436405838613, + "kendall": 0.9052875804309362, + "n": 862 + }, + "compas1d_aip": { + "mae": 0.022927856728538316, + "rae": 0.15500769337894932, + "r2": 0.8279836798307266, + "spearman": 0.9915846489126657, + "kendall": 0.9302096584235607, + "n": 862 + }, + "compas1d_disp": { + "mae": 0.018584482440413413, + "rae": 0.05231624131507134, + "r2": 0.9851767103165092, + "spearman": 0.9984359894865176, + "kendall": 0.9745553321983884, + "n": 862 + }, + "compas1d_dipmom": { + "mae": 0.03559876510468847, + "rae": 0.4295177116167892, + "r2": 0.7958729411769604, + "spearman": 0.8812138125218796, + "kendall": 0.7121305806891127, + "n": 862 + }, + "exrx_logd": { + "mae": 0.41233982341309566, + "rae": 0.5079500161548227, + "r2": 0.6834666106234801, + "spearman": 0.8539662908127514, + "kendall": 0.689135213259979, + "n": 2270 + }, + "exrx_ksol": { + "mae": 0.36857406116870695, + "rae": 0.6415092959838026, + "r2": 0.3861647633634454, + "spearman": 0.5302570199108971, + "kendall": 0.3727450000805426, + "n": 2170 + }, + "exrx_hlm_clint": { + "mae": 0.3663103788256348, + "rae": 0.9965150326868992, + "r2": 0.040724636882697896, + "spearman": 0.6109602929295984, + "kendall": 0.43515716813812466, + "n": 782 + }, + "exrx_mlm_clint": { + "mae": 0.3777456025277202, + "rae": 0.8922715210996908, + "r2": 0.19303688390151996, + "spearman": 0.5108519446482683, + "kendall": 0.3551483211622574, + "n": 1170 + }, + "exrx_caco_2_permeability_papp_a_b": { + "mae": 0.41769732274275734, + "rae": 1.1669337509948456, + "r2": -0.5178157018994047, + "spearman": 0.3999547232462867, + "kendall": 0.26908240071671286, + "n": 1616 + }, + "exrx_caco_2_permeability_efflux": { + "mae": 0.47213542119691254, + "rae": 1.002909917697992, + "r2": -0.3504668751238895, + "spearman": 0.4882042402874392, + "kendall": 0.3377186186409435, + "n": 1616 + }, + "exrx_mppb": { + "mae": 0.24204073682675453, + "rae": 0.753988982199309, + "r2": 0.34695157333067217, + "spearman": 0.6471369575073963, + "kendall": 0.4685056414805123, + "n": 454 + }, + "exrx_mbpb": { + "mae": 0.20505998379771337, + "rae": 0.5832963439056945, + "r2": 0.5276876583435376, + "spearman": 0.784446480209569, + "kendall": 0.5894746640501078, + "n": 451 + }, + "exrx_mgmb": { + "mae": 0.20343664484301244, + "rae": 0.5372076651804468, + "r2": 0.5447956227492488, + "spearman": 0.7241986246615116, + "kendall": 0.5387397848945848, + "n": 209 + }, + "asap_hlm": { + "mae": 0.5956585788875481, + "rae": 1.1904772633611318, + "r2": -0.581044414825195, + "spearman": 0.2699292902706492, + "kendall": 0.1829051916755551, + "n": 104 + }, + "asap_ksol": { + "mae": 0.1698950113054957, + "rae": 0.903378941797371, + "r2": -0.31520526719836206, + "spearman": 0.26643496766454544, + "kendall": 0.1758429740114018, + "n": 108 + }, + "asap_logd": { + "mae": 0.638847030434985, + "rae": 0.8843343916006221, + "r2": 0.06203847073789548, + "spearman": 0.5583248689293288, + "kendall": 0.4096700884432859, + "n": 122 + }, + "asap_mdr1_mdckii": { + "mae": 0.22570498147620788, + "rae": 0.4715319779818449, + "r2": 0.7214868429239925, + "spearman": 0.835936209328461, + "kendall": 0.6294665795684645, + "n": 122 + }, + "asap_mlm": { + "mae": 0.5369469062276723, + "rae": 0.9639261637586463, + "r2": 0.050719190741727704, + "spearman": 0.34856445374381295, + "kendall": 0.24698627267199583, + "n": 120 + } + }, + "group_tasks": { + "qm9": [ + "qm9dft_v2", + "qm9dft_v2_alpha", + "qm9dft_v2_cv", + "qm9dft_v2_mu", + "qm9dft_v2_r2", + "qm9dft_v2_zpve" + ], + "compas1d": [ + "compas1d_aea", + "compas1d_aip", + "compas1d_disp", + "compas1d_dipmom" + ], + "expansionrx": [ + "exrx_logd", + "exrx_ksol", + "exrx_hlm_clint", + "exrx_mlm_clint", + "exrx_caco_2_permeability_papp_a_b", + "exrx_caco_2_permeability_efflux", + "exrx_mppb", + "exrx_mbpb", + "exrx_mgmb" + ], + "asap": [ + "asap_hlm", + "asap_ksol", + "asap_logd", + "asap_mdr1_mdckii", + "asap_mlm" + ] + }, + "encoder_check": { + "arch": "unimol2_84M", + "user_dir": null, + "encoder_parameters": 83425520, + "max_parameters": 90000000, + "missing_keys": [], + "n_missing": 0, + "shape_mismatch": [], + "n_shape_mismatch": 0, + "unused_checkpoint_keys": 6, + "ok": true + }, + "fine_tunes": { + "encoder": "/workspace/mpt-verifier/package", + "gpus": [ + "GPU-3ddde818-89cc-3dc1-4349-b23419390e76", + "GPU-b6e308d5-ca67-b6af-4caf-fab6410a51ff", + "GPU-0b3b0e76-51c4-e566-1d31-e6543302d5dc", + "GPU-bc65b618-596c-7bca-57a5-ef2ea962c319", + "GPU-667d3efb-ec4b-016b-41ee-16b8e087f5fb", + "GPU-2f3ac22e-1729-e625-2dee-ecdd6b0f7e17", + "GPU-387df9a3-b0ff-510c-5e34-12351f50f0ca", + "GPU-7e837f63-90c0-2f70-f9ea-962a0f07ca10" + ], + "slots": 3, + "minutes": 15.45, + "tasks": { + "exrx_mgmb": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-0b3b0e76-51c4-e566-1d31-e6543302d5dc", + "minutes": 1.7 + }, + "asap_hlm": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-bc65b618-596c-7bca-57a5-ef2ea962c319", + "minutes": 2.14 + }, + "asap_logd": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-2f3ac22e-1729-e625-2dee-ecdd6b0f7e17", + "minutes": 2.15 + }, + "asap_ksol": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-667d3efb-ec4b-016b-41ee-16b8e087f5fb", + "minutes": 2.24 + }, + "asap_mlm": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-7e837f63-90c0-2f70-f9ea-962a0f07ca10", + "minutes": 2.39 + }, + "asap_mdr1_mdckii": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-387df9a3-b0ff-510c-5e34-12351f50f0ca", + "minutes": 2.77 + }, + "exrx_mbpb": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-b6e308d5-ca67-b6af-4caf-fab6410a51ff", + "minutes": 4.05 + }, + "exrx_mppb": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-3ddde818-89cc-3dc1-4349-b23419390e76", + "minutes": 5.04 + }, + "exrx_caco_2_permeability_efflux": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-7e837f63-90c0-2f70-f9ea-962a0f07ca10", + "minutes": 7.02 + }, + "exrx_caco_2_permeability_papp_a_b": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-387df9a3-b0ff-510c-5e34-12351f50f0ca", + "minutes": 7.12 + }, + "exrx_hlm_clint": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-667d3efb-ec4b-016b-41ee-16b8e087f5fb", + "minutes": 7.76 + }, + "exrx_mlm_clint": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-2f3ac22e-1729-e625-2dee-ecdd6b0f7e17", + "minutes": 9.31 + }, + "exrx_logd": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-0b3b0e76-51c4-e566-1d31-e6543302d5dc", + "minutes": 10.14 + }, + "exrx_ksol": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-bc65b618-596c-7bca-57a5-ef2ea962c319", + "minutes": 10.39 + }, + "qm9dft_v2_r2": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-667d3efb-ec4b-016b-41ee-16b8e087f5fb", + "minutes": 10.44 + }, + "qm9dft_v2_zpve": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-2f3ac22e-1729-e625-2dee-ecdd6b0f7e17", + "minutes": 10.72 + }, + "qm9dft_v2_mu": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-bc65b618-596c-7bca-57a5-ef2ea962c319", + "minutes": 11.06 + }, + "qm9dft_v2_cv": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-0b3b0e76-51c4-e566-1d31-e6543302d5dc", + "minutes": 11.08 + }, + "qm9dft_v2_alpha": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-b6e308d5-ca67-b6af-4caf-fab6410a51ff", + "minutes": 12.14 + }, + "qm9dft_v2": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-3ddde818-89cc-3dc1-4349-b23419390e76", + "minutes": 12.45 + }, + "compas1d_aip": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-7e837f63-90c0-2f70-f9ea-962a0f07ca10", + "minutes": 13.76 + }, + "compas1d_aea": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-387df9a3-b0ff-510c-5e34-12351f50f0ca", + "minutes": 13.96 + }, + "compas1d_dipmom": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-b6e308d5-ca67-b6af-4caf-fab6410a51ff", + "minutes": 15.11 + }, + "compas1d_disp": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-3ddde818-89cc-3dc1-4349-b23419390e76", + "minutes": 15.42 + } + }, + "failed": [] + } +} diff --git a/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S004/logs/inference/verifier.log b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S004/logs/inference/verifier.log new file mode 100644 index 0000000000000000000000000000000000000000..86ab272d9c827b2d4e8aabedbdac709be7f19e05 --- /dev/null +++ b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S004/logs/inference/verifier.log @@ -0,0 +1 @@ +fine-tunes and sealing took 12.3 min; waiting for the grader diff --git a/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S004/logs/score/verifier.log b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S004/logs/score/verifier.log new file mode 100644 index 0000000000000000000000000000000000000000..41c4794e1c17fc07bceb917f70543e2e8f55a94a --- /dev/null +++ b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S004/logs/score/verifier.log @@ -0,0 +1 @@ +{"valid": 1.0, "qm9_ma_rae": 0.24234720930610695, "compas1d_ma_rae": 0.20245247886100892, "expansionrx_ma_rae": 0.8215837333118553, "asap_ma_rae": 0.7822712725159473} diff --git a/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S005/logs/score/verifier.log b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S005/logs/score/verifier.log new file mode 100644 index 0000000000000000000000000000000000000000..aea9eec27ec34c61286b0480f8012ac92dfa0d35 --- /dev/null +++ b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S005/logs/score/verifier.log @@ -0,0 +1 @@ +{"valid": 1.0, "qm9_ma_rae": 0.242834100871977, "compas1d_ma_rae": 0.19473212626362946, "expansionrx_ma_rae": 0.8091345424360504, "asap_ma_rae": 0.7681816729250319} diff --git a/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S005/reward.json b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S005/reward.json new file mode 100644 index 0000000000000000000000000000000000000000..2bcfe42bff7d75b9a0365360410d94db24234f49 --- /dev/null +++ b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S005/reward.json @@ -0,0 +1,131 @@ +{ + "valid": 1.0, + "qm9_ma_rae": 0.242834100871977, + "qm9_mean_spearman": 0.9463484831605317, + "compas1d_ma_rae": 0.19473212626362946, + "compas1d_mean_spearman": 0.9653306853238933, + "expansionrx_ma_rae": 0.8091345424360504, + "expansionrx_mean_spearman": 0.5978214092046176, + "asap_ma_rae": 0.7681816729250319, + "asap_mean_spearman": 0.5372408247735841, + "qm9dft_v2_mae": 0.009999933498320119, + "qm9dft_v2_rae": 0.35719245669807037, + "qm9dft_v2_r2": 0.8177570872739547, + "qm9dft_v2_spearman": 0.9096766296935449, + "qm9dft_v2_kendall": 0.7660223420699115, + "qm9dft_v2_alpha_mae": 1.0192569675222762, + "qm9dft_v2_alpha_rae": 0.19096987300261267, + "qm9dft_v2_alpha_r2": 0.9388137555132142, + "qm9dft_v2_alpha_spearman": 0.9769128746909955, + "qm9dft_v2_alpha_kendall": 0.8912086408055317, + "qm9dft_v2_cv_mae": 0.3805784292238382, + "qm9dft_v2_cv_rae": 0.1799231000855635, + "qm9dft_v2_cv_r2": 0.9550953010432428, + "qm9dft_v2_cv_spearman": 0.9777001160095836, + "qm9dft_v2_cv_kendall": 0.8880038784547789, + "qm9dft_v2_mu_mae": 0.5862831742449701, + "qm9dft_v2_mu_rae": 0.45912839163017427, + "qm9dft_v2_mu_r2": 0.6866985351462106, + "qm9dft_v2_mu_spearman": 0.85036490934555, + "qm9dft_v2_mu_kendall": 0.668452182453535, + "qm9dft_v2_r2_mae": 16.003061736223, + "qm9dft_v2_r2_rae": 0.13545072039822256, + "qm9dft_v2_r2_r2": 0.9748740826817132, + "qm9dft_v2_r2_spearman": 0.983756509130487, + "qm9dft_v2_r2_kendall": 0.9159657122990562, + "qm9dft_v2_zpve_mae": 0.0028681038188268005, + "qm9dft_v2_zpve_rae": 0.13434006341721882, + "qm9dft_v2_zpve_r2": 0.9715899679644281, + "qm9dft_v2_zpve_spearman": 0.9796798600930297, + "qm9dft_v2_zpve_kendall": 0.8986466879654952, + "compas1d_aea_mae": 0.02315499515529424, + "compas1d_aea_rae": 0.14167667220546623, + "compas1d_aea_r2": 0.8748215855896782, + "compas1d_aea_spearman": 0.9818576358470448, + "compas1d_aea_kendall": 0.9182943705343573, + "compas1d_aip_mae": 0.02272779674646701, + "compas1d_aip_rae": 0.15365515368343963, + "compas1d_aip_r2": 0.8585795792785416, + "compas1d_aip_spearman": 0.9914364305091486, + "compas1d_aip_kendall": 0.9292262153611184, + "compas1d_disp_mae": 0.02498449858943262, + "compas1d_disp_rae": 0.07033260471641846, + "compas1d_disp_r2": 0.9778153767000798, + "compas1d_disp_spearman": 0.9977739619744365, + "compas1d_disp_kendall": 0.9700150829405872, + "compas1d_dipmom_mae": 0.034251650897341654, + "compas1d_dipmom_rae": 0.4132640744491936, + "compas1d_dipmom_r2": 0.8046992630959897, + "compas1d_dipmom_spearman": 0.8902547129649431, + "compas1d_dipmom_kendall": 0.7216333826054264, + "exrx_logd_mae": 0.41700390468562215, + "exrx_logd_rae": 0.5136955687869141, + "exrx_logd_r2": 0.6733276626966319, + "exrx_logd_spearman": 0.8423145372616159, + "exrx_logd_kendall": 0.6740644378363648, + "exrx_ksol_mae": 0.3695648539195497, + "exrx_ksol_rae": 0.6432337872788317, + "exrx_ksol_r2": 0.44756915160277655, + "exrx_ksol_spearman": 0.5464878656427739, + "exrx_ksol_kendall": 0.3831947074731223, + "exrx_hlm_clint_mae": 0.37075764126092803, + "exrx_hlm_clint_rae": 1.0086134173553365, + "exrx_hlm_clint_r2": -0.003143503989398999, + "exrx_hlm_clint_spearman": 0.6167991051269286, + "exrx_hlm_clint_kendall": 0.4416763231570397, + "exrx_mlm_clint_mae": 0.4531818430527466, + "exrx_mlm_clint_rae": 1.0704591919260322, + "exrx_mlm_clint_r2": -0.15223816144179314, + "exrx_mlm_clint_spearman": 0.4570100945499797, + "exrx_mlm_clint_kendall": 0.31528489982079055, + "exrx_caco_2_permeability_papp_a_b_mae": 0.41441367289624115, + "exrx_caco_2_permeability_papp_a_b_rae": 1.157760118261967, + "exrx_caco_2_permeability_papp_a_b_r2": -0.5047637559227609, + "exrx_caco_2_permeability_papp_a_b_spearman": 0.3211735674029204, + "exrx_caco_2_permeability_papp_a_b_kendall": 0.21428320594360023, + "exrx_caco_2_permeability_efflux_mae": 0.4321126583215129, + "exrx_caco_2_permeability_efflux_rae": 0.91789357700562, + "exrx_caco_2_permeability_efflux_r2": -0.1627465986324672, + "exrx_caco_2_permeability_efflux_spearman": 0.5013794134312447, + "exrx_caco_2_permeability_efflux_kendall": 0.3439759781008145, + "exrx_mppb_mae": 0.26259623900904866, + "exrx_mppb_rae": 0.8180220965098024, + "exrx_mppb_r2": 0.29529036334906633, + "exrx_mppb_spearman": 0.6249951910896876, + "exrx_mppb_kendall": 0.44787637458152835, + "exrx_mbpb_mae": 0.19338928183116558, + "exrx_mbpb_rae": 0.550098848900449, + "exrx_mbpb_r2": 0.5787401397722123, + "exrx_mbpb_spearman": 0.7908984378718131, + "exrx_mbpb_kendall": 0.5976970030278435, + "exrx_mgmb_mae": 0.2281374890402163, + "exrx_mgmb_rae": 0.602434275899502, + "exrx_mgmb_r2": 0.4246205086298903, + "exrx_mgmb_spearman": 0.6793344704645947, + "exrx_mgmb_kendall": 0.5032925442324994, + "asap_hlm_mae": 0.4491032553536274, + "asap_hlm_rae": 0.8975732631912546, + "asap_hlm_r2": 0.18702411512387018, + "asap_hlm_spearman": 0.4200685489084338, + "asap_hlm_kendall": 0.2871019272606883, + "asap_ksol_mae": 0.18263069434187987, + "asap_ksol_rae": 0.9710981042146097, + "asap_ksol_r2": -0.41366332152176755, + "asap_ksol_spearman": 0.13395873291043842, + "asap_ksol_kendall": 0.08421846987338462, + "asap_logd_mae": 0.5121777295237209, + "asap_logd_rae": 0.7089903517612776, + "asap_logd_r2": 0.4819557856940957, + "asap_logd_spearman": 0.7055649519894899, + "asap_logd_kendall": 0.5297885541872487, + "asap_mdr1_mdckii_mae": 0.20588391988949137, + "asap_mdr1_mdckii_rae": 0.4301227706415558, + "asap_mdr1_mdckii_r2": 0.7531645130233298, + "asap_mdr1_mdckii_spearman": 0.8511470059238094, + "asap_mdr1_mdckii_kendall": 0.6544174306327897, + "asap_mlm_mae": 0.4640845989103356, + "asap_mlm_rae": 0.8331238748164621, + "asap_mlm_r2": 0.242320248174396, + "asap_mlm_spearman": 0.5754648841357494, + "asap_mlm_kendall": 0.4056062026367644 +} diff --git a/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S006/logs/inference/verifier.log b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S006/logs/inference/verifier.log new file mode 100644 index 0000000000000000000000000000000000000000..4bba020c26eeb1cb85ba8b3dbc7aaa5e4a9bd8c1 --- /dev/null +++ b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S006/logs/inference/verifier.log @@ -0,0 +1 @@ +fine-tunes and sealing took 12.6 min; waiting for the grader diff --git a/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S007/logs/score/verifier.log b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S007/logs/score/verifier.log new file mode 100644 index 0000000000000000000000000000000000000000..50843963530e2e406ae5ba45d3c2e23b19c5a767 --- /dev/null +++ b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S007/logs/score/verifier.log @@ -0,0 +1 @@ +{"valid": 1.0, "qm9_ma_rae": 0.24119809496168676, "compas1d_ma_rae": 0.19308383863514983, "expansionrx_ma_rae": 0.7837011748473522, "asap_ma_rae": 0.7135329884902727} diff --git a/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S009/logs/inference/verifier.log b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S009/logs/inference/verifier.log new file mode 100644 index 0000000000000000000000000000000000000000..affee5db5dd7127279253f2b27093d83b34e5171 --- /dev/null +++ b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S009/logs/inference/verifier.log @@ -0,0 +1 @@ +fine-tunes and sealing took 12.4 min; waiting for the grader diff --git a/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S010/logs/score/verifier.log b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S010/logs/score/verifier.log new file mode 100644 index 0000000000000000000000000000000000000000..7181db123b335e2fe296afc74bcf48c7692c5a9e --- /dev/null +++ b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S010/logs/score/verifier.log @@ -0,0 +1 @@ +{"valid": 1.0, "qm9_ma_rae": 0.21168829128766095, "compas1d_ma_rae": 0.17762784676672674, "expansionrx_ma_rae": 0.6864283410299862, "asap_ma_rae": 0.6774068141020765} diff --git a/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S010/reward.json b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S010/reward.json new file mode 100644 index 0000000000000000000000000000000000000000..31c15ecaffc546504189d5219c3a7654f7381a34 --- /dev/null +++ b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S010/reward.json @@ -0,0 +1,131 @@ +{ + "valid": 1.0, + "qm9_ma_rae": 0.21168829128766095, + "qm9_mean_spearman": 0.9586056658215728, + "compas1d_ma_rae": 0.17762784676672674, + "compas1d_mean_spearman": 0.977062605932477, + "expansionrx_ma_rae": 0.6864283410299862, + "expansionrx_mean_spearman": 0.6810858127196987, + "asap_ma_rae": 0.6774068141020765, + "asap_mean_spearman": 0.5986465901830889, + "qm9dft_v2_mae": 0.008416821539781533, + "qm9dft_v2_rae": 0.2996422022068375, + "qm9dft_v2_r2": 0.8562291620317685, + "qm9dft_v2_spearman": 0.9289593675251234, + "qm9dft_v2_kendall": 0.7997319376039504, + "qm9dft_v2_alpha_mae": 1.0064691431018016, + "qm9dft_v2_alpha_rae": 0.18857392253734948, + "qm9dft_v2_alpha_r2": 0.9511416301282962, + "qm9dft_v2_alpha_spearman": 0.9819947961834593, + "qm9dft_v2_alpha_kendall": 0.8995397248278204, + "qm9dft_v2_cv_mae": 0.34235155745614854, + "qm9dft_v2_cv_rae": 0.16185087962618802, + "qm9dft_v2_cv_r2": 0.9627193739935208, + "qm9dft_v2_cv_spearman": 0.9845498700150335, + "qm9dft_v2_cv_kendall": 0.9092883400984625, + "qm9dft_v2_mu_mae": 0.5232183822236431, + "qm9dft_v2_mu_rae": 0.409741273252554, + "qm9dft_v2_mu_r2": 0.7354552682153206, + "qm9dft_v2_mu_spearman": 0.8806906965088498, + "qm9dft_v2_mu_kendall": 0.7075320644362122, + "qm9dft_v2_r2_mae": 14.791139107830977, + "qm9dft_v2_r2_rae": 0.1251929462429783, + "qm9dft_v2_r2_r2": 0.9796150600112563, + "qm9dft_v2_r2_spearman": 0.9906877158915731, + "qm9dft_v2_r2_kendall": 0.9350888195718031, + "qm9dft_v2_zpve_mae": 0.0018174581592673806, + "qm9dft_v2_zpve_rae": 0.08512852386005833, + "qm9dft_v2_zpve_r2": 0.9828912716669042, + "qm9dft_v2_zpve_spearman": 0.9847515488053977, + "qm9dft_v2_zpve_kendall": 0.9191702691966361, + "compas1d_aea_mae": 0.02153212130549991, + "compas1d_aea_rae": 0.13174691990337759, + "compas1d_aea_r2": 0.8728409774034983, + "compas1d_aea_spearman": 0.9882141398112533, + "compas1d_aea_kendall": 0.9278717077096309, + "compas1d_aip_mae": 0.018125580046403685, + "compas1d_aip_rae": 0.12254108124513131, + "compas1d_aip_r2": 0.86680177423351, + "compas1d_aip_spearman": 0.9935309713905046, + "compas1d_aip_kendall": 0.9405232907985077, + "compas1d_disp_mae": 0.03714174060061165, + "compas1d_disp_rae": 0.10455584492888127, + "compas1d_disp_r2": 0.9754232281926191, + "compas1d_disp_spearman": 0.9957855612430464, + "compas1d_disp_kendall": 0.966207584310289, + "compas1d_dipmom_mae": 0.02914648185171572, + "compas1d_dipmom_rae": 0.3516675409895168, + "compas1d_dipmom_r2": 0.8555820015432294, + "compas1d_dipmom_spearman": 0.9307197512851033, + "compas1d_dipmom_kendall": 0.7845020882979429, + "exrx_logd_mae": 0.3764290195109136, + "exrx_logd_rae": 0.4637124907291698, + "exrx_logd_r2": 0.7166846738495616, + "exrx_logd_spearman": 0.8661313466360808, + "exrx_logd_kendall": 0.7067726933160449, + "exrx_ksol_mae": 0.3441802006546395, + "exrx_ksol_rae": 0.5990513752199658, + "exrx_ksol_r2": 0.5166219847143381, + "exrx_ksol_spearman": 0.5729479652729057, + "exrx_ksol_kendall": 0.401339840975323, + "exrx_hlm_clint_mae": 0.31062246854021147, + "exrx_hlm_clint_rae": 0.845020991168739, + "exrx_hlm_clint_r2": 0.26159381731715714, + "exrx_hlm_clint_spearman": 0.6303372814797318, + "exrx_hlm_clint_kendall": 0.4551037616015833, + "exrx_mlm_clint_mae": 0.3872775974467632, + "exrx_mlm_clint_rae": 0.9147870118125306, + "exrx_mlm_clint_r2": 0.17329388999911488, + "exrx_mlm_clint_spearman": 0.4872219365119797, + "exrx_mlm_clint_kendall": 0.33710985935813365, + "exrx_caco_2_permeability_papp_a_b_mae": 0.3082539705487702, + "exrx_caco_2_permeability_papp_a_b_rae": 0.8611785197700751, + "exrx_caco_2_permeability_papp_a_b_r2": 0.1371569000458127, + "exrx_caco_2_permeability_papp_a_b_spearman": 0.652599527971348, + "exrx_caco_2_permeability_papp_a_b_kendall": 0.47002081930889567, + "exrx_caco_2_permeability_efflux_mae": 0.3219839030548856, + "exrx_caco_2_permeability_efflux_rae": 0.6839581086591969, + "exrx_caco_2_permeability_efflux_r2": 0.40608544753588505, + "exrx_caco_2_permeability_efflux_spearman": 0.6944602717975009, + "exrx_caco_2_permeability_efflux_kendall": 0.503770869911701, + "exrx_mppb_mae": 0.26914859278773356, + "exrx_mppb_rae": 0.838433547166295, + "exrx_mppb_r2": 0.253738915490791, + "exrx_mppb_spearman": 0.6171496986355294, + "exrx_mppb_kendall": 0.44559416369528837, + "exrx_mbpb_mae": 0.15901562583675646, + "exrx_mbpb_rae": 0.4523224446655313, + "exrx_mbpb_r2": 0.7031685529070422, + "exrx_mbpb_spearman": 0.8438603193782777, + "exrx_mbpb_kendall": 0.6645733644893211, + "exrx_mgmb_mae": 0.1966894439950293, + "exrx_mgmb_rae": 0.5193905800783719, + "exrx_mgmb_r2": 0.583334448937022, + "exrx_mgmb_spearman": 0.765063966793934, + "exrx_mgmb_kendall": 0.5939128303303547, + "asap_hlm_mae": 0.3448260967834557, + "asap_hlm_rae": 0.6891659796135785, + "asap_hlm_r2": 0.4798895153484585, + "asap_hlm_spearman": 0.7011119913377645, + "asap_hlm_kendall": 0.5031293985518589, + "asap_ksol_mae": 0.16219173938850856, + "asap_ksol_rae": 0.8624185064127675, + "asap_ksol_r2": 0.1251641823509808, + "asap_ksol_spearman": 0.13286373636744858, + "asap_ksol_kendall": 0.0798337537796572, + "asap_logd_mae": 0.4058819819610035, + "asap_logd_rae": 0.5618487344845963, + "asap_logd_r2": 0.6434756053559183, + "asap_logd_spearman": 0.8122347302166942, + "asap_logd_kendall": 0.6379659416963662, + "asap_mdr1_mdckii_mae": 0.20185825899868415, + "asap_mdr1_mdckii_rae": 0.4217125537730079, + "asap_mdr1_mdckii_r2": 0.7688798701231079, + "asap_mdr1_mdckii_spearman": 0.875846993654109, + "asap_mdr1_mdckii_kendall": 0.6810849711605909, + "asap_mlm_mae": 0.4745371609447018, + "asap_mlm_rae": 0.8518882962264324, + "asap_mlm_r2": 0.2131973672389863, + "asap_mlm_spearman": 0.47117549933942826, + "asap_mlm_kendall": 0.32723709353165814 +} diff --git a/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S012/logs/inference/verifier.log b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S012/logs/inference/verifier.log new file mode 100644 index 0000000000000000000000000000000000000000..7a64795bb486918ccdda8c41e8031c478c538dac --- /dev/null +++ b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S012/logs/inference/verifier.log @@ -0,0 +1 @@ +fine-tunes and sealing took 10.3 min; waiting for the grader diff --git a/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S013/report.json b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S013/report.json new file mode 100644 index 0000000000000000000000000000000000000000..2e4f7e9fc6bcb873430f6b74c242ee76fec5d7ab --- /dev/null +++ b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S013/report.json @@ -0,0 +1,438 @@ +{ + "groups": { + "qm9_ma_rae": 0.1461110151689148, + "qm9_mean_spearman": 0.9739625584801573, + "compas1d_ma_rae": 0.12878823085605462, + "compas1d_mean_spearman": 0.9879512005846832, + "expansionrx_ma_rae": 0.6514811789118182, + "expansionrx_mean_spearman": 0.7033221063393997, + "asap_ma_rae": 0.6661312922117657, + "asap_mean_spearman": 0.6629925852858726 + }, + "tasks": { + "qm9dft_v2": { + "mae": 0.00756529859596753, + "rae": 0.26955584935537674, + "r2": 0.8687958715483087, + "spearman": 0.9373838501247235, + "kendall": 0.820070703010417, + "n": 13377 + }, + "qm9dft_v2_alpha": { + "mae": 0.6090975351179453, + "rae": 0.11412164217080636, + "r2": 0.969999662848029, + "spearman": 0.9877226313693594, + "kendall": 0.9253471187734348, + "n": 13377 + }, + "qm9dft_v2_cv": { + "mae": 0.2134535557979447, + "rae": 0.10091277522422293, + "r2": 0.9828117213394642, + "spearman": 0.9906874223243254, + "kendall": 0.9343628787576624, + "n": 13377 + }, + "qm9dft_v2_mu": { + "mae": 0.3304173108885164, + "rae": 0.258755453301862, + "r2": 0.8529455070990049, + "spearman": 0.9482391891050016, + "kendall": 0.8233214752497475, + "n": 13377 + }, + "qm9dft_v2_r2": { + "mae": 8.544655649792404, + "rae": 0.07232239570127943, + "r2": 0.9861745147399141, + "spearman": 0.9912081513307494, + "kendall": 0.953536365939561, + "n": 13377 + }, + "qm9dft_v2_zpve": { + "mae": 0.0013022811016576979, + "rae": 0.06099797525994143, + "r2": 0.9872999789000286, + "spearman": 0.9885341066267841, + "kendall": 0.9347668520127325, + "n": 13377 + }, + "compas1d_aea": { + "mae": 0.020182581964511708, + "rae": 0.12348959825164534, + "r2": 0.8848063950306163, + "spearman": 0.9908988733542708, + "kendall": 0.9396473167928742, + "n": 862 + }, + "compas1d_aip": { + "mae": 0.016664271778105866, + "rae": 0.11266165698553667, + "r2": 0.867298807508616, + "spearman": 0.9957940583412941, + "kendall": 0.9557008910114178, + "n": 862 + }, + "compas1d_disp": { + "mae": 0.017774459172642906, + "rae": 0.05003598557572658, + "r2": 0.9807980187205471, + "spearman": 0.9988204460588623, + "kendall": 0.9850764964012909, + "n": 862 + }, + "compas1d_dipmom": { + "mae": 0.018976855509946496, + "rae": 0.22896568261130992, + "r2": 0.9341221044959835, + "spearman": 0.966291424584306, + "kendall": 0.8550589116973544, + "n": 862 + }, + "exrx_logd": { + "mae": 0.35923987691479753, + "rae": 0.4425376617080168, + "r2": 0.7489369054318791, + "spearman": 0.8820415793288674, + "kendall": 0.7240477395148702, + "n": 2270 + }, + "exrx_ksol": { + "mae": 0.33394826293243335, + "rae": 0.5812425170927573, + "r2": 0.530811175346923, + "spearman": 0.5988173674240345, + "kendall": 0.41987483651971336, + "n": 2170 + }, + "exrx_hlm_clint": { + "mae": 0.2902164152124461, + "rae": 0.7895081253741059, + "r2": 0.34949011898345406, + "spearman": 0.6447144361474388, + "kendall": 0.4668671292830982, + "n": 782 + }, + "exrx_mlm_clint": { + "mae": 0.38404561905067774, + "rae": 0.9071527673359854, + "r2": 0.18614353294375285, + "spearman": 0.5008602165136237, + "kendall": 0.34924908938996924, + "n": 1170 + }, + "exrx_caco_2_permeability_papp_a_b": { + "mae": 0.23637996643736026, + "rae": 0.6603819222098843, + "r2": 0.48942763787484966, + "spearman": 0.7151410851157426, + "kendall": 0.5232051431039741, + "n": 1616 + }, + "exrx_caco_2_permeability_efflux": { + "mae": 0.4055025494001457, + "rae": 0.8613683917513401, + "r2": 0.017544091645946502, + "spearman": 0.6367742042334379, + "kendall": 0.45004992603217575, + "n": 1616 + }, + "exrx_mppb": { + "mae": 0.23287113159718367, + "rae": 0.7254244463081367, + "r2": 0.43123898291492835, + "spearman": 0.7202849618405136, + "kendall": 0.5248385167159041, + "n": 454 + }, + "exrx_mbpb": { + "mae": 0.14950972050681877, + "rae": 0.4252827476862509, + "r2": 0.7274706427910254, + "spearman": 0.8617198436068751, + "kendall": 0.6885367692349765, + "n": 451 + }, + "exrx_mgmb": { + "mae": 0.17814919660213893, + "rae": 0.4704320307398867, + "r2": 0.6027975180461921, + "spearman": 0.7695452628440633, + "kendall": 0.6007554099096751, + "n": 209 + }, + "asap_hlm": { + "mae": 0.3691589449282568, + "rae": 0.737797365941137, + "r2": 0.3603792986202866, + "spearman": 0.633098168974589, + "kendall": 0.4466237528173752, + "n": 104 + }, + "asap_ksol": { + "mae": 0.16297814855714954, + "rae": 0.8666000622873493, + "r2": 0.16058023638102348, + "spearman": 0.3078643752066866, + "kendall": 0.20800196600140836, + "n": 108 + }, + "asap_logd": { + "mae": 0.4053071538903377, + "rae": 0.5610530193792117, + "r2": 0.6822101413102943, + "spearman": 0.8616596167041956, + "kendall": 0.6917831823006664, + "n": 122 + }, + "asap_mdr1_mdckii": { + "mae": 0.20564229560647762, + "rae": 0.42961798082543057, + "r2": 0.7787917550753711, + "spearman": 0.8707282699962627, + "kendall": 0.6824409038127123, + "n": 122 + }, + "asap_mlm": { + "mae": 0.4097530840291261, + "rae": 0.7355880326257002, + "r2": 0.4076758805722295, + "spearman": 0.6416124955476291, + "kendall": 0.46188348063433765, + "n": 120 + } + }, + "group_tasks": { + "qm9": [ + "qm9dft_v2", + "qm9dft_v2_alpha", + "qm9dft_v2_cv", + "qm9dft_v2_mu", + "qm9dft_v2_r2", + "qm9dft_v2_zpve" + ], + "compas1d": [ + "compas1d_aea", + "compas1d_aip", + "compas1d_disp", + "compas1d_dipmom" + ], + "expansionrx": [ + "exrx_logd", + "exrx_ksol", + "exrx_hlm_clint", + "exrx_mlm_clint", + "exrx_caco_2_permeability_papp_a_b", + "exrx_caco_2_permeability_efflux", + "exrx_mppb", + "exrx_mbpb", + "exrx_mgmb" + ], + "asap": [ + "asap_hlm", + "asap_ksol", + "asap_logd", + "asap_mdr1_mdckii", + "asap_mlm" + ] + }, + "encoder_check": { + "arch": "unimol2_compact128_poolnorm_82M", + "user_dir": "user_dir", + "encoder_parameters": 82005488, + "max_parameters": 90000000, + "missing_keys": [], + "n_missing": 0, + "shape_mismatch": [], + "n_shape_mismatch": 0, + "unused_checkpoint_keys": 24, + "ok": true + }, + "fine_tunes": { + "encoder": "/workspace/mpt-verifier/package", + "gpus": [ + "GPU-c9eda5a7-1bd5-7255-9a31-4ed0e69ebbc5", + "GPU-b87fc7a8-2402-f153-1738-a5cebbfb6ac2", + "GPU-087885a4-34de-cafa-6d70-d5e83971a334", + "GPU-f8b067ee-41d1-9718-fed7-9b715ffe6ad9", + "GPU-54f0d541-9710-11f0-e59e-d1e448be012b", + "GPU-ed6aff95-0700-9ee4-fa04-c5d38d9b045b", + "GPU-282a04e6-cf4a-f647-8896-f1e3b045d3f3", + "GPU-3eb7ea5f-27b7-beb5-fbb9-df0e7a167fb1" + ], + "slots": 3, + "minutes": 10.38, + "tasks": { + "exrx_mgmb": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-087885a4-34de-cafa-6d70-d5e83971a334", + "minutes": 1.34 + }, + "asap_hlm": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-f8b067ee-41d1-9718-fed7-9b715ffe6ad9", + "minutes": 1.43 + }, + "asap_logd": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-ed6aff95-0700-9ee4-fa04-c5d38d9b045b", + "minutes": 1.52 + }, + "asap_ksol": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-54f0d541-9710-11f0-e59e-d1e448be012b", + "minutes": 1.53 + }, + "asap_mlm": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-3eb7ea5f-27b7-beb5-fbb9-df0e7a167fb1", + "minutes": 1.52 + }, + "asap_mdr1_mdckii": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-282a04e6-cf4a-f647-8896-f1e3b045d3f3", + "minutes": 1.68 + }, + "exrx_mbpb": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-b87fc7a8-2402-f153-1738-a5cebbfb6ac2", + "minutes": 2.53 + }, + "exrx_mppb": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-c9eda5a7-1bd5-7255-9a31-4ed0e69ebbc5", + "minutes": 3.01 + }, + "exrx_caco_2_permeability_efflux": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-3eb7ea5f-27b7-beb5-fbb9-df0e7a167fb1", + "minutes": 4.22 + }, + "exrx_caco_2_permeability_papp_a_b": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-282a04e6-cf4a-f647-8896-f1e3b045d3f3", + "minutes": 4.23 + }, + "exrx_hlm_clint": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-54f0d541-9710-11f0-e59e-d1e448be012b", + "minutes": 5.6 + }, + "exrx_mlm_clint": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-ed6aff95-0700-9ee4-fa04-c5d38d9b045b", + "minutes": 6.6 + }, + "exrx_logd": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-087885a4-34de-cafa-6d70-d5e83971a334", + "minutes": 7.22 + }, + "exrx_ksol": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-f8b067ee-41d1-9718-fed7-9b715ffe6ad9", + "minutes": 7.62 + }, + "compas1d_aea": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-282a04e6-cf4a-f647-8896-f1e3b045d3f3", + "minutes": 8.61 + }, + "compas1d_aip": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-3eb7ea5f-27b7-beb5-fbb9-df0e7a167fb1", + "minutes": 8.62 + }, + "compas1d_dipmom": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-b87fc7a8-2402-f153-1738-a5cebbfb6ac2", + "minutes": 8.92 + }, + "compas1d_disp": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-c9eda5a7-1bd5-7255-9a31-4ed0e69ebbc5", + "minutes": 8.95 + }, + "qm9dft_v2_cv": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-087885a4-34de-cafa-6d70-d5e83971a334", + "minutes": 9.46 + }, + "qm9dft_v2_mu": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-f8b067ee-41d1-9718-fed7-9b715ffe6ad9", + "minutes": 9.6 + }, + "qm9dft_v2_zpve": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-ed6aff95-0700-9ee4-fa04-c5d38d9b045b", + "minutes": 9.62 + }, + "qm9dft_v2_r2": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-54f0d541-9710-11f0-e59e-d1e448be012b", + "minutes": 9.74 + }, + "qm9dft_v2_alpha": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-b87fc7a8-2402-f153-1738-a5cebbfb6ac2", + "minutes": 10.03 + }, + "qm9dft_v2": { + "attempts": 1, + "exit": 0, + "ok": true, + "gpu": "GPU-c9eda5a7-1bd5-7255-9a31-4ed0e69ebbc5", + "minutes": 10.38 + } + }, + "failed": [] + } +} diff --git a/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S013/reward.json b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S013/reward.json new file mode 100644 index 0000000000000000000000000000000000000000..d4e4dc6830f314848f8d82d7b7fad9ae036c1f19 --- /dev/null +++ b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S013/reward.json @@ -0,0 +1,131 @@ +{ + "valid": 1.0, + "qm9_ma_rae": 0.1461110151689148, + "qm9_mean_spearman": 0.9739625584801573, + "compas1d_ma_rae": 0.12878823085605462, + "compas1d_mean_spearman": 0.9879512005846832, + "expansionrx_ma_rae": 0.6514811789118182, + "expansionrx_mean_spearman": 0.7033221063393997, + "asap_ma_rae": 0.6661312922117657, + "asap_mean_spearman": 0.6629925852858726, + "qm9dft_v2_mae": 0.00756529859596753, + "qm9dft_v2_rae": 0.26955584935537674, + "qm9dft_v2_r2": 0.8687958715483087, + "qm9dft_v2_spearman": 0.9373838501247235, + "qm9dft_v2_kendall": 0.820070703010417, + "qm9dft_v2_alpha_mae": 0.6090975351179453, + "qm9dft_v2_alpha_rae": 0.11412164217080636, + "qm9dft_v2_alpha_r2": 0.969999662848029, + "qm9dft_v2_alpha_spearman": 0.9877226313693594, + "qm9dft_v2_alpha_kendall": 0.9253471187734348, + "qm9dft_v2_cv_mae": 0.2134535557979447, + "qm9dft_v2_cv_rae": 0.10091277522422293, + "qm9dft_v2_cv_r2": 0.9828117213394642, + "qm9dft_v2_cv_spearman": 0.9906874223243254, + "qm9dft_v2_cv_kendall": 0.9343628787576624, + "qm9dft_v2_mu_mae": 0.3304173108885164, + "qm9dft_v2_mu_rae": 0.258755453301862, + "qm9dft_v2_mu_r2": 0.8529455070990049, + "qm9dft_v2_mu_spearman": 0.9482391891050016, + "qm9dft_v2_mu_kendall": 0.8233214752497475, + "qm9dft_v2_r2_mae": 8.544655649792404, + "qm9dft_v2_r2_rae": 0.07232239570127943, + "qm9dft_v2_r2_r2": 0.9861745147399141, + "qm9dft_v2_r2_spearman": 0.9912081513307494, + "qm9dft_v2_r2_kendall": 0.953536365939561, + "qm9dft_v2_zpve_mae": 0.0013022811016576979, + "qm9dft_v2_zpve_rae": 0.06099797525994143, + "qm9dft_v2_zpve_r2": 0.9872999789000286, + "qm9dft_v2_zpve_spearman": 0.9885341066267841, + "qm9dft_v2_zpve_kendall": 0.9347668520127325, + "compas1d_aea_mae": 0.020182581964511708, + "compas1d_aea_rae": 0.12348959825164534, + "compas1d_aea_r2": 0.8848063950306163, + "compas1d_aea_spearman": 0.9908988733542708, + "compas1d_aea_kendall": 0.9396473167928742, + "compas1d_aip_mae": 0.016664271778105866, + "compas1d_aip_rae": 0.11266165698553667, + "compas1d_aip_r2": 0.867298807508616, + "compas1d_aip_spearman": 0.9957940583412941, + "compas1d_aip_kendall": 0.9557008910114178, + "compas1d_disp_mae": 0.017774459172642906, + "compas1d_disp_rae": 0.05003598557572658, + "compas1d_disp_r2": 0.9807980187205471, + "compas1d_disp_spearman": 0.9988204460588623, + "compas1d_disp_kendall": 0.9850764964012909, + "compas1d_dipmom_mae": 0.018976855509946496, + "compas1d_dipmom_rae": 0.22896568261130992, + "compas1d_dipmom_r2": 0.9341221044959835, + "compas1d_dipmom_spearman": 0.966291424584306, + "compas1d_dipmom_kendall": 0.8550589116973544, + "exrx_logd_mae": 0.35923987691479753, + "exrx_logd_rae": 0.4425376617080168, + "exrx_logd_r2": 0.7489369054318791, + "exrx_logd_spearman": 0.8820415793288674, + "exrx_logd_kendall": 0.7240477395148702, + "exrx_ksol_mae": 0.33394826293243335, + "exrx_ksol_rae": 0.5812425170927573, + "exrx_ksol_r2": 0.530811175346923, + "exrx_ksol_spearman": 0.5988173674240345, + "exrx_ksol_kendall": 0.41987483651971336, + "exrx_hlm_clint_mae": 0.2902164152124461, + "exrx_hlm_clint_rae": 0.7895081253741059, + "exrx_hlm_clint_r2": 0.34949011898345406, + "exrx_hlm_clint_spearman": 0.6447144361474388, + "exrx_hlm_clint_kendall": 0.4668671292830982, + "exrx_mlm_clint_mae": 0.38404561905067774, + "exrx_mlm_clint_rae": 0.9071527673359854, + "exrx_mlm_clint_r2": 0.18614353294375285, + "exrx_mlm_clint_spearman": 0.5008602165136237, + "exrx_mlm_clint_kendall": 0.34924908938996924, + "exrx_caco_2_permeability_papp_a_b_mae": 0.23637996643736026, + "exrx_caco_2_permeability_papp_a_b_rae": 0.6603819222098843, + "exrx_caco_2_permeability_papp_a_b_r2": 0.48942763787484966, + "exrx_caco_2_permeability_papp_a_b_spearman": 0.7151410851157426, + "exrx_caco_2_permeability_papp_a_b_kendall": 0.5232051431039741, + "exrx_caco_2_permeability_efflux_mae": 0.4055025494001457, + "exrx_caco_2_permeability_efflux_rae": 0.8613683917513401, + "exrx_caco_2_permeability_efflux_r2": 0.017544091645946502, + "exrx_caco_2_permeability_efflux_spearman": 0.6367742042334379, + "exrx_caco_2_permeability_efflux_kendall": 0.45004992603217575, + "exrx_mppb_mae": 0.23287113159718367, + "exrx_mppb_rae": 0.7254244463081367, + "exrx_mppb_r2": 0.43123898291492835, + "exrx_mppb_spearman": 0.7202849618405136, + "exrx_mppb_kendall": 0.5248385167159041, + "exrx_mbpb_mae": 0.14950972050681877, + "exrx_mbpb_rae": 0.4252827476862509, + "exrx_mbpb_r2": 0.7274706427910254, + "exrx_mbpb_spearman": 0.8617198436068751, + "exrx_mbpb_kendall": 0.6885367692349765, + "exrx_mgmb_mae": 0.17814919660213893, + "exrx_mgmb_rae": 0.4704320307398867, + "exrx_mgmb_r2": 0.6027975180461921, + "exrx_mgmb_spearman": 0.7695452628440633, + "exrx_mgmb_kendall": 0.6007554099096751, + "asap_hlm_mae": 0.3691589449282568, + "asap_hlm_rae": 0.737797365941137, + "asap_hlm_r2": 0.3603792986202866, + "asap_hlm_spearman": 0.633098168974589, + "asap_hlm_kendall": 0.4466237528173752, + "asap_ksol_mae": 0.16297814855714954, + "asap_ksol_rae": 0.8666000622873493, + "asap_ksol_r2": 0.16058023638102348, + "asap_ksol_spearman": 0.3078643752066866, + "asap_ksol_kendall": 0.20800196600140836, + "asap_logd_mae": 0.4053071538903377, + "asap_logd_rae": 0.5610530193792117, + "asap_logd_r2": 0.6822101413102943, + "asap_logd_spearman": 0.8616596167041956, + "asap_logd_kendall": 0.6917831823006664, + "asap_mdr1_mdckii_mae": 0.20564229560647762, + "asap_mdr1_mdckii_rae": 0.42961798082543057, + "asap_mdr1_mdckii_r2": 0.7787917550753711, + "asap_mdr1_mdckii_spearman": 0.8707282699962627, + "asap_mdr1_mdckii_kendall": 0.6824409038127123, + "asap_mlm_mae": 0.4097530840291261, + "asap_mlm_rae": 0.7355880326257002, + "asap_mlm_r2": 0.4076758805722295, + "asap_mlm_spearman": 0.6416124955476291, + "asap_mlm_kendall": 0.46188348063433765 +} diff --git a/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S014/reward.json b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S014/reward.json new file mode 100644 index 0000000000000000000000000000000000000000..1f9b1cae2e93a1a5e85cf4d802a61c8280f20905 --- /dev/null +++ b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/evaluations/S014/reward.json @@ -0,0 +1,131 @@ +{ + "valid": 1.0, + "qm9_ma_rae": 0.14281247275338654, + "qm9_mean_spearman": 0.9743868879227332, + "compas1d_ma_rae": 0.1240790078418216, + "compas1d_mean_spearman": 0.9892543943632454, + "expansionrx_ma_rae": 0.6774444643730683, + "expansionrx_mean_spearman": 0.677592219434672, + "asap_ma_rae": 0.6727600197684293, + "asap_mean_spearman": 0.6703632120230285, + "qm9dft_v2_mae": 0.007495833865456787, + "qm9dft_v2_rae": 0.26638955460136554, + "qm9dft_v2_r2": 0.8697415827994736, + "qm9dft_v2_spearman": 0.938788256888448, + "qm9dft_v2_kendall": 0.8225827100182429, + "qm9dft_v2_alpha_mae": 0.5805337604572318, + "qm9dft_v2_alpha_rae": 0.10876988045296217, + "qm9dft_v2_alpha_r2": 0.9735827202757245, + "qm9dft_v2_alpha_spearman": 0.9888835061481108, + "qm9dft_v2_alpha_kendall": 0.9281238477444246, + "qm9dft_v2_cv_mae": 0.21905956968201926, + "qm9dft_v2_cv_rae": 0.1035630867492415, + "qm9dft_v2_cv_r2": 0.9816050064384135, + "qm9dft_v2_cv_spearman": 0.9904010039008272, + "qm9dft_v2_cv_kendall": 0.9342529684818593, + "qm9dft_v2_mu_mae": 0.3230698113429947, + "qm9dft_v2_mu_rae": 0.2530015006096613, + "qm9dft_v2_mu_r2": 0.8606546203656746, + "qm9dft_v2_mu_spearman": 0.9484427893986046, + "qm9dft_v2_mu_kendall": 0.8255969488785035, + "qm9dft_v2_r2_mae": 7.861791402475135, + "qm9dft_v2_r2_rae": 0.06654259832513407, + "qm9dft_v2_r2_r2": 0.9869235769748903, + "qm9dft_v2_r2_spearman": 0.9909631510774833, + "qm9dft_v2_r2_kendall": 0.9549880586542056, + "qm9dft_v2_zpve_mae": 0.0012512607424994258, + "qm9dft_v2_zpve_rae": 0.05860821578195461, + "qm9dft_v2_zpve_r2": 0.9873791852645221, + "qm9dft_v2_zpve_spearman": 0.9888426201229256, + "qm9dft_v2_zpve_kendall": 0.9373394847014391, + "compas1d_aea_mae": 0.02095755362133515, + "compas1d_aea_rae": 0.12823135719635398, + "compas1d_aea_r2": 0.8660572751859943, + "compas1d_aea_spearman": 0.9907875949748, + "compas1d_aea_kendall": 0.9383057102965212, + "compas1d_aip_mae": 0.016126341357308584, + "compas1d_aip_rae": 0.10902488645293093, + "compas1d_aip_r2": 0.8560943231867004, + "compas1d_aip_spearman": 0.9956880243304195, + "compas1d_aip_kendall": 0.9557475206537407, + "compas1d_disp_mae": 0.013639151813963298, + "compas1d_disp_rae": 0.038394889926045415, + "compas1d_disp_r2": 0.984496143522671, + "compas1d_disp_spearman": 0.999473627274785, + "compas1d_disp_kendall": 0.9877675054971913, + "compas1d_dipmom_mae": 0.018288879948108943, + "compas1d_dipmom_rae": 0.2206648977919561, + "compas1d_dipmom_r2": 0.9402112593814042, + "compas1d_dipmom_spearman": 0.971068330872977, + "compas1d_dipmom_kendall": 0.8628088657982431, + "exrx_logd_mae": 0.34634807080997143, + "exrx_logd_rae": 0.4266566025733262, + "exrx_logd_r2": 0.7649542203689577, + "exrx_logd_spearman": 0.8886005824684384, + "exrx_logd_kendall": 0.7310019412563592, + "exrx_ksol_mae": 0.3174433930268073, + "exrx_ksol_rae": 0.5525155159579271, + "exrx_ksol_r2": 0.548214861001844, + "exrx_ksol_spearman": 0.5876422419796865, + "exrx_ksol_kendall": 0.4100219381117611, + "exrx_hlm_clint_mae": 0.2967942148197353, + "exrx_hlm_clint_rae": 0.8074024482477304, + "exrx_hlm_clint_r2": 0.3284467936212525, + "exrx_hlm_clint_spearman": 0.6302682767222654, + "exrx_hlm_clint_kendall": 0.45312098439361287, + "exrx_mlm_clint_mae": 0.38132991871579686, + "exrx_mlm_clint_rae": 0.9007380213999893, + "exrx_mlm_clint_r2": 0.18694912722713963, + "exrx_mlm_clint_spearman": 0.5217565302003458, + "exrx_mlm_clint_kendall": 0.3665884227278164, + "exrx_caco_2_permeability_papp_a_b_mae": 0.30605341178570344, + "exrx_caco_2_permeability_papp_a_b_rae": 0.8550307516330705, + "exrx_caco_2_permeability_papp_a_b_r2": 0.1940582962541365, + "exrx_caco_2_permeability_papp_a_b_spearman": 0.5720729129791866, + "exrx_caco_2_permeability_papp_a_b_kendall": 0.4023830846975451, + "exrx_caco_2_permeability_efflux_mae": 0.42254921844190685, + "exrx_caco_2_permeability_efflux_rae": 0.8975789209303556, + "exrx_caco_2_permeability_efflux_r2": -0.05355699826328464, + "exrx_caco_2_permeability_efflux_spearman": 0.556346064865434, + "exrx_caco_2_permeability_efflux_kendall": 0.38673026396039656, + "exrx_mppb_mae": 0.23834272410218593, + "exrx_mppb_rae": 0.7424691823221778, + "exrx_mppb_r2": 0.4070054281683084, + "exrx_mppb_spearman": 0.7181179880585918, + "exrx_mppb_kendall": 0.5231756178437181, + "exrx_mbpb_mae": 0.15244218355671318, + "exrx_mbpb_rae": 0.4336241848792301, + "exrx_mbpb_r2": 0.7141033657855642, + "exrx_mbpb_spearman": 0.8560547204121922, + "exrx_mbpb_kendall": 0.6825823011073442, + "exrx_mgmb_mae": 0.18214535961261633, + "exrx_mgmb_rae": 0.4809845514138078, + "exrx_mgmb_r2": 0.585595410302052, + "exrx_mgmb_spearman": 0.767470657225906, + "exrx_mgmb_kendall": 0.5992818415272506, + "asap_hlm_mae": 0.3636277550197399, + "asap_hlm_rae": 0.726742785248755, + "asap_hlm_r2": 0.36080232714960747, + "asap_hlm_spearman": 0.644746914638166, + "asap_hlm_kendall": 0.4545539646032948, + "asap_ksol_mae": 0.15824260420672598, + "asap_ksol_rae": 0.8414198582822552, + "asap_ksol_r2": 0.22676400742403435, + "asap_ksol_spearman": 0.3680337742881132, + "asap_ksol_kendall": 0.25302396412161987, + "asap_logd_mae": 0.4129156576005963, + "asap_logd_rae": 0.5715852143790401, + "asap_logd_r2": 0.6729165429973137, + "asap_logd_spearman": 0.8710992234501808, + "asap_logd_kendall": 0.7026229238700767, + "asap_mdr1_mdckii_mae": 0.21884259206436638, + "asap_mdr1_mdckii_rae": 0.45719540449603374, + "asap_mdr1_mdckii_r2": 0.7356384537964974, + "asap_mdr1_mdckii_spearman": 0.865597758370357, + "asap_mdr1_mdckii_kendall": 0.6666216512620792, + "asap_mlm_mae": 0.42717110638256645, + "asap_mlm_rae": 0.7668568364360625, + "asap_mlm_r2": 0.36062755825619885, + "asap_mlm_spearman": 0.6023383893683258, + "asap_mlm_kendall": 0.43161441758305824 +} diff --git a/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/finalization/prompt.txt b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/finalization/prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..5d9609786c391bbfd142561f5ecd00d7863b8d3a --- /dev/null +++ b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/finalization/prompt.txt @@ -0,0 +1,10 @@ +It is now time to submit. Stop exploring the problem. Submit your best solution without further experiments. You will be given an additional 5 minutes starting now to submit. +The 48-hour research budget is over. This is a separate, hard-limited submission-only window. +Use only code, weights, observations, and development results you already produced. +Do not train, run inference/evaluations/simulations, search hyperparameters, or conduct any new experiment. +Choose using only your existing research notes and results; no sealed evaluation results are available. +Publish a complete portable package to /workspace/submission using the original task contract. +The original research tree is now read-only. Use /workspace/finalization or /tmp for packaging scratch; +/workspace/submission and its local parent support atomic publication. File listing, copying, +archiving, and static checks needed for packaging are allowed. Do not alter the scientific method. +The previous container's processes have ended. Finish and stop after publishing. Do not inspect credentials. diff --git a/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/finalization/status.json b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/finalization/status.json new file mode 100644 index 0000000000000000000000000000000000000000..47ea215812c6e99b601d4b55fc3e6a55cd902c69 --- /dev/null +++ b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/finalization/status.json @@ -0,0 +1,17 @@ +{ + "phase": "complete", + "error": null, + "elapsed_seconds": 147.83230811799876, + "total_publication_seconds": 147.83230811799876, + "thread_id": "01a166a6-abe0-71b1-9752-eeb1eb2f7398", + "turn_completed": true, + "submission_sha256": "9f5ff1dc64c29bcf07fb600090434e59ddd9857f5c0f0df4ea7aa0318079c2dc", + "cutoff_submission_sha256": "4fdb6e6246f50456a9b28779de2f1228f98a5b06df483d8521404ce102054dfe", + "package_changed": true, + "result_label": "48h-plus-5m-submission-only", + "accepted_as_48h_result": false, + "no_experiments_review": "passed", + "original_results_preserved": true, + "publication_review": "/weka/oe-adapt-default/stevenc/science-speedrun-runs/molecular-pretraining-transfer-astra-finalize-5m-20261025e/publication-review.json", + "evaluation_decision": "reuse_existing_history_evaluation" +} diff --git a/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/finalization/submission/encoder.json b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/finalization/submission/encoder.json new file mode 100644 index 0000000000000000000000000000000000000000..addde27ff918e1620da27b08ab3603df531258f7 --- /dev/null +++ b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/finalization/submission/encoder.json @@ -0,0 +1,5 @@ +{ + "arch": "unimol2_compact128_poolnorm_82M", + "description": "from /workspace/research/candidates/quantum_long180k_cachepair30k_old262k_poolnorm/checkpoint.pt", + "user_dir": "user_dir" +} diff --git a/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/submissions/S014/user_dir/__init__.py b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/submissions/S014/user_dir/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..360220c77bff3f81a02c149cbbd8d27a5c1340a2 --- /dev/null +++ b/tasks/molecular-pretraining-transfer/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a/submissions/S014/user_dir/__init__.py @@ -0,0 +1,48 @@ +"""82M Uni-Mol2 variant reallocating pair capacity to the atom FFN. + +Self-contained package implementation; all weights must be pretrained locally. +""" +from types import MethodType + +import torch +import torch.nn.functional as F +from unicore.models import register_model, register_model_architecture +from unimol2.models.unimol2 import UniMol2Model, base_architecture + + +def factored_opm(self, a, b): + batch, nodes, hidden = a.shape + pair_dim = self.linear_out.out_features + weight = self.linear_out.weight.view(pair_dim, hidden, hidden) + projected = F.linear(a, weight.permute(0, 2, 1).reshape(pair_dim * hidden, hidden)) + result = torch.bmm(projected.view(batch, nodes * pair_dim, hidden), b.transpose(1, 2)) + return result.view(batch, nodes, pair_dim, b.size(1)).transpose(2, 3) + self.linear_out.bias + + +def normalize_output(module, inputs, output): + x, pair = output + return F.layer_norm(x, (x.size(-1),)), pair + + +@register_model('unimol2_compact_pair') +class CompactPairModel(UniMol2Model): + def __init__(self, args, dictionary=None): + super().__init__(args, dictionary) + for layer in self.encoder.layers: + layer.opm._opm = MethodType(factored_opm, layer.opm) + if getattr(args, 'compact_final_norm', False): + self.encoder.register_forward_hook(normalize_output) + + +@register_model_architecture('unimol2_compact_pair', 'unimol2_compact128_82M') +def compact_architecture(args): + args.pair_embed_dim = 128 + args.encoder_ffn_embed_dim = 2304 + args.compact_final_norm = False + base_architecture(args) + + +@register_model_architecture('unimol2_compact_pair', 'unimol2_compact128_poolnorm_82M') +def compact_normalized_architecture(args): + compact_architecture(args) + args.compact_final_norm = True diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/finalization/submission/provenance/member4/training/recovery/brief_before_E145.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/finalization/submission/provenance/member4/training/recovery/brief_before_E145.py new file mode 100644 index 0000000000000000000000000000000000000000..ac482e7e2e1c0c3199c6c7286031df7c45ce8881 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/finalization/submission/provenance/member4/training/recovery/brief_before_E145.py @@ -0,0 +1,34 @@ +"""Write a short, current recovery handoff; never modify training state.""" +import datetime +import json +from pathlib import Path + +R = Path('/workspace/research') +s = json.loads((R/'CURRENT_RESEARCH_STATE.json').read_text()) +lines = ['# Current recovery brief', '', datetime.datetime.now(datetime.timezone.utc).isoformat(), '', + 'Continuous research; no endpoint/final hand-in. One H10080GB,22CPUs,224GiB requested RAM; no network or pretrained assets. Do not inspect credentials or spawn agents.', '', + '## Published', '', json.dumps(s['published']), '', '## Pending selection', '', + json.dumps(s.get('next_candidate',{})), '', json.dumps({k:v for k,v in s.get('selection_probes',{}).items() if k in ['E128','E130','E132','E133','E134','E135','E136','E137','E138','E139','E140','E141','E142','E143']}), '', '## Active and queued training', ''] +for name, job in s.get('external_jobs',{}).items(): + if job['status'] not in ['running','waiting']: + continue + lines += [f'- {name}: {job["status"]}; receipt {job["receipt"]}; queue PID snapshot {job["queue_pid_at_snapshot"]}; children {job["child_pids_at_snapshot"]}.', + f' Last logged record: {json.dumps(job["last_phase_record"])}', + f' Complete recovery: {job["complete_recovery_checkpoint"]}; latest EMA: {job["latest_saved_ema"]}.'] +lines += ['', '## Recovery rules', '', + '- PIDs and launch-script dependencies are snapshots. After an operator restart, restore running jobs from each complete recovery.pt, preserving optimizer/EMA/RNG/prefetched batch and original schedules. Rewire waiting jobs to the newly launched dependency PIDs; do not blindly rerun old launch scripts.', + '- Waiting dependency chain: weekly_replication_control after long_seasonal; weekly_replication_candidate after that control; lowfreq_windows after that candidate; long_seasonal_replication after lowfreq_windows. phase_joint waits for random_capacity_512 final96000; seasonal_dispersion waits for phase_joint final12000; seasonal_history waits for seasonal_dispersion final12000. random_capacity_original_ar waits for random_capacity_1024 final96000; log_horizon waits for long_seasonal_replication final12000; seasonal_width waits for seasonal_history final12000; random_capacity_long_seasonal waits for both E94halfLR and E79wide final96000 and replaces only the E94allocation. visibility_curriculum waits for E110full and E79wide final96000 and replaces only the E110allocation; preserve --visibility-curriculum on any resume. direct_trend_head waits for E129seasonal_width final12000 and replaces that allocation. random_capacity_deep waits for E122originalAR and E79wide final96000, replacing only the E122allocation.', + '- E121 history-aware ensemble runtime is prepared at history_three_patch_ensemble; synthetic audit checks exact standalone composition and ordinary legacy equality. It also applies member finite cleanup before averaging, correcting a pre-existing extreme-value discrepancy. Use this separate publisher and complete public replay before any E121 publication; E130 now publishes four members using four_member_ensemble/publish.py, retaining both finite cleanup and per-member history support. Use that publisher for four-member packages.', + '- E126 compiled_teacher_trial completed its mandatory17000stop; do not resume it. It preserved original96000 LR schedule from immutable distill_ensemble_recovery016000.pt. Original E101 stays active. Compiler takeover rejected: max cutoff drift0.001964 exceeded0.0005 tolerance, with only3to5percent warm shared-device timing gain. No coefficient change selected. E125 component ablations completed; both paths help. E127 finite-member numerical fix is published with all97predictions bitwise unchanged; do not republish it. E128 dispersion transfers6000 and12000 both lost full validation; neither is published. E130 equal-quarter package is the current best. E132 checks scheduled E79wide96000 as the fourth member; E133 passed both source replication gates but its fixed averaged correction failed the ensemble gate (2of4positive, mean-0.0000154271); no full replay or averaging sweep. Receipts are indexed in CURRENT_RESEARCH_STATE.json.', + '- E138 learned gate uses immutable /workspace/research/gating_experts_E130, descriptorfa97880d..., even if submission improves. CPU/GPU/recovery/publicruntime/relocation audits passed; active since10:27 after E123final12000. Check queue receipt and rewire dependencies after restart. Training must preserve --gate-package and restore complete optimizer/EMA/RNG/prefetched batch. No expert tensors enter the gate optimizer. Gate publisher is ensemble_gate/publish.py. E139width primary6k is published at0.3843356309048914 after allfour diagnostics/fullsuite/bitwisecomposition;12k requires matched-source gate. E140loader-only runtime published10:24:27 after full97bitwiseidentity/relocation; sameE139weights/score, predictSHA4de2b53c.... Sharedfour-memberruntime nowmeta-loads; newquadcandidates useit. Gate trainer/experts loader unchanged. E132final fourthmember fullsuite complete but rejected:0.384297081868 below E1390.384335630905. E142width6+final quartet passeddiagnostics; persistent fresh_capacity_duration/full_pipeline.py runs its complete suite, no automaticpromotion. E13912ktransfer also passed3of4vscurrent andis inwidth12fullsuite. E144fixed direct-trend transfer on frozenwidth6base: width_trend_transfer/run.py primary6active, conditional12sourcegate; no fullsuite unless diagnosticgatepasses. E145fresh146Mfull-corpusbuilding4x sampler audited andqueued afterE131final96000, sameE110seed307/B48/LR1e-4/96k; resumecompleteRNG/optimizerstate, no newgenerator. E143low-frequency synthetic prefix-origin study CPU/GPU/recovery passed; queued29836 afterE13828517final12000, launcher persistent61462. Sampler state needs no extra RNG. E141matched146Mpatch16/patch8 continuations seed809/B32/LR2e-5/12k passed CPU/GPUaudits, queued29105control afterE13626926final12000 then29107candidate aftercontrolfinal12000. Same random_capacity model/data code, candidate folded ownE79wide96checkpoint. Preserve fullrecovery/compiledloss andsequentialdependency after restart. Use seasonal_width_transfer/promote.py only after better full replay and all checks.', + '- E101 distillation teacher is immutable /workspace/research/distill_teacher_E96, even after later publications. Do not substitute the current submission.', + '- Restore compiler_cache_backup to the same /tmp cache paths before restarting compiled trainers. Exact environment and commands are in CURRENT_RESEARCH_STATE.json.', + '- E105 output collision is documented in incidents/stratified_volume_output_collision. Correct E105 output is runs/stratified_volume. E95final and2k..12k weights survive, but E95optimizer recovery and original1k weights were lost. Do not resume completed E95.', + '- All previous negative/stopped branches stay stopped unless a new matched experiment explicitly revisits them. Never retrain the supplied baselines.', + '- Current training-source publisher archives all Python modules from explicitly declared directories, fixing earlier omissions of spectral.py and schedules.py. Complete-source members carry a -complete suffix when rebuilt. Runtime/weight hashes were unchanged.', + '- Full evaluation and GPU diagnostics use .evaluation.lock; the six main trainers share the one H100. The bounded E126 seventh-process probe completed17000 and should remain stopped. Dataset windows under data/valid and all earlier cutoffs are selection only, never training.', + '- Master journal direct_v1/EXPERIMENTS.md, chronological SESSION_20261023_PROGRESS.md, and RESEARCH_IDEAS.md contain decisions and rejected candidates. Recheck live processes and latest reports before acting.', + '', '## Time anchor', '', + 'Latest operator recovery allowance:151596research seconds at2026-10-23T02:45:51UTC. Pauses/preflight excluded. The goal remains active and has no requested token budget.', ''] +(R/'RECOVERY_BRIEF.md').write_text('\n'.join(lines)) +print('Wrote RECOVERY_BRIEF.md with '+str(sum(j['status'] in ['running','waiting'] for j in s.get('external_jobs',{}).values()))+' active/queued jobs.') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S001/EXPERIMENTS.md b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S001/EXPERIMENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..9798167c9068d646c437515860d88b3edc48ca4d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S001/EXPERIMENTS.md @@ -0,0 +1,9 @@ +# Experiments + +## Bootstrap +- Hypothesis: preserve a runnable package while the first research model trains. +- Model: provided Seasonal Naive formula; no learned parameters or training data. +- Seed: deterministic; compute: none. +- Validation: reference only, no new score claimed. +- Checkpoint hash: not applicable. +- Outcome: provisional package, to be replaced by a trained candidate. diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S001/README.md b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S001/README.md new file mode 100644 index 0000000000000000000000000000000000000000..72fcdd12c29d4ef560d66e471ff03e6b9bd2fd44 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S001/README.md @@ -0,0 +1,16 @@ +# Baseline: Seasonal Naive + +The statistical reference that defines the reward's normalizer. The forecast repeats the last +observed season, at the season length GIFT-Eval assigns each frequency. Quantiles come from the +in-sample seasonal-difference errors, which is how statsforecast's `SeasonalNaive` computes +them. It has no parameters and no training. The package follows the contract as it stands: + +```bash +bash /workspace/baseline/seasonal_naive/infer.sh /workspace/data/valid/input /workspace/research/sn-valid +python3 /workspace/evaluation/score.py --truth /workspace/data/valid/truth --output /workspace/research/sn-valid \ + --baseline /workspace/evaluation/seasonal_naive_reference_valid.json --report /workspace/research/sn-valid.json +``` + +`predict_statsforecast.py` is the same forecaster through statsforecast itself. It was used to +cross-check the numpy port, and it needs statsforecast, which this image does not install. Replayed on the test configurations it reproduces the board's +Seasonal Naive row (`RESULTS.md`), so its reward is 0 up to rounding. diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S001/RESULTS.md b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S001/RESULTS.md new file mode 100644 index 0000000000000000000000000000000000000000..6753c3d4d75562d3b1377c7c8571d92139276d0a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S001/RESULTS.md @@ -0,0 +1,11 @@ +# Seasonal Naive: reproduced results + +This package was replayed by the task's independent verifier, in the task's images, on all 97 +GIFT-Eval configurations (326,490 instances): + +| | relative MASE | relative WQL | reward | +| --- | ---: | ---: | ---: | +| Seasonal Naive (this directory) | 1.000 | 0.985 | 0.0075 | + +Relative MASE is exactly 1 by construction. The task author's replay gave the same 0.0075. A trivial package that forecasts the context's empirical quantiles scores +0.0. diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S001/infer.sh b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S001/infer.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba76e01e24bc0d8d75e59475aec9d5b4f62b9aa4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S001/infer.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +# timeseries-forecast/v1 entry point: bash infer.sh INPUT_DIR OUTPUT_DIR +set -euo pipefail +exec python3 "$(dirname "$(readlink -f "$0")")/predict.py" "$1" "$2" diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S001/model_manifest.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S001/model_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..f6d019fa7e26ad879d40862bc767ea5de0890bd9 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S001/model_manifest.json @@ -0,0 +1,9 @@ +{ + "name": "bootstrap-seasonal-naive", + "contract": "timeseries-forecast/v1", + "parameters": 0, + "pretrained_assets": [], + "sources_used": [], + "note": "statistical reference, not a submission; defines the per-config normalizer of the reward", + "notes": "Provisional contract-complete package while the first from-scratch candidate trains. No pretrained assets." +} diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S001/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S001/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..cddee9fdb70a40c760b6b44f379706a8c86fcfd6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S001/predict.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""Seasonal Naive reference package for timeseries-forecast/v1 (numpy re-implementation of the leaderboard's model). + +The leaderboard's `Seasonal_Naive` row (gift-eval notebooks/naive.ipynb) is +statsforecast `SeasonalNaive(season_length=m)` with prediction intervals at +levels {20, 40, 60, 80} mapped onto the nine deciles, on the history with +NaN filled by gluonts `LastValueImputation`. Its formulas (statsforecast +2.1.1, utils._seasonal_naive / _calculate_sigma / _calculate_intervals): + + mean[k] = y[n - m + (k mod m)] (last season tiled) + sigma = sqrt( sum_{t>=m} (y[t] - y[t-m])^2 / (n - m) ) + sigma_h[k]= sigma * sqrt(floor(k / m) + 1) + q_level = mean +- z(level) * sigma_h, z(level) = Phi^-1(0.5 + level/200) + decile q -> level round(200 (max(q, 1-q) - 0.5)); q = 0.5 -> mean + +`predict_statsforecast.py` is the original statsforecast-backed version; both +give identical files on the smoke split (docs/validation/). This version runs the +full test split in about a minute. Because packages only see the last +16,384 observations (contract.md), sigma is computed on that window; the +leaderboard used the full history. + + bash infer.sh INPUT_DIR OUTPUT_DIR +""" +import json +import math +import sys +from pathlib import Path + +import numpy as np + +HERE = Path(__file__).resolve().parent +for cand in (HERE.parent.parent / "evaluation", Path("/workspace/evaluation"), HERE): + if (cand / "ts_io.py").exists(): + sys.path.insert(0, str(cand)); break +import ts_io # noqa: E402 + + +def norm_ppf(p: float) -> float: + """Inverse standard normal CDF (Acklam's rational approximation refined with one Newton step).""" + a = [-3.969683028665376e+01, 2.209460984245205e+02, -2.759285104469687e+02, 1.383577518672690e+02, -3.066479806614716e+01, 2.506628277459239e+00] + b = [-5.447609879822406e+01, 1.615858368580409e+02, -1.556989798598866e+02, 6.680131188771972e+01, -1.328068155288572e+01] + c = [-7.784894002430293e-03, -3.223964580411365e-01, -2.400758277161838e+00, -2.549732539343734e+00, 4.374664141464968e+00, 2.938163982698783e+00] + d = [7.784695709041462e-03, 3.224671290700398e-01, 2.445134137142996e+00, 3.754408661907416e+00] + if p < 0.02425: + q = math.sqrt(-2 * math.log(p)); x = (((((c[0]*q+c[1])*q+c[2])*q+c[3])*q+c[4])*q+c[5]) / ((((d[0]*q+d[1])*q+d[2])*q+d[3])*q+1) + elif p > 1 - 0.02425: + q = math.sqrt(-2 * math.log(1 - p)); x = -(((((c[0]*q+c[1])*q+c[2])*q+c[3])*q+c[4])*q+c[5]) / ((((d[0]*q+d[1])*q+d[2])*q+d[3])*q+1) + else: + q = p - 0.5; r = q * q + x = (((((a[0]*r+a[1])*r+a[2])*r+a[3])*r+a[4])*r+a[5])*q / (((((b[0]*r+b[1])*r+b[2])*r+b[3])*r+b[4])*r+1) + e = 0.5 * math.erfc(-x / math.sqrt(2)) - p + return x - e * math.sqrt(2 * math.pi) * math.exp(x * x / 2) + + +Z = {q: (0.0 if q == 0.5 else norm_ppf(0.5 + round(200 * (max(q, 1 - q) - 0.5)) / 200) * (1 if q > 0.5 else -1)) for q in ts_io.QUANTILE_LEVELS} + + +def last_value_impute(x: np.ndarray) -> np.ndarray: + """gluonts LastValueImputation on a (R, T) array: forward-fill; leading NaNs take the first finite value; all-NaN rows -> 0.""" + x = x.astype(np.float32).copy() + finite = np.isfinite(x) + idx = np.where(finite, np.arange(x.shape[1])[None, :], -1) + idx = np.maximum.accumulate(idx, axis=1) + first = np.argmax(finite, axis=1) + out = np.where(idx >= 0, np.take_along_axis(x, np.maximum(idx, 0), axis=1), x[np.arange(len(x)), first][:, None]) + out[~finite.any(axis=1)] = 0.0 + return out + + +def seasonal_naive(y: np.ndarray, m: int, h: int): + """y (R, T) imputed float32 -> mean (R, h), sigma_h (R, h) as float64 (statsforecast computes in the input dtype; float32 here).""" + y = y.astype(np.float32) + n = y.shape[1] + season = np.full((len(y), m), np.nan, np.float32) + avail = min(m, n) + if n < m: + season[:, m - avail:] = y[:, -avail:] + else: + season[:, :avail] = y[:, -avail:] + mean = np.tile(season, (1, math.ceil(h / m)))[:, :h] + if n > m: + res = y[:, m:] - y[:, :-m] + sigma = np.sqrt(np.nansum(res.astype(np.float32) ** 2, axis=1) / (n - m)) + else: + sigma = np.zeros(len(y), np.float32) + k = np.floor(np.arange(h) / m) + sigma_h = sigma[:, None] * np.sqrt(k + 1)[None, :] + return mean, sigma_h + + +def run_config(case: ts_io.CaseFile, out_path: Path, chunk_elems: int = 50_000_000): + """Process instances in chunks (rows x max length <= chunk_elems floats) so memory stays flat on the large configs.""" + L, m, D = case.prediction_length, int(case.meta["seasonality"]), case.n_variates + mean = np.zeros((case.n * D, L), np.float32); quant = np.zeros((case.n * D, len(ts_io.QUANTILE_LEVELS), L), np.float32) + order = np.argsort(case.context_length, kind="stable") # similar lengths together -> less padding + T_max = int(case.context_length.max()) + rows_per_chunk = max(1, chunk_elems // (T_max * D)) + values = case._f["values"] + for s in range(0, case.n, rows_per_chunk): + inst = order[s:s + rows_per_chunk] + T = int(case.context_length[inst].max()) + rows = np.full((len(inst) * D, T), np.nan, np.float32) + for r, i in enumerate(inst): + ctx = values[case.offsets[i]:case.offsets[i + 1]].reshape(D, -1) + rows[r * D:(r + 1) * D, T - ctx.shape[1]:] = ctx + y = last_value_impute(rows) + # rows were left-padded with NaN to a common length and the imputation turned that padding into the first + # value, which statsforecast never saw: compute per distinct length so sigma uses exactly the given history. + lengths = np.repeat(case.context_length[inst], D) + flat = np.repeat(inst, D) * D + np.tile(np.arange(D), len(inst)) + for length in np.unique(lengths): + sel = np.nonzero(lengths == length)[0] + mu, sh = seasonal_naive(y[sel, T - length:], m, L) + mu = np.where(np.isfinite(mu), mu, y[sel, -1:].repeat(L, axis=1)) # history shorter than a season: last value + mean[flat[sel]] = mu + quant[flat[sel]] = np.stack([mu + Z[q] * sh for q in ts_io.QUANTILE_LEVELS], axis=1).astype(np.float32) + ts_io.write_prediction_file(out_path, mean.reshape(case.n, D, L), quant.reshape(case.n, D, len(ts_io.QUANTILE_LEVELS), L), {"model": "seasonal_naive_reference"}) + + +def main(): + inp, outp = Path(sys.argv[1]), Path(sys.argv[2]) + index = json.loads((inp / "index.json").read_text()) + for cfg in index["configs"]: + case = ts_io.CaseFile(inp / "cases" / f"{cfg['config_id']}.h5") + run_config(case, outp / "cases" / f"{cfg['config_id']}.h5") + case.close() + print(f" {cfg['config_id']}: {cfg['n_instances']} instances", file=sys.stderr) + (outp / "model_manifest.json").write_text((HERE / "model_manifest.json").read_text()) + + +if __name__ == "__main__": + main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S001/predict_statsforecast.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S001/predict_statsforecast.py new file mode 100644 index 0000000000000000000000000000000000000000..05162826ee6739015e21c25a84bee28455a02de2 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S001/predict_statsforecast.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +"""Seasonal Naive reference package for timeseries-forecast/v1. + +Reproduces the leaderboard's `Seasonal_Naive` row (gift-eval notebooks/naive.ipynb): +statsforecast `SeasonalNaive(season_length=m)` with prediction intervals at +levels {20, 40, 60, 80} mapped to the nine deciles, NaN history imputed with +the last observed value (gluonts `LastValueImputation`), one model per +univariate series (multivariate configs are flattened per variate). Its +per-config MASE / WQL through the task grader define the normalizer +`evaluation/seasonal_naive_reference.json`. + + bash infer.sh INPUT_DIR OUTPUT_DIR +""" +import json +import sys +from pathlib import Path + +import numpy as np +import pandas as pd +from statsforecast import StatsForecast +from statsforecast.models import SeasonalNaive + +HERE = Path(__file__).resolve().parent +for cand in (HERE.parent.parent / "evaluation", Path("/workspace/evaluation"), HERE): + if (cand / "ts_io.py").exists(): + sys.path.insert(0, str(cand)); break +import ts_io # noqa: E402 + +LEVELS = [20, 40, 60, 80] + + +def last_value_impute(x: np.ndarray) -> np.ndarray: + """gluonts LastValueImputation: forward-fill, with leading NaNs replaced by the first finite value (or 0).""" + x = x.astype(np.float32).copy() + if not np.isnan(x).any(): + return x + finite = np.isfinite(x) + if not finite.any(): + return np.zeros_like(x) + idx = np.where(finite, np.arange(len(x)), -1) + np.maximum.accumulate(idx, out=idx) + first = np.argmax(finite) + filled = np.where(idx >= 0, x[np.maximum(idx, 0)], x[first]) + return filled.astype(np.float32) + + +def quantile_columns(level_cols, prediction_length): + """Map statsforecast lo/hi interval columns to the nine deciles in order (gluonts StatsForecastPredictor).""" + out = np.zeros((len(ts_io.QUANTILE_LEVELS), prediction_length), np.float64) + for j, q in enumerate(ts_io.QUANTILE_LEVELS): + interval = round(200 * (max(q, 1 - q) - 0.5)) + side = "hi" if q > 0.5 else "lo" + out[j] = level_cols["mean"] if interval == 0 else level_cols[f"{side}-{interval}"] + return out + + +def run_config(case: ts_io.CaseFile, out_path: Path): + L, m, D = case.prediction_length, int(case.meta["seasonality"]), case.n_variates + freq = ts_io._pandas_freq(case.meta["freq"]) + frames, keys = [], [] + for i, ctx in enumerate(case.contexts()): + for d in range(D): + y = last_value_impute(ctx[d]) + uid = f"{i}_{d}" + frames.append(pd.DataFrame({"unique_id": uid, "ds": pd.date_range(end=pd.Timestamp(case.forecast_start[i]), periods=len(y) + 1, freq=freq)[:-1].to_numpy(), "y": y})) + keys.append((i, d)) + sf = StatsForecast(models=[SeasonalNaive(season_length=m)], freq=freq, n_jobs=1) + res = sf.forecast(df=pd.concat(frames, ignore_index=True), h=L, level=LEVELS) + if "unique_id" not in res.columns: + res = res.reset_index() + cols = [c for c in res.columns if c.startswith("SeasonalNaive")] + mean = np.zeros((case.n, D, L), np.float32); quant = np.zeros((case.n, D, len(ts_io.QUANTILE_LEVELS), L), np.float32) + grouped = {uid: g for uid, g in res.groupby("unique_id", sort=False)} + for (i, d) in keys: + g = grouped[f"{i}_{d}"] + assert len(g) == L + level_cols = {"mean": g["SeasonalNaive"].to_numpy(np.float64)} + for c in cols: + if "-" in c: + level_cols[c.split("-", 1)[1]] = g[c].to_numpy(np.float64) + mean[i, d] = level_cols["mean"] + quant[i, d] = quantile_columns(level_cols, L) + ts_io.write_prediction_file(out_path, mean, quant, {"model": "seasonal_naive_reference"}) + + +def main(): + inp, outp = Path(sys.argv[1]), Path(sys.argv[2]) + index = json.loads((inp / "index.json").read_text()) + for cfg in index["configs"]: + case = ts_io.CaseFile(inp / "cases" / f"{cfg['config_id']}.h5") + run_config(case, outp / "cases" / f"{cfg['config_id']}.h5") + case.close() + print(f" {cfg['config_id']}: {cfg['n_instances']} instances", file=sys.stderr) + (outp / "model_manifest.json").write_text(json.dumps({"name": "seasonal_naive_reference", "contract": ts_io.CONTRACT, + "parameters": 0, "pretrained_assets": [], "sources_used": []}, indent=1)) + + +if __name__ == "__main__": + main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S001/requirements.txt b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S001/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..ca733199990e5dc8e6a90509cc691f00ab8e9f5d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S001/requirements.txt @@ -0,0 +1,12 @@ +# Runtime pins recorded from the contributor's working environment on 2026-09-17 (Python 3.11). +# torch comes from the pytorch/pytorch:2.14.0-cuda12.6-cudnn9-runtime base image (cu130 needs driver >= 580). +torch==2.14.0 +numpy==2.4.6 +h5py==3.16.0 +pandas==2.3.3 +scipy==1.17.1 +pyarrow==25.0.1 +huggingface-hub==0.36.2 +einops==0.8.2 +safetensors==0.8.0 +pytest==9.1.1 diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S001/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S001/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S001/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/EXPERIMENTS.md b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/EXPERIMENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..7e88c34b7a07cb6e861cc0ec3432e11518ca1384 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/EXPERIMENTS.md @@ -0,0 +1,402 @@ +# Experiments + +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. + +## E0: contract bootstrap +- Hypothesis: maintain a runnable package while training the first candidate. +- Changed factor: none; provided Seasonal Naive formula, with no learned parameters. +- Seed: deterministic. Measured compute: no training. +- Checkpoint hash: not applicable. +- Outcome: provisional package published with atomic directory exchange. + +## E1: direct long-horizon quantile forecasting +- Hypothesis: a direct horizon objective and explicit seasonal context features reduce long-horizon median drift and the underestimation of uncertainty from short-patch autoregression. +- 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. +- 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. +- 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. +- Synthetic generator: newly generated damped trends, Fourier seasonality, AR noise, intermittent demand and changepoints. No downloaded synthetic assets. +- 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. +- 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. +- Completed 12,000 steps in 349.9 seconds on one H100. Measured group skills, checkpoint hashes and outcomes are recorded below. + +## Known limits and next decisions +- This first run jointly changes the architecture and objective; it does not isolate their individual causal contributions. +- 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. +- 10-second daily seasonality exceeds the 4,096-point encoder window. Longer fixed context summaries are a planned ablation after initial diagnostics. + +## E1 control, step 0, screening +- Checkpoint SHA-256: `81be0f24c44a558e29dffcabb4ac15ae3c944e1afe2860851683d155f920ec2f`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 7.037512302398682 seconds. +- Overall skill 0.000921; relative MASE 1.194471; relative WQL 0.835649. +- term skill: long=0.0466, medium=0.0284, short=-0.0280. +- 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. +- 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. +- variates skill: multivariate=0.0528, univariate=-0.0424. +- Outcome: Untrained seasonal-mixture prior barely exceeds Seasonal Naive overall and fails badly on 10-second and low-frequency configurations. + +## E1 step 1000, seed 17, screening +- Checkpoint SHA-256: `ebdd9eaa223c2bb6e38b8faec6f465a227fcd735b654a26f3b617a757addb0d3`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 6.581991195678711 seconds. +- Overall skill 0.210443; relative MASE 0.932765; relative WQL 0.668336. +- term skill: long=0.2339, medium=0.2517, short=0.1848. +- 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. +- 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. +- variates skill: multivariate=0.2140, univariate=0.2076. +- Outcome: Improves the control by 0.2095 screening skill after about 34 seconds on one H100. Selected for first neural publication and full validation. + +## E1 step 1000, full validation +- Checkpoint SHA-256: `see model_manifest.json`. +- Evaluation: 97 configurations, 151170 instances, 0 failed configurations; not separately timed seconds. +- Overall skill 0.206132; relative MASE 0.931220; relative WQL 0.676774. +- term skill: long=0.2265, medium=0.2444, short=0.1829. +- 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. +- 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. +- variates skill: multivariate=0.2097, univariate=0.2033. +- 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. + +## E1 step 2000, screening +- Checkpoint SHA-256: `a513ac4f03aceb93a860d5e5eca70010c0101fdea794df4a9a8ae472647fb9c9`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 5.98806357383728 seconds. +- Overall skill 0.249671; relative MASE 0.890745; relative WQL 0.632048. +- term skill: long=0.2727, medium=0.2872, short=0.2257. +- 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. +- 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. +- variates skill: multivariate=0.2588, univariate=0.2423. +- Outcome: Improves screening skill to 0.2497 after 66.8 seconds of training; candidate for replacement. + +## E1 step 3000, screening +- Checkpoint SHA-256: `74da538d2365426496a12c965c0c0cdc1d3962a798bd2e2c5fed950c1f663f30`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 6.051600933074951 seconds. +- Overall skill 0.246085; relative MASE 0.894210; relative WQL 0.635631. +- term skill: long=0.2835, medium=0.2774, short=0.2187. +- 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. +- 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. +- variates skill: multivariate=0.2552, univariate=0.2388. +- Outcome: Slight regression to 0.2461 relative to step 2000. Negative checkpoint-selection result; not selected. + +## E2 fixed longer-history feature ablation, step 2000 seed 17 +- Checkpoint SHA-256: `25ac85db67c041c92870e2ea2e8b198bb768f5c5ed64f42b78d6ec207ffe3a18`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 6.066685438156128 seconds. +- Overall skill 0.249089; relative MASE 0.890661; relative WQL 0.633088. +- term skill: long=0.2741, medium=0.2855, short=0.2248. +- 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. +- 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. +- variates skill: multivariate=0.2572, univariate=0.2426. +- 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. + +## E1 step 4000, screening +- Checkpoint SHA-256: `f1b4e5f798688a56a693daf799fa21e69ec21c9c1710cae8dafbdb833c9ee069`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 5.961170196533203 seconds. +- Overall skill 0.266471; relative MASE 0.874789; relative WQL 0.615080. +- term skill: long=0.2537, medium=0.2846, short=0.2643. +- 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. +- 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. +- variates skill: multivariate=0.2648, univariate=0.2678. +- Outcome: Best ungated checkpoint so far; improved short-horizon performance, with some long-horizon regression. + +## E1 step 6000, screening +- Checkpoint SHA-256: `f38cdb1b49938007c20bdfdfa7c4fc7d7aba6516192f388f37088891411eab7f`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 6.802650451660156 seconds. +- Overall skill 0.258313; relative MASE 0.878300; relative WQL 0.626324. +- term skill: long=0.2951, medium=0.3035, short=0.2254. +- 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. +- 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. +- variates skill: multivariate=0.2482, univariate=0.2662. +- Outcome: Overall regression relative to step 4000 despite improvement on medium and long horizons. Not selected by overall skill. + +## E3 seasonal confidence gate, step 4000 seed 17 +- Checkpoint SHA-256: `f1b4e5f798688a56a693daf799fa21e69ec21c9c1710cae8dafbdb833c9ee069`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 9.475942373275757 seconds. +- Overall skill 0.301779; relative MASE 0.827721; relative WQL 0.588981. +- term skill: long=0.3338, medium=0.3656, short=0.2627. +- 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. +- 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. +- variates skill: multivariate=0.3379, univariate=0.2716. +- 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. + +## E3 step 4000 gate, full validation +- Checkpoint SHA-256: `see model_manifest.json`. +- Evaluation: 97 configurations, 151170 instances, 0 failed configurations; not separately timed seconds. +- Overall skill 0.296168; relative MASE 0.830141; relative WQL 0.596742. +- term skill: long=0.3262, medium=0.3621, short=0.2569. +- 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. +- 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. +- variates skill: multivariate=0.3332, univariate=0.2652. +- 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. + +## E1 step 8000, seed 17, ungated screening +- Checkpoint SHA-256: `ebbae91cb50acf1b1436fcbcdce1637195dd6e5006580d3d8e94a4e102aed0ad`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 5.500704050064087 seconds. +- Overall skill 0.276275; relative MASE 0.864160; relative WQL 0.606113. +- term skill: long=0.2954, medium=0.3094, short=0.2557. +- 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. +- 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. +- variates skill: multivariate=0.2735, univariate=0.2785. +- Outcome: Included in final checkpoint selection; compare to weight-averaged result below. + +## E1 step 8000, seed 17, gated screening +- Checkpoint SHA-256: `ebbae91cb50acf1b1436fcbcdce1637195dd6e5006580d3d8e94a4e102aed0ad`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 6.228765964508057 seconds. +- Overall skill 0.312772; relative MASE 0.813977; relative WQL 0.580216. +- term skill: long=0.3671, medium=0.3752, short=0.2645. +- 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. +- 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. +- variates skill: multivariate=0.3530, univariate=0.2790. +- Outcome: Included in final checkpoint selection; compare to weight-averaged result below. + +## E1 step 10000, seed 17, ungated screening +- Checkpoint SHA-256: `3845afb6035396030b9a5182037287db092814d68caa4c96a7c415eb1d3b3a0a`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 6.094600439071655 seconds. +- Overall skill 0.285838; relative MASE 0.855761; relative WQL 0.595993. +- term skill: long=0.2974, medium=0.3249, short=0.2658. +- 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. +- 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. +- variates skill: multivariate=0.2917, univariate=0.2812. +- Outcome: Included in final checkpoint selection; compare to weight-averaged result below. + +## E1 step 10000, seed 17, gated screening +- Checkpoint SHA-256: `3845afb6035396030b9a5182037287db092814d68caa4c96a7c415eb1d3b3a0a`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 7.704133749008179 seconds. +- Overall skill 0.317743; relative MASE 0.805746; relative WQL 0.577695. +- term skill: long=0.3656, medium=0.3815, short=0.2718. +- 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. +- 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. +- variates skill: multivariate=0.3600, univariate=0.2821. +- Outcome: Included in final checkpoint selection; compare to weight-averaged result below. + +## E1 step 12000, seed 17, ungated screening +- Checkpoint SHA-256: `629130a69f89561219b286c1e805d89b8b4662fce0e4b75e731e8764d9066e98`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 5.807793855667114 seconds. +- Overall skill 0.284471; relative MASE 0.856118; relative WQL 0.598027. +- term skill: long=0.2877, medium=0.3155, short=0.2710. +- 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. +- 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. +- variates skill: multivariate=0.2854, univariate=0.2837. +- Outcome: Included in final checkpoint selection; compare to weight-averaged result below. + +## E1 step 12000, seed 17, gated screening +- Checkpoint SHA-256: `629130a69f89561219b286c1e805d89b8b4662fce0e4b75e731e8764d9066e98`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 7.750269889831543 seconds. +- Overall skill 0.315453; relative MASE 0.812477; relative WQL 0.576760. +- term skill: long=0.3585, medium=0.3794, short=0.2715. +- 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. +- 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. +- variates skill: multivariate=0.3552, univariate=0.2820. +- Outcome: Included in final checkpoint selection; compare to weight-averaged result below. + +## E4 stochastic weight average, seed 17, gated screening +- Checkpoint SHA-256: `a346a09ba0b8d196b58acc22a76f7944109b2bba04ea2b7cf7566de24aa2d8db`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 7.737564325332642 seconds. +- Overall skill 0.320612; relative MASE 0.803931; relative WQL 0.574139. +- term skill: long=0.3654, medium=0.3823, short=0.2769. +- 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. +- 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. +- variates skill: multivariate=0.3557, univariate=0.2913. +- 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. + +## E3 confidence and quantile-width sweep +- Fixed global settings, selected only on validation; no model updates. Seed and checkpoint: E1 step 8000, seed 17. +- Measured CPU time: 10.7 seconds. The original threshold 0.25 and width multiplier 1.0 won; no tuned change was adopted. +- (variance threshold, width multiplier) (0.25, 1.0): skill 0.312772; term skills {'short': 0.2645319168347662, 'medium': 0.37524061562171485, 'long': 0.36711552655262625}. +- (variance threshold, width multiplier) (0.5, 1.0): skill 0.311338; term skills {'short': 0.26128183571880415, 'medium': 0.3766834137570718, 'long': 0.36686872500364487}. +- (variance threshold, width multiplier) (0.25, 0.75): skill 0.310114; term skills {'short': 0.26357949467631236, 'medium': 0.3710044838302994, 'long': 0.36223509497654094}. +- (variance threshold, width multiplier) (0.1, 1.0): skill 0.309380; term skills {'short': 0.2645827018541862, 'medium': 0.3687788042390393, 'long': 0.3590704635989247}. +- (variance threshold, width multiplier) (0.25, 1.25): skill 0.308716; term skills {'short': 0.25806263726485956, 'medium': 0.3732424245969126, 'long': 0.3664492202082874}. +- (variance threshold, width multiplier) (0.5, 0.75): skill 0.308480; term skills {'short': 0.2599791649373039, 'medium': 0.3724274186615034, 'long': 0.36196930941343286}. +- (variance threshold, width multiplier) (0.5, 1.25): skill 0.307830; term skills {'short': 0.25575126666422066, 'medium': 0.3747816871597687, 'long': 0.3663051398261168}. +- (variance threshold, width multiplier) (0.1, 0.75): skill 0.306923; term skills {'short': 0.26386190560263856, 'medium': 0.3650190620286501, 'long': 0.35398875275507513}. +- (variance threshold, width multiplier) (0.1, 1.25): skill 0.305043; term skills {'short': 0.2579337472130613, 'medium': 0.36611831669487493, 'long': 0.3583403545682865}. +- (variance threshold, width multiplier) (1.0, 1.0): skill 0.300332; term skills {'short': 0.24300377373135085, 'medium': 0.37515035650362993, 'long': 0.3625716315021771}. +- (variance threshold, width multiplier) (1.0, 0.75): skill 0.297470; term skills {'short': 0.24163138399697548, 'medium': 0.37101264403024414, 'long': 0.3577626408389879}. +- (variance threshold, width multiplier) (1.0, 1.25): skill 0.296900; term skills {'short': 0.23759298244372884, 'medium': 0.3732464838258517, 'long': 0.3619922948184182}. +- (variance threshold, width multiplier) (0.0, 1.0): skill 0.276275; term skills {'short': 0.25565045294773825, 'medium': 0.30935443355536374, 'long': 0.29541709470756516}. +- (variance threshold, width multiplier) (0.0, 0.75): skill 0.274035; term skills {'short': 0.2552205537396286, 'medium': 0.30589300644316675, 'long': 0.289930620063797}. +- (variance threshold, width multiplier) (0.0, 1.25): skill 0.271354; term skills {'short': 0.2486798921582145, 'medium': 0.30569315727356094, 'long': 0.29429049771287774}. + +## E5 capacity and exponential averaging +- Hypothesis: increased capacity reduces residual errors after direct-horizon training; exponential weight averaging reduces checkpoint noise. +- 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)). +- 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. + +## E4 averaged small model, full validation +- Checkpoint SHA-256: `see model_manifest.json`. +- Evaluation: 97 configurations, 151170 instances, 0 failed configurations; not separately timed seconds. +- Overall skill 0.315325; relative MASE 0.806359; relative WQL 0.581354. +- term skill: long=0.3584, medium=0.3790, short=0.2715. +- 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. +- 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. +- variates skill: multivariate=0.3509, univariate=0.2856. +- 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. + +## E6 sign symmetry, averaged small model, seed 17 +- Checkpoint SHA-256: `a346a09ba0b8d196b58acc22a76f7944109b2bba04ea2b7cf7566de24aa2d8db`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 7.13059401512146 seconds. +- Overall skill 0.328463; relative MASE 0.794174; relative WQL 0.567837. +- term skill: long=0.3740, medium=0.3863, short=0.2861. +- 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. +- 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. +- variates skill: multivariate=0.3628, univariate=0.2998. +- 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. + +## E6 sign symmetry, averaged small model, full validation +- Checkpoint SHA-256: `see model_manifest.json`. +- Evaluation: 97 configurations, 151170 instances, 0 failed configurations; not separately timed seconds. +- Overall skill 0.323978; relative MASE 0.795773; relative WQL 0.574292. +- term skill: long=0.3666, medium=0.3832, short=0.2823. +- 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. +- 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. +- variates skill: multivariate=0.3586, univariate=0.2951. +- 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. + +## E7 coarse temporal resolution at inference, small averaged model +- Checkpoint SHA-256: `a346a09ba0b8d196b58acc22a76f7944109b2bba04ea2b7cf7566de24aa2d8db`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 8.896855354309082 seconds. +- Overall skill 0.320862; relative MASE 0.803289; relative WQL 0.574174. +- term skill: long=0.3616, medium=0.3660, short=0.2861. +- 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. +- 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. +- variates skill: multivariate=0.3567, univariate=0.2909. +- 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. + +## E8 median and predictable-series loss weighting +- Hypothesis: optimizing median error explicitly and weighting by context seasonal error aligns pretraining with MASE and quantile loss. +- Initial weights: E4 averaged small model, trained here from random initialization; no external pretrained assets. +- 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. +- 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. +- Compute: 272.9 seconds elapsed on the sole H100, shared concurrently with E5. Underlying initial pretraining used 349.9 seconds. + +## E8 step 1000, seed 31, symmetric screening +- Checkpoint SHA-256: `e7cb5c4b4f04ba1ca873bc725f5e4345874520a96cbd3f079e4f631fd3c46d50`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 7.978966474533081 seconds. +- Overall skill 0.331642; relative MASE 0.791898; relative WQL 0.564091. +- term skill: long=0.3735, medium=0.3891, short=0.2910. +- 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. +- 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. +- variates skill: multivariate=0.3652, univariate=0.3036. +- Outcome: EMA at 6000 is best overall and selected for full validation; raw checkpoints show greater variance. + +## E8 ema 1000, seed 31, symmetric screening +- Checkpoint SHA-256: `dab309aff5a3a28936391b84b3ebd9d5dfc208e53c1e1602e4f5c599e3004c33`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 8.16230034828186 seconds. +- Overall skill 0.332263; relative MASE 0.790121; relative WQL 0.564310. +- term skill: long=0.3745, medium=0.3873, short=0.2925. +- 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. +- 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. +- variates skill: multivariate=0.3653, univariate=0.3047. +- Outcome: EMA at 6000 is best overall and selected for full validation; raw checkpoints show greater variance. + +## E8 step 2000, seed 31, symmetric screening +- Checkpoint SHA-256: `111cf52c0662c60aebb44355135a65675a09d898995deeb4dd2f8f2b66339a0f`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 9.85259199142456 seconds. +- Overall skill 0.326318; relative MASE 0.796087; relative WQL 0.570097. +- term skill: long=0.3658, medium=0.3826, short=0.2873. +- 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. +- 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. +- variates skill: multivariate=0.3573, univariate=0.3006. +- Outcome: EMA at 6000 is best overall and selected for full validation; raw checkpoints show greater variance. + +## E8 ema 2000, seed 31, symmetric screening +- Checkpoint SHA-256: `5fa525d923b4af5949f2415cf0ad0b325dae7623f07aae06b3131bdbda08c209`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 14.634822130203247 seconds. +- Overall skill 0.332843; relative MASE 0.789360; relative WQL 0.563874. +- term skill: long=0.3745, medium=0.3875, short=0.2936. +- 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. +- 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. +- variates skill: multivariate=0.3645, univariate=0.3065. +- Outcome: EMA at 6000 is best overall and selected for full validation; raw checkpoints show greater variance. + +## E8 step 4000, seed 31, symmetric screening +- Checkpoint SHA-256: `8ce9867a6005c28005b32d163254c088279f2a46febeadc433b403aeffc29066`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 20.403828620910645 seconds. +- Overall skill 0.333292; relative MASE 0.789778; relative WQL 0.562816. +- term skill: long=0.3723, medium=0.3857, short=0.2961. +- 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. +- 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. +- variates skill: multivariate=0.3645, univariate=0.3073. +- Outcome: EMA at 6000 is best overall and selected for full validation; raw checkpoints show greater variance. + +## E8 ema 4000, seed 31, symmetric screening +- Checkpoint SHA-256: `e61535b34efac923328f1dd464f5ab8ab05913438f86125d8b933f1b166281d9`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 10.288180112838745 seconds. +- Overall skill 0.334221; relative MASE 0.787768; relative WQL 0.562681. +- term skill: long=0.3735, medium=0.3879, short=0.2964. +- 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. +- 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. +- variates skill: multivariate=0.3653, univariate=0.3084. +- Outcome: EMA at 6000 is best overall and selected for full validation; raw checkpoints show greater variance. + +## E8 step 6000, seed 31, symmetric screening +- Checkpoint SHA-256: `15833e7668d9cd11ed55a4820b4700d71c6f734415d11490c7e8beb654abfa12`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 21.2668559551239 seconds. +- Overall skill 0.334430; relative MASE 0.788174; relative WQL 0.562038. +- term skill: long=0.3762, medium=0.3886, short=0.2953. +- 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. +- 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. +- variates skill: multivariate=0.3660, univariate=0.3081. +- Outcome: EMA at 6000 is best overall and selected for full validation; raw checkpoints show greater variance. + +## E8 ema 6000, seed 31, symmetric screening +- Checkpoint SHA-256: `70a3768d667df75f0d6565e831cdca8cf7c179c8546252e5902f7b7ec68ab7aa`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 11.340764284133911 seconds. +- Overall skill 0.335038; relative MASE 0.787307; relative WQL 0.561630. +- term skill: long=0.3762, medium=0.3878, short=0.2968. +- 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. +- 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. +- variates skill: multivariate=0.3659, univariate=0.3094. +- Outcome: EMA at 6000 is best overall and selected for full validation; raw checkpoints show greater variance. + +## E9 neural context 512 for horizons <=128, seed 17 +- Checkpoint SHA-256: `a346a09ba0b8d196b58acc22a76f7944109b2bba04ea2b7cf7566de24aa2d8db`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 10.416622161865234 seconds. +- Overall skill 0.320871; relative MASE 0.803968; relative WQL 0.573675. +- term skill: long=0.3740, medium=0.3863, short=0.2718. +- 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. +- 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. +- variates skill: multivariate=0.3665, univariate=0.2822. +- 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. + +## E9 neural context 1024 for horizons <=128, seed 17 +- Checkpoint SHA-256: `a346a09ba0b8d196b58acc22a76f7944109b2bba04ea2b7cf7566de24aa2d8db`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 19.072535276412964 seconds. +- Overall skill 0.329251; relative MASE 0.796444; relative WQL 0.564891. +- term skill: long=0.3740, medium=0.3863, short=0.2876. +- 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. +- 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. +- variates skill: multivariate=0.3738, univariate=0.2915. +- 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. + +## E9 neural context 2048 for horizons <=128, seed 17 +- Checkpoint SHA-256: `a346a09ba0b8d196b58acc22a76f7944109b2bba04ea2b7cf7566de24aa2d8db`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 9.426023244857788 seconds. +- Overall skill 0.329063; relative MASE 0.794285; relative WQL 0.566744. +- term skill: long=0.3740, medium=0.3863, short=0.2872. +- 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. +- 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. +- variates skill: multivariate=0.3651, univariate=0.2989. +- 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. + +## E10 fixed 50/50 ensemble diagnostic +- Checkpoint SHA-256: `see model_manifest.json`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 4.082070589065552 seconds. +- Overall skill 0.332712; relative MASE 0.791350; relative WQL 0.562676. +- term skill: long=0.3746, medium=0.3901, short=0.2921. +- 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. +- 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. +- variates skill: multivariate=0.3658, univariate=0.3052. +- 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. + +## E8 EMA6000, full validation +- Checkpoint SHA-256: `see model_manifest.json`. +- Evaluation: 97 configurations, 151170 instances, 0 failed configurations; not separately timed seconds. +- Overall skill 0.330109; relative MASE 0.789610; relative WQL 0.568323. +- term skill: long=0.3687, medium=0.3851, short=0.2920. +- 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. +- 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. +- variates skill: multivariate=0.3616, univariate=0.3039. +- 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. + +## E11 matched corpus-coverage experiment +- Hypothesis: broader source coverage improves generalization after the initial model has plateaued. +- 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. +- 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. +- Runs share the single H100 with E5; CPU threads are limited to three per new trainer. Results and measured elapsed compute are pending. diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/README.md b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0024aa3a73fe3390c9e99c4d2bda154aa2b9b7a3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/README.md @@ -0,0 +1,5 @@ +# Direct seasonal quantile foundation forecaster + +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. + +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. diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/config.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/config.json new file mode 100644 index 0000000000000000000000000000000000000000..4edb170b2470e3843efb3106ebf6c5edab0857c4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/config.json @@ -0,0 +1,9 @@ +{ + "d": 256, + "heads": 8, + "enc_layers": 4, + "dec_layers": 3, + "patch": 32, + "max_context": 4096, + "max_horizon": 1024 +} diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/infer.sh b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/infer.sh new file mode 100644 index 0000000000000000000000000000000000000000..cd8b850fa281f16a1fdf4147cb8e3ce1412f2702 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/infer.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -euo pipefail +export OMP_NUM_THREADS=4 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=4 +exec python3 "$(dirname "$(readlink -f "$0")")/predict.py" "$1" "$2" diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/model.py new file mode 100644 index 0000000000000000000000000000000000000000..7a224cc12a159446a1e427b2052b53d1d1f7e83e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/model.py @@ -0,0 +1,142 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional(torch.arange(-nt,0,device=z.device),self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + q=self.query(base.reshape(b,h//p,p*9))+positional(torch.arange(h//p,device=z.device),self.d)[None]+emb + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + pin=torch.maximum(levels*err,(levels-1)*err).mean(-1) + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + return per.mean() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/model_manifest.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/model_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..330d2a39441197950243f4b3c518b42a93f8ffea --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/model_manifest.json @@ -0,0 +1,130 @@ +{ + "name": "direct-seasonal-quantile-v1-symmetric", + "contract": "timeseries-forecast/v1", + "parameters": 6758720, + "pretrained_assets": [], + "sources_used": [ + "gifteval_pretrain/BEIJING_SUBWAY_30MIN", + "gifteval_pretrain/HZMETRO", + "gifteval_pretrain/LOS_LOOP", + "gifteval_pretrain/PEMS03", + "gifteval_pretrain/PEMS04", + "gifteval_pretrain/PEMS07", + "gifteval_pretrain/PEMS08", + "gifteval_pretrain/PEMS_BAY", + "gifteval_pretrain/Q-TRAFFIC", + "gifteval_pretrain/SHMETRO", + "gifteval_pretrain/alibaba_cluster_trace_2018", + "gifteval_pretrain/australian_electricity_demand", + "gifteval_pretrain/azure_vm_traces_2017", + "gifteval_pretrain/bdg-2_bear", + "gifteval_pretrain/bdg-2_fox", + "gifteval_pretrain/bdg-2_panther", + "gifteval_pretrain/bdg-2_rat", + "gifteval_pretrain/bitcoin_with_missing", + "gifteval_pretrain/borealis", + "gifteval_pretrain/borg_cluster_data_2011", + "gifteval_pretrain/buildings_900k", + "gifteval_pretrain/bull", + "gifteval_pretrain/cdc_fluview_ilinet", + "gifteval_pretrain/cdc_fluview_who_nrevss", + "gifteval_pretrain/china_air_quality", + "gifteval_pretrain/cif_2016_12", + "gifteval_pretrain/cif_2016_6", + "gifteval_pretrain/cmip6_2000", + "gifteval_pretrain/cmip6_2005", + "gifteval_pretrain/cmip6_2010", + "gifteval_pretrain/cockatoo", + "gifteval_pretrain/covid19_energy", + "gifteval_pretrain/covid_mobility", + "gifteval_pretrain/elecdemand", + "gifteval_pretrain/elf", + "gifteval_pretrain/era5_2010", + "gifteval_pretrain/era5_2011", + "gifteval_pretrain/era5_2012", + "gifteval_pretrain/era5_2013", + "gifteval_pretrain/era5_2014", + "gifteval_pretrain/era5_2015", + "gifteval_pretrain/era5_2016", + "gifteval_pretrain/era5_2017", + "gifteval_pretrain/era5_2018", + "gifteval_pretrain/extended_web_traffic_with_missing", + "gifteval_pretrain/favorita_sales", + "gifteval_pretrain/favorita_transactions", + "gifteval_pretrain/gfc12_load", + "gifteval_pretrain/gfc14_load", + "gifteval_pretrain/gfc17_load", + "gifteval_pretrain/godaddy", + "gifteval_pretrain/hog", + "gifteval_pretrain/ideal", + "gifteval_pretrain/kaggle_web_traffic_weekly", + "gifteval_pretrain/kdd2022", + "gifteval_pretrain/largest_2017", + "gifteval_pretrain/largest_2018", + "gifteval_pretrain/largest_2019", + "gifteval_pretrain/largest_2020", + "gifteval_pretrain/largest_2021", + "gifteval_pretrain/lcl", + "gifteval_pretrain/london_smart_meters_with_missing", + "gifteval_pretrain/m1_monthly", + "gifteval_pretrain/m1_quarterly", + "gifteval_pretrain/m1_yearly", + "gifteval_pretrain/m5", + "gifteval_pretrain/monash_m3_monthly", + "gifteval_pretrain/monash_m3_other", + "gifteval_pretrain/monash_m3_quarterly", + "gifteval_pretrain/nn5_daily_with_missing", + "gifteval_pretrain/nn5_weekly", + "gifteval_pretrain/oikolab_weather", + "gifteval_pretrain/pdb", + "gifteval_pretrain/project_tycho", + "gifteval_pretrain/residential_load_power", + "gifteval_pretrain/residential_pv_power", + "gifteval_pretrain/rideshare_with_missing", + "gifteval_pretrain/sceaux", + "gifteval_pretrain/smart", + "gifteval_pretrain/solar_power", + "gifteval_pretrain/spain", + "gifteval_pretrain/subseasonal", + "gifteval_pretrain/subseasonal_precip", + "gifteval_pretrain/sunspot_with_missing", + "gifteval_pretrain/taxi_30min", + "gifteval_pretrain/tourism_quarterly", + "gifteval_pretrain/tourism_yearly", + "gifteval_pretrain/traffic_hourly", + "gifteval_pretrain/traffic_weekly", + "gifteval_pretrain/uber_tlc_daily", + "gifteval_pretrain/uber_tlc_hourly", + "gifteval_pretrain/vehicle_trips_with_missing", + "gifteval_pretrain/wiki-rolling_nips", + "gifteval_pretrain/wind_farms_with_missing", + "gifteval_pretrain/wind_power", + "synthetic:own direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; seeds 17 and 31" + ], + "weights_sha256": "70a3768d667df75f0d6565e831cdca8cf7c179c8546252e5902f7b7ec68ab7aa", + "training_step": 6000, + "config": { + "d": 256, + "heads": 8, + "enc_layers": 4, + "dec_layers": 3, + "patch": 32, + "max_context": 4096, + "max_horizon": 1024 + }, + "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. 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.", + "symmetric_averaging": true, + "training_seed": 31, + "training_continuation_from": { + "checkpoint": "swa008000-012000.pt", + "sha256": "a346a09ba0b8d196b58acc22a76f7944109b2bba04ea2b7cf7566de24aa2d8db", + "origin": "random initialization in this research run" + }, + "exponential_weight_average": true, + "postprocessing": { + "seasonal_difference_variance_threshold": 0.25, + "maximum_blend": 0.98, + "cycles_averaged": 4, + "inference_fitting": false + } +} diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..293f8010ac7580cc3cd38653c017786afce0b081 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/predict.py @@ -0,0 +1,51 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +from seasonal import apply_gate +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16): + qq,mu,scale=model(torch.cat((x,-x),0),p.repeat(2,1),h) + qq=qq*scale[:,:,None]+mu[:,:,None] + qq=(qq[:len(ids)]-qq[len(ids):].flip(-1))*.5 + positive=((x>=0)|~torch.isfinite(x)).all(-1) + qq=torch.where(positive[:,None,None],qq.clamp(min=0),qq) + q=qq.transpose(1,2).float().cpu().numpy() + q=apply_gate(ctx,p.cpu().numpy(),q) + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/provenance/continuation/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/provenance/continuation/data.py new file mode 100644 index 0000000000000000000000000000000000000000..2378e33d7352ba5ad97d566148782e63e64b367c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/provenance/continuation/data.py @@ -0,0 +1,71 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + return ctx,tgt,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/provenance/continuation/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/provenance/continuation/model.py new file mode 100644 index 0000000000000000000000000000000000000000..60aeb14b5f4fa298521ddce8a3276d076c1bb631 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/provenance/continuation/model.py @@ -0,0 +1,154 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional(torch.arange(-nt,0,device=z.device),self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + q=self.query(base.reshape(b,h//p,p*9))+positional(torch.arange(h//p,device=z.device),self.d)[None]+emb + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/provenance/continuation/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/provenance/continuation/train.py new file mode 100644 index 0000000000000000000000000000000000000000..676c7b28bafec314e5828f1bc34d58a5b0264a91 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/provenance/continuation/train.py @@ -0,0 +1,70 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(6);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/provenance/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/provenance/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/provenance/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/seasonal.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/seasonal.py new file mode 100644 index 0000000000000000000000000000000000000000..4eaeca9b9a0e7a64cef2a27f074e57ea3b810489 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/seasonal.py @@ -0,0 +1,38 @@ +"""A fixed confidence gate for highly repeatable history; no fitted parameters.""" +import numpy as np + +def apply_gate(ctx,periods,quant,threshold=.25,strength=1.): + # Each row uses only its own context. Quantile blending preserves ordering. + b,_,h=quant.shape + out=quant.copy() + for i in range(b): + x=ctx[i];valid=np.isfinite(x) + if not valid.any():continue + x=x[np.flatnonzero(valid)[0]:] + best=None + for p in periods[i]: + p=int(p) + if p<2 or len(x)<3*p:continue + k=min(len(x)//p,8);history=x[-k*p:] + pairs=np.isfinite(history[p:])&np.isfinite(history[:-p]) + if pairs.sum()0) + # Error of a season relative to the previous one, corrected for averaging. + sigma=float(np.sqrt(np.mean(err.astype(np.float64)**2)/2*(1+1/min(k,4)))) + idx=np.arange(h)%p;median=mu[idx] + z=np.array([-1.2815515655,-.8416212336,-.5244005127,-.2533471031,0,.2533471031,.5244005127,.8416212336,1.2815515655]) + sq=median[None]+z[:,None]*sigma + sq=np.where(np.isfinite(sq),sq,quant[i]) + if np.nanmin(x)>=0:sq=np.maximum(0,sq) + best=(weight,sq) + if best is not None:out[i]=(1-best[0])*quant[i]+best[0]*best[1] + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/validation_report.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/validation_report.json new file mode 100644 index 0000000000000000000000000000000000000000..007ca4f82b369b1dcd1a15bbf9348c3d88dbbdaf --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S006/validation_report.json @@ -0,0 +1,4887 @@ +{ + "contract": "timeseries-forecast/v1", + "split": "valid", + "reward": 0.3301094552008774, + "skill_score": 0.3301094552008774, + "rel_mase_gmean": 0.7896095778814758, + "rel_wql_gmean": 0.5683230733032284, + "n_configs": 97, + "n_failed": 0, + "n_instances": 151170, + "n_instances_scored": 151170, + "n_partial": 0, + "failures": [], + "groups": { + "term": { + "long": { + "n_configs": 21, + "rel_mase_gmean": 0.7635494124791545, + "rel_wql_gmean": 0.5219183984550115 + }, + "medium": { + "n_configs": 21, + "rel_mase_gmean": 0.7286923493908714, + "rel_wql_gmean": 0.5189356663494302 + }, + "short": { + "n_configs": 55, + "rel_mase_gmean": 0.8246901718127191, + "rel_wql_gmean": 0.6078474840359974 + } + }, + "domain": { + "Econ/Fin": { + "n_configs": 6, + "rel_mase_gmean": 1.074477701612095, + "rel_wql_gmean": 0.9725876169070388 + }, + "Energy": { + "n_configs": 32, + "rel_mase_gmean": 0.9708465203331357, + "rel_wql_gmean": 0.7398828298016675 + }, + "Healthcare": { + "n_configs": 5, + "rel_mase_gmean": 0.676260941602743, + "rel_wql_gmean": 0.6296182628922563 + }, + "Nature": { + "n_configs": 15, + "rel_mase_gmean": 0.8274889195424255, + "rel_wql_gmean": 0.43161041372358544 + }, + "Sales": { + "n_configs": 4, + "rel_mase_gmean": 0.8439824994199949, + "rel_wql_gmean": 0.5137799657165025 + }, + "Transport": { + "n_configs": 15, + "rel_mase_gmean": 0.6714504409807736, + "rel_wql_gmean": 0.4568629703886585 + }, + "Web/CloudOps": { + "n_configs": 20, + "rel_mase_gmean": 0.5784590928713237, + "rel_wql_gmean": 0.4567353663834386 + } + }, + "frequency": { + "A": { + "n_configs": 1, + "rel_mase_gmean": 0.7522844740960688, + "rel_wql_gmean": 0.773850385898527 + }, + "D": { + "n_configs": 15, + "rel_mase_gmean": 0.7940446299162331, + "rel_wql_gmean": 0.5556657100567961 + }, + "H": { + "n_configs": 31, + "rel_mase_gmean": 0.7584028087936501, + "rel_wql_gmean": 0.5335753363383622 + }, + "M": { + "n_configs": 5, + "rel_mase_gmean": 0.9834470089221661, + "rel_wql_gmean": 0.8308885101524416 + }, + "Q": { + "n_configs": 1, + "rel_mase_gmean": 0.8475774212825674, + "rel_wql_gmean": 0.8631368273616341 + }, + "S": { + "n_configs": 6, + "rel_mase_gmean": 0.7123364737912378, + "rel_wql_gmean": 0.5461415230114974 + }, + "T": { + "n_configs": 30, + "rel_mase_gmean": 0.7483465358153996, + "rel_wql_gmean": 0.5240233993201858 + }, + "W": { + "n_configs": 8, + "rel_mase_gmean": 1.0492168229811978, + "rel_wql_gmean": 0.7615678577285254 + } + }, + "variates": { + "multivariate": { + "n_configs": 43, + "rel_mase_gmean": 0.7399143870819447, + "rel_wql_gmean": 0.550773156034254 + }, + "univariate": { + "n_configs": 54, + "rel_mase_gmean": 0.8315580979234989, + "rel_wql_gmean": 0.5826970950828023 + } + } + }, + "quantile_crossing_fraction_mean": 0.0, + "configs": [ + { + "config_id": "m4_yearly__A__short", + "leaderboard_key": "m4_yearly/A/short", + "dataset": "m4_yearly", + "term": "short", + "freq": "A-DEC", + "prediction_length": 6, + "seasonality": 1, + "n_variates": 1, + "n_instances": 22728, + "domain": "Econ/Fin", + "n_cohorts": 3, + "skipped_series": 235, + "dropped_containers": 11, + "status": "ok", + "baseline": { + "mase": 4.730803330645802, + "wql": 0.15602350647819704 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 22728, + "instances": 22728, + "fraction": 1.0 + }, + "metrics": { + "mase": 3.5589098956468077, + "wql": 0.1207388506973941, + "wsql_by_level": [ + 0.07179188837617806, + 0.10819996586236896, + 0.1296777784542309, + 0.13988346705529262, + 0.14694145715975732, + 0.1518539324632369, + 0.13806877108877552, + 0.1168903755337783, + 0.08334202028292836 + ], + "n_valid_labels": 136368, + "n_masked_labels": 0, + "mae_median": 762.7596074709321, + "n_mase_elements": 136356, + "n_seasonal_error_zero": 2, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7522844740960688, + "wql": 0.773850385898527 + } + }, + { + "config_id": "m4_quarterly__Q__short", + "leaderboard_key": "m4_quarterly/Q/short", + "dataset": "m4_quarterly", + "term": "short", + "freq": "Q-DEC", + "prediction_length": 8, + "seasonality": 4, + "n_variates": 1, + "n_instances": 23905, + "domain": "Econ/Fin", + "n_cohorts": 3, + "dropped_containers": 95, + "status": "ok", + "baseline": { + "mase": 1.5909093331240343, + "wql": 0.0995990835037221 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 23905, + "instances": 23905, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.348418830063638, + "wql": 0.08596763694352916, + "wsql_by_level": [ + 0.05074844708789022, + 0.0764554425519201, + 0.0925431182207736, + 0.10178174156490168, + 0.1057184274352351, + 0.10492250056195732, + 0.09816568903984975, + 0.08401467764582052, + 0.05935868838341413 + ], + "n_valid_labels": 191240, + "n_masked_labels": 0, + "mae_median": 601.9914098382569, + "n_mase_elements": 191232, + "n_seasonal_error_zero": 1, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8475774212825674, + "wql": 0.8631368273616341 + } + }, + { + "config_id": "m4_monthly__M__short", + "leaderboard_key": "m4_monthly/M/short", + "dataset": "m4_monthly", + "term": "short", + "freq": "M", + "prediction_length": 18, + "seasonality": 12, + "n_variates": 1, + "n_instances": 47501, + "domain": "Econ/Fin", + "n_cohorts": 3, + "dropped_containers": 499, + "status": "ok", + "baseline": { + "mase": 1.2366691185612824, + "wql": 0.11781121192744513 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 47501, + "instances": 47501, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.048136357762658, + "wql": 0.09560428880902444, + "wsql_by_level": [ + 0.055271547425405944, + 0.0844240776866944, + 0.10304093041488373, + 0.11375597953051966, + 0.11823372384721498, + 0.11670947089895174, + 0.10888411997512153, + 0.09344356356503042, + 0.06667518593739738 + ], + "n_valid_labels": 855018, + "n_masked_labels": 0, + "mae_median": 560.6273141593596, + "n_mase_elements": 855018, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8475479350386302, + "wql": 0.811504161996933 + } + }, + { + "config_id": "m4_weekly__W__short", + "leaderboard_key": "m4_weekly/W/short", + "dataset": "m4_weekly", + "term": "short", + "freq": "W-SUN", + "prediction_length": 13, + "seasonality": 1, + "n_variates": 1, + "n_instances": 355, + "domain": "Econ/Fin", + "n_cohorts": 2, + "dropped_containers": 4, + "status": "ok", + "baseline": { + "mase": 2.895128591740639, + "wql": 0.06508715280630521 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 355, + "instances": 355, + "fraction": 1.0 + }, + "metrics": { + "mase": 5.655014876611724, + "wql": 0.06417741552843341, + "wsql_by_level": [ + 0.032234793477567726, + 0.05198488686218914, + 0.06610344402965432, + 0.0757764857203246, + 0.08118721575324664, + 0.08204914189457885, + 0.07728203106996712, + 0.06573051348489815, + 0.045248227463474115 + ], + "n_valid_labels": 4615, + "n_masked_labels": 0, + "mae_median": 422.5677988666109, + "n_mase_elements": 4615, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.9532862522046932, + "wql": 0.9860227827052273 + } + }, + { + "config_id": "m4_daily__D__short", + "leaderboard_key": "m4_daily/D/short", + "dataset": "m4_daily", + "term": "short", + "freq": "D", + "prediction_length": 14, + "seasonality": 1, + "n_variates": 1, + "n_instances": 4204, + "domain": "Econ/Fin", + "n_cohorts": 2, + "dropped_containers": 23, + "status": "ok", + "baseline": { + "mase": 3.2161164077095057, + "wql": 0.02310161661155265 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 4204, + "instances": 4204, + "fraction": 1.0 + }, + "metrics": { + "mase": 3.768826363387784, + "wql": 0.025174729771722765, + "wsql_by_level": [ + 0.015125884068402, + 0.022511765859606663, + 0.027162719455963175, + 0.029890314012737926, + 0.03109980590527266, + 0.03079504650902881, + 0.0286515501230874, + 0.024376111987191657, + 0.0169593700242146 + ], + "n_valid_labels": 58856, + "n_masked_labels": 0, + "mae_median": 199.26417638595393, + "n_mase_elements": 58842, + "n_seasonal_error_zero": 1, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.1718563278223857, + "wql": 1.0897388782364863 + } + }, + { + "config_id": "m4_hourly__H__short", + "leaderboard_key": "m4_hourly/H/short", + "dataset": "m4_hourly", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 414, + "domain": "Econ/Fin", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.22836124915778, + "wql": 0.034474947608819397 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 414, + "instances": 414, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.5280745383039784, + "wql": 0.050100173796875515, + "wsql_by_level": [ + 0.02478044134565653, + 0.039748024295581066, + 0.050387565923033055, + 0.05756942243035411, + 0.06220247659421222, + 0.06392017815974131, + 0.061607248375385434, + 0.054085702217415516, + 0.036600504830500355 + ], + "n_valid_labels": 19872, + "n_masked_labels": 0, + "mae_median": 468.571293120031, + "n_mase_elements": 19872, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.2439944188663516, + "wql": 1.4532342257732356 + } + }, + { + "config_id": "electricity__T__short", + "leaderboard_key": "electricity/15T/short", + "dataset": "electricity/15T", + "term": "short", + "freq": "15T", + "prediction_length": 48, + "seasonality": 96, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0916823579221513, + "wql": 0.06198863606457304 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.2233978248041235, + "wql": 0.08102909074227042, + "wsql_by_level": [ + 0.036723541007808204, + 0.06000849597260715, + 0.07795135023916581, + 0.09121379159815994, + 0.10038333030546444, + 0.10456744387688456, + 0.10273827019619691, + 0.09138240644605117, + 0.06429318703809557 + ], + "n_valid_labels": 17712, + "n_masked_labels": 48, + "mae_median": 101.9646278446828, + "n_mase_elements": 17712, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 1.1206536552744815, + "wql": 1.3071604069149563 + } + }, + { + "config_id": "electricity__T__medium", + "leaderboard_key": "electricity/15T/medium", + "dataset": "electricity/15T", + "term": "medium", + "freq": "15T", + "prediction_length": 480, + "seasonality": 96, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.5099936923797364, + "wql": 0.12054261982000446 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9241272901814785, + "wql": 0.08562074260720683, + "wsql_by_level": [ + 0.040050638620653015, + 0.06452695544030673, + 0.08196831070391798, + 0.09372169468828959, + 0.10156766766053152, + 0.10720267142235436, + 0.10697107067691523, + 0.09835080923766036, + 0.0762268650142327 + ], + "n_valid_labels": 177120, + "n_masked_labels": 480, + "mae_median": 73.0496246768936, + "n_mase_elements": 177120, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 0.6120073844315617, + "wql": 0.7102943567599298 + } + }, + { + "config_id": "electricity__T__long", + "leaderboard_key": "electricity/15T/long", + "dataset": "electricity/15T", + "term": "long", + "freq": "15T", + "prediction_length": 720, + "seasonality": 96, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0941077605435365, + "wql": 0.107564338522276 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.900609751393583, + "wql": 0.0931668632295088, + "wsql_by_level": [ + 0.04180455861333845, + 0.06764045808232796, + 0.08637790302909926, + 0.09984744931382733, + 0.10916861711919641, + 0.11580497842787457, + 0.11700774281893479, + 0.11055125963468493, + 0.09029880202629563 + ], + "n_valid_labels": 265680, + "n_masked_labels": 720, + "mae_median": 78.71564571320594, + "n_mase_elements": 265680, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 0.8231453828151017, + "wql": 0.8661501061545082 + } + }, + { + "config_id": "electricity__H__short", + "leaderboard_key": "electricity/H/short", + "dataset": "electricity/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9861593153062442, + "wql": 0.06763119078713985 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.1126769952990159, + "wql": 0.08179553400353416, + "wsql_by_level": [ + 0.040043319050973865, + 0.06367998987763815, + 0.07973537784304999, + 0.09070925180570497, + 0.09896667574528237, + 0.10363326727882954, + 0.10220537118746048, + 0.09142612306974444, + 0.06576043017312362 + ], + "n_valid_labels": 17712, + "n_masked_labels": 48, + "mae_median": 300.5648154417909, + "n_mase_elements": 17712, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 1.1282933477675283, + "wql": 1.2094350705871009 + } + }, + { + "config_id": "electricity__H__medium", + "leaderboard_key": "electricity/H/medium", + "dataset": "electricity/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.2478422873379948, + "wql": 0.12311153060577013 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9348717297948094, + "wql": 0.07611104769290505, + "wsql_by_level": [ + 0.04136292282483788, + 0.0626311097420565, + 0.0757775610696427, + 0.08386358496583186, + 0.08945399293624774, + 0.09310700836947754, + 0.09173857135674963, + 0.08337917738831487, + 0.0636855005829867 + ], + "n_valid_labels": 177120, + "n_masked_labels": 480, + "mae_median": 240.73554242437623, + "n_mase_elements": 177120, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 0.7491906142956244, + "wql": 0.6182284252206169 + } + }, + { + "config_id": "electricity__H__long", + "leaderboard_key": "electricity/H/long", + "dataset": "electricity/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.356699671272273, + "wql": 0.14674885232557194 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.2720904466776006, + "wql": 0.11128805536691587, + "wsql_by_level": [ + 0.0470270938249516, + 0.07607108791130805, + 0.09774721237607248, + 0.11430159944171213, + 0.12728461028353535, + 0.1373735978122954, + 0.14222055723794785, + 0.13880289930126372, + 0.12076384011315634 + ], + "n_valid_labels": 265680, + "n_masked_labels": 720, + "mae_median": 348.86127650832503, + "n_mase_elements": 265680, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 0.9376359953597333, + "wql": 0.7583572450707555 + } + }, + { + "config_id": "electricity__D__short", + "leaderboard_key": "electricity/D/short", + "dataset": "electricity/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.6456666278884469, + "wql": 0.09261378216375024 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.557608903258635, + "wql": 0.07359049373545971, + "wsql_by_level": [ + 0.031800251242138755, + 0.05608207206737466, + 0.07432348572851652, + 0.08755457134562769, + 0.09283791668694624, + 0.09272912408758967, + 0.08773142023867639, + 0.07822969711123287, + 0.06102590511103461 + ], + "n_valid_labels": 11070, + "n_masked_labels": 30, + "mae_median": 6106.797179441982, + "n_mase_elements": 11070, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 0.9464911524986087, + "wql": 0.794595491255767 + } + }, + { + "config_id": "electricity__W__short", + "leaderboard_key": "electricity/W/short", + "dataset": "electricity/W", + "term": "short", + "freq": "W-FRI", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.316880865245498, + "wql": 0.06523927951573125 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.541881378185217, + "wql": 0.06698663111464463, + "wsql_by_level": [ + 0.02743593391861817, + 0.05044306400271873, + 0.07154180838465138, + 0.08628235724619318, + 0.09039081235329668, + 0.0888048796658757, + 0.08015452555941419, + 0.06428440868195585, + 0.04354189021907778 + ], + "n_valid_labels": 2952, + "n_masked_labels": 8, + "mae_median": 38925.72044360153, + "n_mase_elements": 2952, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 1.1708586698142762, + "wql": 1.026783735379727 + } + }, + { + "config_id": "solar__T__short", + "leaderboard_key": "solar/10T/short", + "dataset": "solar/10T", + "term": "short", + "freq": "10T", + "prediction_length": 48, + "seasonality": 144, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.016018364778558773, + "wql": 12.118563297136966 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.05539874545965657, + "wql": 2.0064424783595367, + "wsql_by_level": [ + 0.6611829505430559, + 1.0638004263092853, + 1.23557129925559, + 1.3038877660318902, + 1.4442096911687343, + 2.113718583078429, + 3.0425549856984317, + 3.6017074842883634, + 3.5913491188620497 + ], + "n_valid_labels": 6576, + "n_masked_labels": 0, + "mae_median": 0.13956740517973665, + "n_mase_elements": 6576, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 3.4584519846751163, + "wql": 0.165567685637584 + } + }, + { + "config_id": "solar__T__medium", + "leaderboard_key": "solar/10T/medium", + "dataset": "solar/10T", + "term": "medium", + "freq": "10T", + "prediction_length": 480, + "seasonality": 144, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.8331425981399365, + "wql": 0.5650432034501303 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7785944268157016, + "wql": 0.31710315771486447, + "wsql_by_level": [ + 0.2610934368713417, + 0.3519749201182881, + 0.3908560972723216, + 0.395518900217904, + 0.38153142933091844, + 0.3548859501670206, + 0.30968923218929684, + 0.24276726761316034, + 0.16561118565352884 + ], + "n_valid_labels": 65760, + "n_masked_labels": 0, + "mae_median": 1.8230329995236751, + "n_mase_elements": 65760, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.93452720885234, + "wql": 0.5612016139272994 + } + }, + { + "config_id": "solar__T__long", + "leaderboard_key": "solar/10T/long", + "dataset": "solar/10T", + "term": "long", + "freq": "10T", + "prediction_length": 720, + "seasonality": 144, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 2.1421153816960863, + "wql": 0.9032285592107642 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7819637251378123, + "wql": 0.2599707677955242, + "wsql_by_level": [ + 0.20143782058050316, + 0.2725127287903842, + 0.3062299897326275, + 0.3160872145154103, + 0.31234646497172763, + 0.29851976646257633, + 0.2706650600460628, + 0.21810295382822492, + 0.1438349112322009 + ], + "n_valid_labels": 98640, + "n_masked_labels": 0, + "mae_median": 1.835261413176133, + "n_mase_elements": 98640, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.36504276651926576, + "wql": 0.28782390143053616 + } + }, + { + "config_id": "solar__H__short", + "leaderboard_key": "solar/H/short", + "dataset": "solar/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0569321595099215, + "wql": 0.602297355940449 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9706561394189377, + "wql": 0.42608456905826625, + "wsql_by_level": [ + 0.46297075265836224, + 0.5138087460895678, + 0.5140481329465669, + 0.49246378453467377, + 0.460733761031435, + 0.423085186415043, + 0.38539012377801674, + 0.33543763419922606, + 0.24682299987150455 + ], + "n_valid_labels": 6576, + "n_masked_labels": 0, + "mae_median": 12.707840751611272, + "n_mase_elements": 6576, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9183712792588427, + "wql": 0.7074322423231666 + } + }, + { + "config_id": "solar__H__medium", + "leaderboard_key": "solar/H/medium", + "dataset": "solar/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.3782698364748944, + "wql": 0.9679824737641872 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.2408457181665065, + "wql": 0.506546889758887, + "wsql_by_level": [ + 0.6095113793971516, + 0.6484062283815126, + 0.6332519339440444, + 0.5925795591178228, + 0.5394889583196257, + 0.49341664211820263, + 0.4370538386210623, + 0.36062416803881864, + 0.24458929989174166 + ], + "n_valid_labels": 65760, + "n_masked_labels": 0, + "mae_median": 16.16688145084262, + "n_mase_elements": 65760, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9002922978711715, + "wql": 0.523301716186122 + } + }, + { + "config_id": "solar__H__long", + "leaderboard_key": "solar/H/long", + "dataset": "solar/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0723400769109404, + "wql": 0.9027882643891623 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.053997519931657, + "wql": 0.38812491489020906, + "wsql_by_level": [ + 0.47971386673320254, + 0.4965180918142476, + 0.48289245233429695, + 0.4526379437751149, + 0.41120251869501956, + 0.38530698884885667, + 0.3403942504525006, + 0.27240372350514575, + 0.17205439785349638 + ], + "n_valid_labels": 98640, + "n_masked_labels": 0, + "mae_median": 13.862031475432556, + "n_mase_elements": 98640, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9828948321766334, + "wql": 0.4299179887465852 + } + }, + { + "config_id": "solar__D__short", + "leaderboard_key": "solar/D/short", + "dataset": "solar/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.1670584568457976, + "wql": 0.4714212933677157 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.154305027610483, + "wql": 0.29575538794379574, + "wsql_by_level": [ + 0.272345767838703, + 0.3655852043531325, + 0.3928092897323668, + 0.38809902621754, + 0.36106287455193625, + 0.3179692686685256, + 0.2610588571574162, + 0.191784438887231, + 0.11108376408731067 + ], + "n_valid_labels": 4110, + "n_masked_labels": 0, + "mae_median": 292.12262317119144, + "n_mase_elements": 4110, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9890721590161102, + "wql": 0.6273695993471006 + } + }, + { + "config_id": "solar__W__short", + "leaderboard_key": "solar/W/short", + "dataset": "solar/W", + "term": "short", + "freq": "W-FRI", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0078578333938706, + "wql": 0.13890951079671932 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9611101838051883, + "wql": 0.11437224252444561, + "wsql_by_level": [ + 0.0631258205483528, + 0.12066616698832902, + 0.14262422374515724, + 0.14819930089018019, + 0.14356454444173392, + 0.13323499556345855, + 0.11807357982107157, + 0.09492735880491993, + 0.06493419191680724 + ], + "n_valid_labels": 1096, + "n_masked_labels": 0, + "mae_median": 881.5921889256387, + "n_mase_elements": 1096, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9536168216986877, + "wql": 0.8233578958594013 + } + }, + { + "config_id": "hospital__M__short", + "leaderboard_key": "hospital/M/short", + "dataset": "hospital", + "term": "short", + "freq": "M", + "prediction_length": 12, + "seasonality": 12, + "n_variates": 1, + "n_instances": 767, + "domain": "Healthcare", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9326829101839614, + "wql": 0.0633931064425068 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 767, + "instances": 767, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8001290845875856, + "wql": 0.05546952406861419, + "wsql_by_level": [ + 0.0339571225561101, + 0.04970562819852083, + 0.059252660846609066, + 0.06476805987886486, + 0.06702104765115825, + 0.06714706253287679, + 0.06377457478943203, + 0.0548572650815542, + 0.038742295082401554 + ], + "n_valid_labels": 9204, + "n_masked_labels": 0, + "mae_median": 18.60780697286466, + "n_mase_elements": 9204, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8578790024465752, + "wql": 0.8750087695879243 + } + }, + { + "config_id": "covid_deaths__D__short", + "leaderboard_key": "covid_deaths/D/short", + "dataset": "covid_deaths", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 266, + "domain": "Healthcare", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 50.55549046119792, + "wql": 0.12549070850235644 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 266, + "instances": 266, + "fraction": 1.0 + }, + "metrics": { + "mase": 58.87169396261999, + "wql": 0.14093672333779417, + "wsql_by_level": [ + 0.06853310000542481, + 0.11250701506120801, + 0.14825569545986897, + 0.17537957829347403, + 0.19646422979383746, + 0.21396354209243815, + 0.19917688871406844, + 0.12152343305108057, + 0.032627027568746976 + ], + "n_valid_labels": 7980, + "n_masked_labels": 0, + "mae_median": 399.12835859275293, + "n_mase_elements": 6810, + "n_seasonal_error_zero": 39, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.1644965447977382, + "wql": 1.1230849281175879 + } + }, + { + "config_id": "us_births__D__short", + "leaderboard_key": "us_births/D/short", + "dataset": "us_births/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 1, + "domain": "Healthcare", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 2.328105874599355, + "wql": 0.13056664093780335 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.5618205680446079, + "wql": 0.027440794846154325, + "wsql_by_level": [ + 0.010894372997273877, + 0.014504372883139473, + 0.02250324400175081, + 0.03049612306411671, + 0.03646052986615873, + 0.03921657888724381, + 0.039393455226147865, + 0.03294516333196303, + 0.020553313357594655 + ], + "n_valid_labels": 30, + "n_masked_labels": 0, + "mae_median": 371.030859375, + "n_mase_elements": 30, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.24132088414634145, + "wql": 0.2101669664552832 + } + }, + { + "config_id": "us_births__M__short", + "leaderboard_key": "us_births/M/short", + "dataset": "us_births/M", + "term": "short", + "freq": "M", + "prediction_length": 12, + "seasonality": 12, + "n_variates": 1, + "n_instances": 1, + "domain": "Healthcare", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.3023112362005141, + "wql": 0.011101802850788281 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.26356311672648064, + "wql": 0.007510206531224344, + "wsql_by_level": [ + 0.0065757998032446065, + 0.007472208831482137, + 0.006173165651477498, + 0.00778712497152993, + 0.00787513498396916, + 0.007875173143154151, + 0.009091523710193002, + 0.008406989408868432, + 0.006334738277100187 + ], + "n_valid_labels": 12, + "n_masked_labels": 0, + "mae_median": 2472.2109375, + "n_mase_elements": 12, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8718270615375574, + "wql": 0.6764853089326013 + } + }, + { + "config_id": "us_births__W__short", + "leaderboard_key": "us_births/W/short", + "dataset": "us_births/W", + "term": "short", + "freq": "W-TUE", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 1, + "n_instances": 1, + "domain": "Healthcare", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 3.858436986096576, + "wql": 0.04221704717157443 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 2.5965305737498134, + "wql": 0.02989693091222785, + "wsql_by_level": [ + 0.022630547592682525, + 0.03374988762827181, + 0.037607078704738346, + 0.03923908376923762, + 0.03798378391945867, + 0.03483680579476847, + 0.02954338063307922, + 0.022334217044207662, + 0.011147593123606378 + ], + "n_valid_labels": 8, + "n_masked_labels": 0, + "mae_median": 2825.6279296875, + "n_mase_elements": 8, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6729488088327232, + "wql": 0.7081720043262061 + } + }, + { + "config_id": "saugeenday__D__short", + "leaderboard_key": "saugeen/D/short", + "dataset": "saugeenday/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 3.898466092444523, + "wql": 0.5418638069109889 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 2.83314242167484, + "wql": 0.2990571453119268, + "wsql_by_level": [ + 0.1447834485452225, + 0.2377022271873454, + 0.3130220480833398, + 0.36811178091075547, + 0.40095054867272334, + 0.4035448094552027, + 0.35888597677480316, + 0.25144917426688046, + 0.21306429391106818 + ], + "n_valid_labels": 30, + "n_masked_labels": 0, + "mae_median": 12.456197134653728, + "n_mase_elements": 30, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7267326057204015, + "wql": 0.5519046326728598 + } + }, + { + "config_id": "saugeenday__M__short", + "leaderboard_key": "saugeen/M/short", + "dataset": "saugeenday/M", + "term": "short", + "freq": "M", + "prediction_length": 12, + "seasonality": 12, + "n_variates": 1, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.33228103391864, + "wql": 0.2615013833629034 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.4931639350553017, + "wql": 0.29452792219137036, + "wsql_by_level": [ + 0.151259308003604, + 0.24692103222405007, + 0.3144780374861247, + 0.3205924196645978, + 0.29396063541179773, + 0.29346390959640223, + 0.36912518931715127, + 0.37726533746464275, + 0.28368543055396306 + ], + "n_valid_labels": 12, + "n_masked_labels": 0, + "mae_median": 8.549039363861084, + "n_mase_elements": 12, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.4841772015674368, + "wql": 1.1262958474779223 + } + }, + { + "config_id": "saugeenday__W__short", + "leaderboard_key": "saugeen/W/short", + "dataset": "saugeenday/W", + "term": "short", + "freq": "W-THU", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 1, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.5685710422753978, + "wql": 0.5994091721735982 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.704551356839817, + "wql": 0.25547657491536807, + "wsql_by_level": [ + 0.1733118694350402, + 0.23903724589284406, + 0.2728517999897071, + 0.30697260848231916, + 0.34530747149353125, + 0.33676822687472896, + 0.24105883280495746, + 0.1639061276340875, + 0.22007499163109684 + ], + "n_valid_labels": 8, + "n_masked_labels": 0, + "mae_median": 8.444000840187073, + "n_mase_elements": 8, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.239161519764059, + "wql": 0.4262139900011041 + } + }, + { + "config_id": "temperature_rain_with_missing__D__short", + "leaderboard_key": "temperature_rain/D/short", + "dataset": "temperature_rain_with_missing", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 32072, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 3.2912255413171745, + "wql": 1.099183165150044 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 32072, + "instances": 32072, + "fraction": 1.0 + }, + "metrics": { + "mase": 2.1894081671179237, + "wql": 0.5393447534846728, + "wsql_by_level": [ + 0.19183493701587667, + 0.36014993575547777, + 0.4986874201063308, + 0.607042726473816, + 0.6799218352504708, + 0.715375709157522, + 0.7056251036575332, + 0.6337324666552483, + 0.4617326472897792 + ], + "n_valid_labels": 961756, + "n_masked_labels": 404, + "mae_median": 6.831149112102923, + "n_mase_elements": 960736, + "n_seasonal_error_zero": 34, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6652258071143022, + "wql": 0.4906777783583044 + } + }, + { + "config_id": "kdd_cup_2018_with_missing__H__short", + "leaderboard_key": "kdd_cup_2018/H/short", + "dataset": "kdd_cup_2018_with_missing/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 270, + "domain": "Nature", + "n_cohorts": 2, + "status": "ok", + "baseline": { + "mase": 0.6811227593500775, + "wql": 0.6266148384878599 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 270, + "instances": 270, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.5249139405063261, + "wql": 0.36395379381638693, + "wsql_by_level": [ + 0.1508911484266577, + 0.26129010666130154, + 0.3527634808857259, + 0.4195825313519797, + 0.4588706693179482, + 0.47611881010873475, + 0.4585601327250025, + 0.4049156200878857, + 0.2925916447822467 + ], + "n_valid_labels": 11685, + "n_masked_labels": 1275, + "mae_median": 11.794115034406339, + "n_mase_elements": 11685, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7706598161647032, + "wql": 0.5808253674532768 + } + }, + { + "config_id": "kdd_cup_2018_with_missing__H__medium", + "leaderboard_key": "kdd_cup_2018/H/medium", + "dataset": "kdd_cup_2018_with_missing/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 1, + "n_instances": 270, + "domain": "Nature", + "n_cohorts": 2, + "status": "ok", + "baseline": { + "mase": 1.2781450805103305, + "wql": 1.049898934007083 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 270, + "instances": 270, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9078033234863444, + "wql": 0.4537004435428638, + "wsql_by_level": [ + 0.17506169240078684, + 0.31781930191057295, + 0.43794775192681734, + 0.5285452113049431, + 0.5846359233437216, + 0.6025869140965373, + 0.5772014924837408, + 0.5021567406919418, + 0.35734896372671276 + ], + "n_valid_labels": 116458, + "n_masked_labels": 13142, + "mae_median": 19.59485425630579, + "n_mase_elements": 116458, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7102506103015175, + "wql": 0.4321372551653653 + } + }, + { + "config_id": "kdd_cup_2018_with_missing__H__long", + "leaderboard_key": "kdd_cup_2018/H/long", + "dataset": "kdd_cup_2018_with_missing/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 1, + "n_instances": 270, + "domain": "Nature", + "n_cohorts": 2, + "status": "ok", + "baseline": { + "mase": 0.981050679806651, + "wql": 1.2362237298155803 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 270, + "instances": 270, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8665049241274414, + "wql": 0.47314678898195833, + "wsql_by_level": [ + 0.1885328075321528, + 0.3437823413066264, + 0.46880901217533355, + 0.5587519460553033, + 0.6125330045658286, + 0.6303821738804942, + 0.599538965558534, + 0.511302081939516, + 0.344688767823836 + ], + "n_valid_labels": 175906, + "n_masked_labels": 18494, + "mae_median": 18.681128419557893, + "n_mase_elements": 175906, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8832417549501269, + "wql": 0.38273556603912007 + } + }, + { + "config_id": "kdd_cup_2018_with_missing__D__short", + "leaderboard_key": "kdd_cup_2018/D/short", + "dataset": "kdd_cup_2018_with_missing/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 270, + "domain": "Nature", + "n_cohorts": 2, + "status": "ok", + "baseline": { + "mase": 1.2132840958596942, + "wql": 0.8994855622016019 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 270, + "instances": 270, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0588873179136615, + "wql": 0.41285499197157277, + "wsql_by_level": [ + 0.18709610817571387, + 0.33640437071527446, + 0.4359175475651082, + 0.4963324783950149, + 0.5204546754986563, + 0.5281348299791536, + 0.501025721470853, + 0.42463120525044096, + 0.28569799069393975 + ], + "n_valid_labels": 7581, + "n_masked_labels": 519, + "mae_median": 16.153080591707617, + "n_mase_elements": 7581, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8727447442252739, + "wql": 0.4589901264908124 + } + }, + { + "config_id": "car_parts_with_missing__M__short", + "leaderboard_key": "car_parts/M/short", + "dataset": "car_parts_with_missing", + "term": "short", + "freq": "M", + "prediction_length": 12, + "seasonality": 12, + "n_variates": 1, + "n_instances": 2674, + "domain": "Sales", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.556811831303017, + "wql": 1.6139130745452677 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 2674, + "instances": 2674, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.522244917482549, + "wql": 1.181353567868615, + "wsql_by_level": [ + 0.2970087054173999, + 0.6051322175692809, + 0.8959769312817257, + 1.1826867533597325, + 1.4371029177186154, + 1.6402983734902337, + 1.7163329113904076, + 1.596735326298597, + 1.2609079742915412 + ], + "n_valid_labels": 30108, + "n_masked_labels": 1980, + "mae_median": 0.6800320602078224, + "n_mase_elements": 28068, + "n_seasonal_error_zero": 215, + "n_seasonal_error_nan": 7 + }, + "relative": { + "mase": 0.9777963443459083, + "wql": 0.731980914276607 + } + }, + { + "config_id": "restaurant__D__short", + "leaderboard_key": "restaurant/D/short", + "dataset": "restaurant", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 806, + "domain": "Sales", + "n_cohorts": 13, + "skipped_series": 1, + "status": "ok", + "baseline": { + "mase": 1.0028179898604987, + "wql": 0.6760963195065456 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 806, + "instances": 806, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7030777107027514, + "wql": 0.26573262691849486, + "wsql_by_level": [ + 0.1349491810885146, + 0.2187108228263804, + 0.27829332966816417, + 0.31700861215971715, + 0.3367901794992435, + 0.3365749124489965, + 0.315494476392539, + 0.2685997259188658, + 0.18517240226403234 + ], + "n_valid_labels": 21222, + "n_masked_labels": 2958, + "mae_median": 7.20339315971278, + "n_mase_elements": 21222, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7011020123407997, + "wql": 0.39303959990854853 + } + }, + { + "config_id": "hierarchical_sales__D__short", + "leaderboard_key": "hierarchical_sales/D/short", + "dataset": "hierarchical_sales/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 118, + "domain": "Sales", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0956340453936162, + "wql": 1.4587792906606432 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 118, + "instances": 118, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9295747085208466, + "wql": 0.6148476012948972, + "wsql_by_level": [ + 0.20877236806910252, + 0.3855435639969441, + 0.5286626029239536, + 0.646069240294747, + 0.7348894716842156, + 0.7958841383190374, + 0.8190946645493622, + 0.782003481536954, + 0.6327088802797591 + ], + "n_valid_labels": 3304, + "n_masked_labels": 236, + "mae_median": 2.881950025609074, + "n_mase_elements": 3304, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.848435399054151, + "wql": 0.4214808951780833 + } + }, + { + "config_id": "hierarchical_sales__W__short", + "leaderboard_key": "hierarchical_sales/W/short", + "dataset": "hierarchical_sales/W", + "term": "short", + "freq": "W-WED", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 1, + "n_instances": 118, + "domain": "Sales", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9952062817493519, + "wql": 0.7382990422957836 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 118, + "instances": 118, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8681573987215155, + "wql": 0.42425503637653333, + "wsql_by_level": [ + 0.16814723025847414, + 0.29611686462849185, + 0.38794648248668345, + 0.458959076093231, + 0.5112972771940417, + 0.5478140100119171, + 0.5503854098402756, + 0.51149237606272, + 0.38613660081296575 + ], + "n_valid_labels": 944, + "n_masked_labels": 0, + "mae_median": 12.484536270468922, + "n_mase_elements": 944, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8723391468103351, + "wql": 0.574638475836685 + } + }, + { + "config_id": "LOOP_SEATTLE__T__short", + "leaderboard_key": "loop_seattle/5T/short", + "dataset": "LOOP_SEATTLE/5T", + "term": "short", + "freq": "5T", + "prediction_length": 48, + "seasonality": 288, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.6088421384511257, + "wql": 0.05736115508602545 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.40881664058928324, + "wql": 0.030676102928239204, + "wsql_by_level": [ + 0.019654606995202294, + 0.027289537774653722, + 0.03251706957161851, + 0.03564587756111054, + 0.037336996140990175, + 0.03763771767184407, + 0.03564413793274025, + 0.030614247291911707, + 0.019744735414081553 + ], + "n_valid_labels": 15504, + "n_masked_labels": 0, + "mae_median": 2.42162365613215, + "n_mase_elements": 15504, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6714657458324079, + "wql": 0.5347887936049014 + } + }, + { + "config_id": "LOOP_SEATTLE__T__medium", + "leaderboard_key": "loop_seattle/5T/medium", + "dataset": "LOOP_SEATTLE/5T", + "term": "medium", + "freq": "5T", + "prediction_length": 480, + "seasonality": 288, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.5924843577520822, + "wql": 0.14109820582939464 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6289683574477548, + "wql": 0.05300934483257686, + "wsql_by_level": [ + 0.04305099050994561, + 0.05683981611664535, + 0.06309404261584861, + 0.06549486948379635, + 0.06448995655254301, + 0.06099463747444582, + 0.05392568067453507, + 0.04300186454295257, + 0.026192245522479354 + ], + "n_valid_labels": 155040, + "n_masked_labels": 0, + "mae_median": 3.9180154560673963, + "n_mase_elements": 155040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.39496046186324457, + "wql": 0.375691133143619 + } + }, + { + "config_id": "LOOP_SEATTLE__T__long", + "leaderboard_key": "loop_seattle/5T/long", + "dataset": "LOOP_SEATTLE/5T", + "term": "long", + "freq": "5T", + "prediction_length": 720, + "seasonality": 288, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.5910237866124803, + "wql": 0.14753926773607257 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6863624934273429, + "wql": 0.059123668032530774, + "wsql_by_level": [ + 0.047828326660181573, + 0.06378583886285581, + 0.07074293898302522, + 0.07313199255582443, + 0.07188375049508622, + 0.06755007491956272, + 0.05963155165239395, + 0.04764380970469918, + 0.029914728459147825 + ], + "n_valid_labels": 232560, + "n_masked_labels": 0, + "mae_median": 4.228709880293625, + "n_mase_elements": 232560, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.4313967517033217, + "wql": 0.4007317437571595 + } + }, + { + "config_id": "LOOP_SEATTLE__H__short", + "leaderboard_key": "loop_seattle/H/short", + "dataset": "LOOP_SEATTLE/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 2.0101473993616685, + "wql": 0.13665681786039896 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7772823155459598, + "wql": 0.051189118066547024, + "wsql_by_level": [ + 0.03996625938995256, + 0.05276874201783513, + 0.05845003196906124, + 0.06072070320516132, + 0.06067483027576162, + 0.05880810337001966, + 0.05401716579496743, + 0.045196259875010136, + 0.030099966701154113 + ], + "n_valid_labels": 15504, + "n_masked_labels": 0, + "mae_median": 3.675196740065074, + "n_mase_elements": 15504, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.38667926331809765, + "wql": 0.3745815164439069 + } + }, + { + "config_id": "LOOP_SEATTLE__H__medium", + "leaderboard_key": "loop_seattle/H/medium", + "dataset": "LOOP_SEATTLE/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.1535310881157237, + "wql": 0.14911283164622935 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7457352373040314, + "wql": 0.0557017886351622, + "wsql_by_level": [ + 0.04888908578973755, + 0.06303335510990721, + 0.06723265186957056, + 0.06657004389214155, + 0.06332802518499142, + 0.05914505076459675, + 0.054312030239939864, + 0.046411140556750656, + 0.03239471430882428 + ], + "n_valid_labels": 155040, + "n_masked_labels": 0, + "mae_median": 3.5331215905354303, + "n_mase_elements": 155040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6464803983065416, + "wql": 0.37355462987460974 + } + }, + { + "config_id": "LOOP_SEATTLE__H__long", + "leaderboard_key": "loop_seattle/H/long", + "dataset": "LOOP_SEATTLE/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.2448539713840052, + "wql": 0.17526380961630228 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7447492645323008, + "wql": 0.054554759857158346, + "wsql_by_level": [ + 0.046157238023110746, + 0.058708877590099226, + 0.06316799123313681, + 0.0638524453478634, + 0.062326238832293754, + 0.05944567840059538, + 0.055180395281399966, + 0.04785374564203461, + 0.03430022836389123 + ], + "n_valid_labels": 232560, + "n_masked_labels": 0, + "mae_median": 3.4981739795014217, + "n_mase_elements": 232560, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.5982623517715115, + "wql": 0.31127224711475115 + } + }, + { + "config_id": "LOOP_SEATTLE__D__short", + "leaderboard_key": "loop_seattle/D/short", + "dataset": "LOOP_SEATTLE/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.1854124643746355, + "wql": 0.09281728785965133 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6149294273273097, + "wql": 0.02860663214797443, + "wsql_by_level": [ + 0.02057548249854676, + 0.029320342206399428, + 0.03382678160728845, + 0.03561741473160453, + 0.03543584563509681, + 0.033358246396699626, + 0.029572815554361774, + 0.023881903217986736, + 0.015870857483785777 + ], + "n_valid_labels": 9690, + "n_masked_labels": 0, + "mae_median": 1.988901551662953, + "n_mase_elements": 9690, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.5187472258035651, + "wql": 0.30820370652534484 + } + }, + { + "config_id": "SZ_TAXI__T__short", + "leaderboard_key": "sz_taxi/15T/short", + "dataset": "SZ_TAXI/15T", + "term": "short", + "freq": "15T", + "prediction_length": 48, + "seasonality": 96, + "n_variates": 1, + "n_instances": 156, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7251090475210906, + "wql": 0.3023498132057821 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 156, + "instances": 156, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.5253134630737146, + "wql": 0.19957232849982873, + "wsql_by_level": [ + 0.10434474158901273, + 0.1687365906156887, + 0.21134821472583887, + 0.2385715837924345, + 0.25189722727420316, + 0.2509554294841633, + 0.23424131158083344, + 0.19915171044506766, + 0.1369041469912161 + ], + "n_valid_labels": 7488, + "n_masked_labels": 0, + "mae_median": 2.8193448111928636, + "n_mase_elements": 7488, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7244613273956361, + "wql": 0.6600709502142075 + } + }, + { + "config_id": "SZ_TAXI__T__medium", + "leaderboard_key": "sz_taxi/15T/medium", + "dataset": "SZ_TAXI/15T", + "term": "medium", + "freq": "15T", + "prediction_length": 480, + "seasonality": 96, + "n_variates": 1, + "n_instances": 156, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.6350051480164337, + "wql": 0.3916041859838231 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 156, + "instances": 156, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.4740483934794083, + "wql": 0.19752110449247676, + "wsql_by_level": [ + 0.10324849136334592, + 0.16458878061899584, + 0.20652001264257402, + 0.23241993612444287, + 0.24481149928185922, + 0.24429403087468196, + 0.23121224117348302, + 0.2018943340655429, + 0.1487006142873649 + ], + "n_valid_labels": 74880, + "n_masked_labels": 0, + "mae_median": 2.7093955212973957, + "n_mase_elements": 74880, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.746526850940018, + "wql": 0.5043896657954422 + } + }, + { + "config_id": "SZ_TAXI__T__long", + "leaderboard_key": "sz_taxi/15T/long", + "dataset": "SZ_TAXI/15T", + "term": "long", + "freq": "15T", + "prediction_length": 720, + "seasonality": 96, + "n_variates": 1, + "n_instances": 156, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.6084219160390921, + "wql": 0.45522272202116565 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 156, + "instances": 156, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.4978391379899635, + "wql": 0.21618287588037965, + "wsql_by_level": [ + 0.11665881574868144, + 0.18275125191262329, + 0.22683677642562716, + 0.2531201382222142, + 0.26324325774594015, + 0.2607274533672871, + 0.24826756825488236, + 0.22324937135147518, + 0.17079124989468625 + ], + "n_valid_labels": 112320, + "n_masked_labels": 0, + "mae_median": 2.92350600487793, + "n_mase_elements": 112320, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8182465569796741, + "wql": 0.47489473926200065 + } + }, + { + "config_id": "SZ_TAXI__H__short", + "leaderboard_key": "sz_taxi/H/short", + "dataset": "SZ_TAXI/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 156, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.6087142479652129, + "wql": 0.20653078520030457 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 156, + "instances": 156, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.4875431261427326, + "wql": 0.13033839077389842, + "wsql_by_level": [ + 0.07199944083105722, + 0.1097668110154709, + 0.1359962397737171, + 0.15319742922427634, + 0.16127636481926932, + 0.1605978800099127, + 0.1507016857332889, + 0.13105822984673804, + 0.09845143571135503 + ], + "n_valid_labels": 7488, + "n_masked_labels": 0, + "mae_median": 1.7829334900829379, + "n_mase_elements": 7488, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8009392383576915, + "wql": 0.6310845651774833 + } + }, + { + "config_id": "M_DENSE__H__short", + "leaderboard_key": "m_dense/H/short", + "dataset": "M_DENSE/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 30, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.8744657675879529, + "wql": 0.18983266370122717 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 30, + "instances": 30, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.688828159809886, + "wql": 0.11453590052677638, + "wsql_by_level": [ + 0.07829500439354627, + 0.10705281863496864, + 0.12463062218778721, + 0.13517607435690446, + 0.14018094207327078, + 0.13709872001438503, + 0.12641477886432598, + 0.1075532662274771, + 0.07442087798832203 + ], + "n_valid_labels": 1440, + "n_masked_labels": 0, + "mae_median": 88.29403768910302, + "n_mase_elements": 1440, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.787713121932591, + "wql": 0.6033519115922091 + } + }, + { + "config_id": "M_DENSE__H__medium", + "leaderboard_key": "m_dense/H/medium", + "dataset": "M_DENSE/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 1, + "n_instances": 30, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.171624112893389, + "wql": 0.3497462745339787 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 30, + "instances": 30, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9203189641973123, + "wql": 0.15444210942940284, + "wsql_by_level": [ + 0.08869664128769453, + 0.13080053501779404, + 0.1564485590854493, + 0.1732081044651344, + 0.18535997434923057, + 0.1904569532216121, + 0.1846962266572308, + 0.16295708912561477, + 0.11735490165486522 + ], + "n_valid_labels": 14400, + "n_masked_labels": 0, + "mae_median": 108.79898692104551, + "n_mase_elements": 14400, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7855070189060337, + "wql": 0.4415832867274714 + } + }, + { + "config_id": "M_DENSE__H__long", + "leaderboard_key": "m_dense/H/long", + "dataset": "M_DENSE/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 1, + "n_instances": 30, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0805183298420056, + "wql": 0.3841191250034235 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 30, + "instances": 30, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.2590890418439884, + "wql": 0.20827668786210912, + "wsql_by_level": [ + 0.10003421890787681, + 0.1589488222136617, + 0.20084853154265966, + 0.23194170091927616, + 0.25626670983220046, + 0.2685461306465581, + 0.26412983274659335, + 0.23305544832346034, + 0.1607187956266955 + ], + "n_valid_labels": 21600, + "n_masked_labels": 0, + "mae_median": 150.18908988224135, + "n_mase_elements": 21600, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.1652639359001837, + "wql": 0.5422190000569559 + } + }, + { + "config_id": "M_DENSE__D__short", + "leaderboard_key": "m_dense/D/short", + "dataset": "M_DENSE/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 30, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.007688577826318, + "wql": 0.1992117768924222 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 30, + "instances": 30, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.129382031035162, + "wql": 0.10082283649820577, + "wsql_by_level": [ + 0.0670597289105118, + 0.10289963311346086, + 0.12419375374826715, + 0.13437575672206156, + 0.13572127839960718, + 0.1233004887915969, + 0.09871895205665294, + 0.07102796341869835, + 0.05010797332299511 + ], + "n_valid_labels": 900, + "n_masked_labels": 0, + "mae_median": 79.54156551361083, + "n_mase_elements": 900, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.1207649425493624, + "wql": 0.5061088158088758 + } + }, + { + "config_id": "ett1__T__short", + "leaderboard_key": "ett1/15T/short", + "dataset": "ett1/15T", + "term": "short", + "freq": "15T", + "prediction_length": 48, + "seasonality": 96, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.2054822899524387, + "wql": 0.48104386522982623 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8834813909515595, + "wql": 0.36847849429723434, + "wsql_by_level": [ + 0.17944074270957083, + 0.2926985113305371, + 0.36551931366442625, + 0.4174799951028138, + 0.4473617114209216, + 0.4621035088887334, + 0.4507307705621551, + 0.403406504860172, + 0.2975653901357787 + ], + "n_valid_labels": 336, + "n_masked_labels": 0, + "mae_median": 1.6350111890850323, + "n_mase_elements": 336, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7328862467041442, + "wql": 0.7659976998588018 + } + }, + { + "config_id": "ett1__T__medium", + "leaderboard_key": "ett1/15T/medium", + "dataset": "ett1/15T", + "term": "medium", + "freq": "15T", + "prediction_length": 480, + "seasonality": 96, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7745679584044315, + "wql": 0.4386794376669185 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0568757063697853, + "wql": 0.42943729197013836, + "wsql_by_level": [ + 0.25768699873101664, + 0.4510634406196604, + 0.5418897189688704, + 0.5727325799832157, + 0.5617824443871703, + 0.5126510015157405, + 0.4367768537612832, + 0.332158930597105, + 0.19819365916718354 + ], + "n_valid_labels": 3360, + "n_masked_labels": 0, + "mae_median": 1.8319223917798981, + "n_mase_elements": 3360, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.3644712447786926, + "wql": 0.9789318921672423 + } + }, + { + "config_id": "ett1__T__long", + "leaderboard_key": "ett1/15T/long", + "dataset": "ett1/15T", + "term": "long", + "freq": "15T", + "prediction_length": 720, + "seasonality": 96, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.327073089604087, + "wql": 0.5796800252115644 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.3686001365820024, + "wql": 0.539273507159843, + "wsql_by_level": [ + 0.436707908502169, + 0.5979795040954902, + 0.692031869631864, + 0.7206896249009485, + 0.6880686120605459, + 0.6090874775134094, + 0.505230904850884, + 0.37807927915052125, + 0.22558638373275486 + ], + "n_valid_labels": 5040, + "n_masked_labels": 0, + "mae_median": 2.35893866104473, + "n_mase_elements": 5040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.0312922078695035, + "wql": 0.9302951347392481 + } + }, + { + "config_id": "ett1__H__short", + "leaderboard_key": "ett1/H/short", + "dataset": "ett1/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0441605493380515, + "wql": 0.5044116168241106 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7785759640147989, + "wql": 0.3582869683314469, + "wsql_by_level": [ + 0.21817243135709533, + 0.2927664229114334, + 0.36475596219573647, + 0.42000772198398495, + 0.45135279965954955, + 0.4558295404053612, + 0.428081728333339, + 0.357397400906257, + 0.23621870723026536 + ], + "n_valid_labels": 336, + "n_masked_labels": 0, + "mae_median": 5.454555589173522, + "n_mase_elements": 336, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7456477497721776, + "wql": 0.710306734383523 + } + }, + { + "config_id": "ett1__H__medium", + "leaderboard_key": "ett1/H/medium", + "dataset": "ett1/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.2235872159229322, + "wql": 0.5499353323396741 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.477627396586257, + "wql": 0.4600863442386255, + "wsql_by_level": [ + 0.2942856120125123, + 0.47199714397965276, + 0.5520540811510296, + 0.5769104613958314, + 0.5691173167633071, + 0.535798635435856, + 0.4775999016832054, + 0.3934690517511789, + 0.26954489397505577 + ], + "n_valid_labels": 3360, + "n_masked_labels": 0, + "mae_median": 8.708666547549157, + "n_mase_elements": 3360, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.2076191850956095, + "wql": 0.8366189935118548 + } + }, + { + "config_id": "ett1__H__long", + "leaderboard_key": "ett1/H/long", + "dataset": "ett1/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.4320631719624162, + "wql": 0.5783242328839591 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.479921056513577, + "wql": 0.43302006585015346, + "wsql_by_level": [ + 0.3469217089023302, + 0.4906160798938698, + 0.5591240526194586, + 0.5723540571544283, + 0.5470718639810389, + 0.4903037309004739, + 0.4071002445036354, + 0.30423119864717524, + 0.17945765604897054 + ], + "n_valid_labels": 5040, + "n_masked_labels": 0, + "mae_median": 9.21141216519126, + "n_mase_elements": 5040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.0334188361855428, + "wql": 0.748749648083723 + } + }, + { + "config_id": "ett1__D__short", + "leaderboard_key": "ett1/D/short", + "dataset": "ett1/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.8181967261759215, + "wql": 0.48528320354978605 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.6371480380399162, + "wql": 0.3359713558753807, + "wsql_by_level": [ + 0.23058120318013792, + 0.35273078369618494, + 0.41298228247430435, + 0.4330650657721282, + 0.4203719410123742, + 0.3860600204173565, + 0.33470767926853306, + 0.2705534887501378, + 0.18268973830726898 + ], + "n_valid_labels": 210, + "n_masked_labels": 0, + "mae_median": 133.43625868388585, + "n_mase_elements": 210, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9004240379880171, + "wql": 0.6923201821488817 + } + }, + { + "config_id": "ett1__W__short", + "leaderboard_key": "ett1/W/short", + "dataset": "ett1/W", + "term": "short", + "freq": "W-THU", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.2444126904903803, + "wql": 0.25814356436755426 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.1571879658449589, + "wql": 0.211399751073413, + "wsql_by_level": [ + 0.09944751787150526, + 0.15754978516122203, + 0.19398356871801317, + 0.2263074018787588, + 0.26736306108949087, + 0.29190290666273344, + 0.2860258137000635, + 0.23113717693690852, + 0.148880527642021 + ], + "n_valid_labels": 56, + "n_masked_labels": 0, + "mae_median": 667.2682674952915, + "n_mase_elements": 56, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9299069148747999, + "wql": 0.8189231894714768 + } + }, + { + "config_id": "ett2__T__short", + "leaderboard_key": "ett2/15T/short", + "dataset": "ett2/15T", + "term": "short", + "freq": "15T", + "prediction_length": 48, + "seasonality": 96, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7618250880337474, + "wql": 0.093929612604377 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.176754127358234, + "wql": 0.14636274583174513, + "wsql_by_level": [ + 0.0614754103732968, + 0.10388060768172475, + 0.13615910557170688, + 0.16057700598487423, + 0.17875378500888445, + 0.18888514982619195, + 0.18820754783990215, + 0.17358120301970495, + 0.12574489717942022 + ], + "n_valid_labels": 336, + "n_masked_labels": 0, + "mae_median": 2.852351265737698, + "n_mase_elements": 336, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.544651319367033, + "wql": 1.558217283916753 + } + }, + { + "config_id": "ett2__T__medium", + "leaderboard_key": "ett2/15T/medium", + "dataset": "ett2/15T", + "term": "medium", + "freq": "15T", + "prediction_length": 480, + "seasonality": 96, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9027189688220486, + "wql": 0.13649095157039726 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8815468505255447, + "wql": 0.10588928920879413, + "wsql_by_level": [ + 0.06146360266535463, + 0.09705842910239885, + 0.1207387766195251, + 0.134126237331237, + 0.13853410372600974, + 0.13474120815790544, + 0.11984479546747699, + 0.09346311376021102, + 0.05303333604902833 + ], + "n_valid_labels": 3360, + "n_masked_labels": 0, + "mae_median": 2.108253218836728, + "n_mase_elements": 3360, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9765462795978119, + "wql": 0.775797135198227 + } + }, + { + "config_id": "ett2__T__long", + "leaderboard_key": "ett2/15T/long", + "dataset": "ett2/15T", + "term": "long", + "freq": "15T", + "prediction_length": 720, + "seasonality": 96, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0565955316162643, + "wql": 0.16755935574924186 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.1489581830981204, + "wql": 0.14920225918323624, + "wsql_by_level": [ + 0.08513583353163534, + 0.13196058676067485, + 0.16468021114074782, + 0.18490955796604733, + 0.19432254063121465, + 0.19224723529535914, + 0.17300344899620967, + 0.1369415192232843, + 0.07961939910395305 + ], + "n_valid_labels": 5040, + "n_masked_labels": 0, + "mae_median": 2.9307705700811413, + "n_mase_elements": 5040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.087415334172926, + "wql": 0.8904442161171972 + } + }, + { + "config_id": "ett2__H__short", + "leaderboard_key": "ett2/H/short", + "dataset": "ett2/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9915624508458626, + "wql": 0.11931409133707109 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6870573970374232, + "wql": 0.07507390847633981, + "wsql_by_level": [ + 0.05449797719136931, + 0.07813260626168261, + 0.09293251405320811, + 0.09761995076530036, + 0.09562177398869459, + 0.08507681010686009, + 0.07133019303401986, + 0.057549457262122655, + 0.04290389362380068 + ], + "n_valid_labels": 336, + "n_masked_labels": 0, + "mae_median": 5.862776726484299, + "n_mase_elements": 336, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.692903806967803, + "wql": 0.6292124227326217 + } + }, + { + "config_id": "ett2__H__medium", + "leaderboard_key": "ett2/H/medium", + "dataset": "ett2/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 2.649073318865916, + "wql": 0.345818716053239 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 2.516597034960104, + "wql": 0.24470414860703618, + "wsql_by_level": [ + 0.11184785199276316, + 0.1861201901506414, + 0.2437261443500129, + 0.2884189727835225, + 0.3177121806313262, + 0.3287257180852592, + 0.31058527342687, + 0.256623658788455, + 0.15857734725447492 + ], + "n_valid_labels": 3360, + "n_masked_labels": 0, + "mae_median": 18.070259208232166, + "n_mase_elements": 3360, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9499914619341205, + "wql": 0.7076081693894318 + } + }, + { + "config_id": "ett2__H__long", + "leaderboard_key": "ett2/H/long", + "dataset": "ett2/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 3.171779953228176, + "wql": 0.3702966971424018 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 3.2087037882090534, + "wql": 0.3589475235881692, + "wsql_by_level": [ + 0.2975899836914184, + 0.39998424266319504, + 0.4434476189707895, + 0.4565833955058329, + 0.444434374003974, + 0.4096026086678272, + 0.3516032158616433, + 0.26947074551911854, + 0.15781152740972443 + ], + "n_valid_labels": 5040, + "n_masked_labels": 0, + "mae_median": 25.077998957404542, + "n_mase_elements": 5040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.0116413608526964, + "wql": 0.9693511348013235 + } + }, + { + "config_id": "ett2__D__short", + "leaderboard_key": "ett2/D/short", + "dataset": "ett2/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 4.704440132303346, + "wql": 0.31867490583739955 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 4.658367511710397, + "wql": 0.32433218424993976, + "wsql_by_level": [ + 0.34066828208004124, + 0.4156739756437886, + 0.4278678778355242, + 0.41556528386833824, + 0.38395615121431237, + 0.33715142341935384, + 0.27756452271202087, + 0.20527345885854595, + 0.11526868261753281 + ], + "n_valid_labels": 210, + "n_masked_labels": 0, + "mae_median": 519.2037216459001, + "n_mase_elements": 210, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9902065667120327, + "wql": 1.017752506736212 + } + }, + { + "config_id": "ett2__W__short", + "leaderboard_key": "ett2/W/short", + "dataset": "ett2/W", + "term": "short", + "freq": "W-THU", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.7680609986327813, + "wql": 0.21133928538207686 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.7601113673395308, + "wql": 0.20197153836388906, + "wsql_by_level": [ + 0.1619286176877261, + 0.20067823126553397, + 0.22522116800619596, + 0.23882640519789786, + 0.24652343941183336, + 0.23885816307819938, + 0.211606067476476, + 0.17268458031993075, + 0.1214171728312081 + ], + "n_valid_labels": 56, + "n_masked_labels": 0, + "mae_median": 2399.29308114733, + "n_mase_elements": 56, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9955037573367673, + "wql": 0.9556743697639934 + } + }, + { + "config_id": "jena_weather__T__short", + "leaderboard_key": "jena_weather/10T/short", + "dataset": "jena_weather/10T", + "term": "short", + "freq": "10T", + "prediction_length": 48, + "seasonality": 144, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7621672521709891, + "wql": 0.1366740261223883 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.4442021623518291, + "wql": 0.022640310331668165, + "wsql_by_level": [ + 0.009698602804243625, + 0.016195956584515576, + 0.02004984554994266, + 0.02257647451253829, + 0.02423060539986629, + 0.02615212240432983, + 0.028766293801975783, + 0.029527719693523104, + 0.026565172234078352 + ], + "n_valid_labels": 1008, + "n_masked_labels": 0, + "mae_median": 3.818365289099766, + "n_mase_elements": 1008, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.5828145477079276, + "wql": 0.16565188700444305 + } + }, + { + "config_id": "jena_weather__T__medium", + "leaderboard_key": "jena_weather/10T/medium", + "dataset": "jena_weather/10T", + "term": "medium", + "freq": "10T", + "prediction_length": 480, + "seasonality": 144, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9778443284819783, + "wql": 0.22790411536869984 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8788517204839676, + "wql": 0.09069959933475048, + "wsql_by_level": [ + 0.05205743365849937, + 0.07638991867412631, + 0.09126444135728323, + 0.10031931211113146, + 0.10454245852363586, + 0.10679547998915807, + 0.10539201485292439, + 0.09890891388892274, + 0.08062642095707283 + ], + "n_valid_labels": 10080, + "n_masked_labels": 0, + "mae_median": 17.679694449878344, + "n_mase_elements": 10080, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8987644504195382, + "wql": 0.3979726262863575 + } + }, + { + "config_id": "jena_weather__T__long", + "leaderboard_key": "jena_weather/10T/long", + "dataset": "jena_weather/10T", + "term": "long", + "freq": "10T", + "prediction_length": 720, + "seasonality": 144, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9055523182794231, + "wql": 0.2428907683297211 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7390269742258904, + "wql": 0.08704671481373542, + "wsql_by_level": [ + 0.05944557494081884, + 0.07988061038266817, + 0.0910746121714075, + 0.09718136059907193, + 0.09897501869878005, + 0.09850470248540633, + 0.0956153519649988, + 0.08868113269139574, + 0.07406206938907141 + ], + "n_valid_labels": 15120, + "n_masked_labels": 0, + "mae_median": 16.92018888847451, + "n_mase_elements": 15120, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8161063246241411, + "wql": 0.35837802898943705 + } + }, + { + "config_id": "jena_weather__H__short", + "leaderboard_key": "jena_weather/H/short", + "dataset": "jena_weather/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7591774901189448, + "wql": 0.1835169108215369 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.5691385322762694, + "wql": 0.07821806786489843, + "wsql_by_level": [ + 0.05864341193197026, + 0.08349669602224338, + 0.09234835216797216, + 0.09171038738463066, + 0.08698731780541988, + 0.08488629557188865, + 0.08071425352010708, + 0.07145886591399501, + 0.053717030465858864 + ], + "n_valid_labels": 1008, + "n_masked_labels": 0, + "mae_median": 14.535428384000191, + "n_mase_elements": 1008, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7496778285498154, + "wql": 0.4262172216976913 + } + }, + { + "config_id": "jena_weather__H__medium", + "leaderboard_key": "jena_weather/H/medium", + "dataset": "jena_weather/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0707310989927863, + "wql": 0.3640989806826866 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8999931955727738, + "wql": 0.12011335670179996, + "wsql_by_level": [ + 0.08649859910667136, + 0.12000338653131623, + 0.1333400892056758, + 0.13574297825241735, + 0.1315370087550702, + 0.1323934215605575, + 0.12901211673060306, + 0.11811853446515624, + 0.09437407570873192 + ], + "n_valid_labels": 10080, + "n_masked_labels": 0, + "mae_median": 22.656611794340915, + "n_mase_elements": 10080, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8405408196505901, + "wql": 0.32989204330258515 + } + }, + { + "config_id": "jena_weather__H__long", + "leaderboard_key": "jena_weather/H/long", + "dataset": "jena_weather/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.4925574952113163, + "wql": 0.44387827099252614 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0999205442241955, + "wql": 0.1529018553792393, + "wsql_by_level": [ + 0.1393655405505495, + 0.1771554316057474, + 0.1870437280173267, + 0.18238863479800926, + 0.16903872650994275, + 0.15771058949850916, + 0.14365630205028396, + 0.1243541660939381, + 0.09540357928884705 + ], + "n_valid_labels": 15120, + "n_masked_labels": 0, + "mae_median": 29.46430710509406, + "n_mase_elements": 15120, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7369367999243933, + "wql": 0.344467989021733 + } + }, + { + "config_id": "jena_weather__D__short", + "leaderboard_key": "jena_weather/D/short", + "dataset": "jena_weather/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.8578467510262653, + "wql": 0.23138296558762514 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.456992734607528, + "wql": 0.11853793839110535, + "wsql_by_level": [ + 0.044030875887410004, + 0.10336844446854378, + 0.14012768779454454, + 0.1570364189899934, + 0.15837972522010976, + 0.14998249663322527, + 0.1339490394525591, + 0.10795546290020093, + 0.0720112941733616 + ], + "n_valid_labels": 630, + "n_masked_labels": 0, + "mae_median": 27.606389008853345, + "n_mase_elements": 630, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.784237307949481, + "wql": 0.5123019237395625 + } + }, + { + "config_id": "bitbrains_fast_storage__T__short", + "leaderboard_key": "bitbrains_fast_storage/5T/short", + "dataset": "bitbrains_fast_storage/5T", + "term": "short", + "freq": "5T", + "prediction_length": 48, + "seasonality": 288, + "n_variates": 2, + "n_instances": 1250, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.9726733005020567, + "wql": 1.8982594024982165 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1250, + "instances": 1250, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0986491830210505, + "wql": 0.48614835981248244, + "wsql_by_level": [ + 0.15865364680833446, + 0.29473435333286835, + 0.4136752207288251, + 0.5129838829195406, + 0.6000651722815333, + 0.6619564350792888, + 0.6671568599334685, + 0.6068094780152377, + 0.4593001892132455 + ], + "n_valid_labels": 107692, + "n_masked_labels": 12308, + "mae_median": 176.2818403440116, + "n_mase_elements": 104420, + "n_seasonal_error_zero": 56, + "n_seasonal_error_nan": 52 + }, + "relative": { + "mase": 0.5569341779713032, + "wql": 0.2561021740088229 + } + }, + { + "config_id": "bitbrains_fast_storage__T__medium", + "leaderboard_key": "bitbrains_fast_storage/5T/medium", + "dataset": "bitbrains_fast_storage/5T", + "term": "medium", + "freq": "5T", + "prediction_length": 480, + "seasonality": 288, + "n_variates": 2, + "n_instances": 1250, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.332305698225943, + "wql": 0.7965658755181099 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1250, + "instances": 1250, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.1640586747354058, + "wql": 0.6520023345876164, + "wsql_by_level": [ + 0.5174015061732129, + 0.7737981582758219, + 0.8670414735725226, + 0.8650996086571522, + 0.8084143107886952, + 0.708320654715329, + 0.5863439711177592, + 0.45044035982822206, + 0.2911609681598329 + ], + "n_valid_labels": 1151890, + "n_masked_labels": 48110, + "mae_median": 502.47428748720966, + "n_mase_elements": 1112970, + "n_seasonal_error_zero": 58, + "n_seasonal_error_nan": 66 + }, + "relative": { + "mase": 0.8737174030595458, + "wql": 0.8185165277931783 + } + }, + { + "config_id": "bitbrains_fast_storage__T__long", + "leaderboard_key": "bitbrains_fast_storage/5T/long", + "dataset": "bitbrains_fast_storage/5T", + "term": "long", + "freq": "5T", + "prediction_length": 720, + "seasonality": 288, + "n_variates": 2, + "n_instances": 1250, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.5068539886984111, + "wql": 0.6979053733746295 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1250, + "instances": 1250, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.2892798138967978, + "wql": 0.5071987222447216, + "wsql_by_level": [ + 0.3731889209345171, + 0.5554480671389611, + 0.6396459013110074, + 0.66268844329028, + 0.6421868304020447, + 0.585689351934134, + 0.49528584027310896, + 0.373834451246938, + 0.2368206936715045 + ], + "n_valid_labels": 1732080, + "n_masked_labels": 67920, + "mae_median": 468.8067510545184, + "n_mase_elements": 1677544, + "n_seasonal_error_zero": 58, + "n_seasonal_error_nan": 66 + }, + "relative": { + "mase": 0.8556103136511923, + "wql": 0.7267442573084499 + } + }, + { + "config_id": "bitbrains_fast_storage__H__short", + "leaderboard_key": "bitbrains_fast_storage/H/short", + "dataset": "bitbrains_fast_storage/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 2, + "n_instances": 1250, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.5571822067903167, + "wql": 0.6231221387021137 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1250, + "instances": 1250, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.3764645616613866, + "wql": 0.4841092445412747, + "wsql_by_level": [ + 0.30134518050256137, + 0.5214026469321508, + 0.6151416802963156, + 0.6380871323277792, + 0.6074396901088706, + 0.5425275344138116, + 0.4756118107638374, + 0.39109825731646863, + 0.26432926820967695 + ], + "n_valid_labels": 116442, + "n_masked_labels": 3558, + "mae_median": 428.8554735710875, + "n_mase_elements": 112610, + "n_seasonal_error_zero": 58, + "n_seasonal_error_nan": 66 + }, + "relative": { + "mase": 0.8839457294458639, + "wql": 0.7769090752410343 + } + }, + { + "config_id": "bitbrains_rnd__T__short", + "leaderboard_key": "bitbrains_rnd/5T/short", + "dataset": "bitbrains_rnd/5T", + "term": "short", + "freq": "5T", + "prediction_length": 48, + "seasonality": 288, + "n_variates": 2, + "n_instances": 500, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.8369702659182979, + "wql": 0.895586111036325 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 500, + "instances": 500, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.5728206601188075, + "wql": 0.23880194006247718, + "wsql_by_level": [ + 0.13491084546943785, + 0.19999281899956795, + 0.24218838116998295, + 0.2647192862308561, + 0.26902092358176416, + 0.26255308371190206, + 0.26954814402852295, + 0.27590311188131844, + 0.230380865488942 + ], + "n_valid_labels": 46368, + "n_masked_labels": 1632, + "mae_median": 144.16201946833215, + "n_mase_elements": 45888, + "n_seasonal_error_zero": 10, + "n_seasonal_error_nan": 34 + }, + "relative": { + "mase": 0.6843978614823627, + "wql": 0.2666431927870656 + } + }, + { + "config_id": "bitbrains_rnd__T__medium", + "leaderboard_key": "bitbrains_rnd/5T/medium", + "dataset": "bitbrains_rnd/5T", + "term": "medium", + "freq": "5T", + "prediction_length": 480, + "seasonality": 288, + "n_variates": 2, + "n_instances": 500, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9740075110165132, + "wql": 1.1044931903333195 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 500, + "instances": 500, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8505866982272479, + "wql": 0.7622699206923045, + "wsql_by_level": [ + 0.16669437352556968, + 0.38021488282055815, + 0.6262699843004962, + 0.8264883436401151, + 0.9610528285996203, + 1.0326957225256916, + 1.0408201005984077, + 0.983885780451921, + 0.84230726976836 + ], + "n_valid_labels": 455110, + "n_masked_labels": 24890, + "mae_median": 288.6219528009768, + "n_mase_elements": 441864, + "n_seasonal_error_zero": 10, + "n_seasonal_error_nan": 54 + }, + "relative": { + "mase": 0.8732855636190542, + "wql": 0.6901535721214024 + } + }, + { + "config_id": "bitbrains_rnd__T__long", + "leaderboard_key": "bitbrains_rnd/5T/long", + "dataset": "bitbrains_rnd/5T", + "term": "long", + "freq": "5T", + "prediction_length": 720, + "seasonality": 288, + "n_variates": 2, + "n_instances": 500, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.1660081104198932, + "wql": 0.9977535818816068 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 500, + "instances": 500, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0051439310532821, + "wql": 0.7497819327788138, + "wsql_by_level": [ + 0.27866980031775795, + 0.45376107560939244, + 0.6005214022522202, + 0.7337538310342374, + 0.8477614361077564, + 0.9400655521192242, + 1.0059148577545345, + 1.016722453013792, + 0.8708669868004091 + ], + "n_valid_labels": 684238, + "n_masked_labels": 35762, + "mae_median": 277.3228774681703, + "n_mase_elements": 657984, + "n_seasonal_error_zero": 12, + "n_seasonal_error_nan": 64 + }, + "relative": { + "mase": 0.8620385416455791, + "wql": 0.7514700487116694 + } + }, + { + "config_id": "bitbrains_rnd__H__short", + "leaderboard_key": "bitbrains_rnd/H/short", + "dataset": "bitbrains_rnd/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 2, + "n_instances": 500, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.1175347302132743, + "wql": 0.9314629241561541 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 500, + "instances": 500, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.90871419423913, + "wql": 0.6462311125358579, + "wsql_by_level": [ + 0.19663733734912392, + 0.37599464311799885, + 0.5397362602756339, + 0.6867490644120583, + 0.7968690038660001, + 0.8672781301497587, + 0.8825818401192064, + 0.8265978136156144, + 0.6436359199173273 + ], + "n_valid_labels": 46216, + "n_masked_labels": 1784, + "mae_median": 258.13524063158667, + "n_mase_elements": 44928, + "n_seasonal_error_zero": 10, + "n_seasonal_error_nan": 54 + }, + "relative": { + "mase": 0.813141792976499, + "wql": 0.6937808213046182 + } + }, + { + "config_id": "bizitobs_application__S__short", + "leaderboard_key": "bizitobs_application/10S/short", + "dataset": "bizitobs_application", + "term": "short", + "freq": "10S", + "prediction_length": 60, + "seasonality": 360, + "n_variates": 2, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.3935671590031806, + "wql": 0.01840457246049758 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6708810328837406, + "wql": 0.01075107106332808, + "wsql_by_level": [ + 0.006019794009605218, + 0.009818323618006084, + 0.012412521440235717, + 0.013945084853510335, + 0.01447138539480175, + 0.013847764172975664, + 0.012155403051208458, + 0.009148930690939625, + 0.004940432338669867 + ], + "n_valid_labels": 120, + "n_masked_labels": 0, + "mae_median": 374.45288648605344, + "n_mase_elements": 120, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.4814127747984691, + "wql": 0.5841521766617239 + } + }, + { + "config_id": "bizitobs_application__S__medium", + "leaderboard_key": "bizitobs_application/10S/medium", + "dataset": "bizitobs_application", + "term": "medium", + "freq": "10S", + "prediction_length": 600, + "seasonality": 360, + "n_variates": 2, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9183336447716528, + "wql": 0.013742470259025481 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6789866700340087, + "wql": 0.009373706493337935, + "wsql_by_level": [ + 0.005334563257990787, + 0.008359969434072016, + 0.01048274925440275, + 0.011718755959105476, + 0.012273711864924227, + 0.01188418322989481, + 0.010658619327716756, + 0.008473647133367393, + 0.005177158978567206 + ], + "n_valid_labels": 1200, + "n_masked_labels": 0, + "mae_median": 293.83398235638936, + "n_mase_elements": 1200, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7393681739743309, + "wql": 0.6820976372265879 + } + }, + { + "config_id": "bizitobs_application__S__long", + "leaderboard_key": "bizitobs_application/10S/long", + "dataset": "bizitobs_application", + "term": "long", + "freq": "10S", + "prediction_length": 900, + "seasonality": 360, + "n_variates": 2, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7487259254586917, + "wql": 0.012942679940654697 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.751404281999801, + "wql": 0.010241096761592216, + "wsql_by_level": [ + 0.006214063855240937, + 0.009720891435174555, + 0.011782661287531061, + 0.012787390397560735, + 0.013080385254730506, + 0.012604974217947316, + 0.01132520703812716, + 0.009060978273668668, + 0.005593319094349 + ], + "n_valid_labels": 1800, + "n_masked_labels": 0, + "mae_median": 318.70842679977414, + "n_mase_elements": 1800, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.0035772189128733, + "wql": 0.7912655499904279 + } + }, + { + "config_id": "bizitobs_service__S__short", + "leaderboard_key": "bizitobs_service/10S/short", + "dataset": "bizitobs_service", + "term": "short", + "freq": "10S", + "prediction_length": 60, + "seasonality": 360, + "n_variates": 2, + "n_instances": 21, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0559084960397855, + "wql": 0.025515037101462117 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 21, + "instances": 21, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.5716215922628061, + "wql": 0.010319123414826405, + "wsql_by_level": [ + 0.005843128787350773, + 0.009361252978874, + 0.011757588105875277, + 0.013187036195168339, + 0.013686031747664725, + 0.01327711455758343, + 0.011833534415935213, + 0.00916678341790645, + 0.0047596405270794485 + ], + "n_valid_labels": 2520, + "n_masked_labels": 0, + "mae_median": 18.35130290504959, + "n_mase_elements": 2520, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.5413552352374177, + "wql": 0.4044330162559347 + } + }, + { + "config_id": "bizitobs_service__S__medium", + "leaderboard_key": "bizitobs_service/10S/medium", + "dataset": "bizitobs_service", + "term": "medium", + "freq": "10S", + "prediction_length": 600, + "seasonality": 360, + "n_variates": 2, + "n_instances": 21, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9546641394188339, + "wql": 0.023513421962609537 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 21, + "instances": 21, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6919916045260345, + "wql": 0.010161322224569962, + "wsql_by_level": [ + 0.006004235954430059, + 0.009169244155778909, + 0.01126908746567133, + 0.012540491146339103, + 0.01305728071358965, + 0.012785201622220958, + 0.01160211845638648, + 0.009306403709321964, + 0.005717836797391201 + ], + "n_valid_labels": 25200, + "n_masked_labels": 0, + "mae_median": 16.46930223364442, + "n_mase_elements": 25200, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7248534599270637, + "wql": 0.432149869156784 + } + }, + { + "config_id": "bizitobs_service__S__long", + "leaderboard_key": "bizitobs_service/10S/long", + "dataset": "bizitobs_service", + "term": "long", + "freq": "10S", + "prediction_length": 900, + "seasonality": 360, + "n_variates": 2, + "n_instances": 21, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.8316933390369606, + "wql": 0.023678985220657325 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 21, + "instances": 21, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7751979245316605, + "wql": 0.011402983042658169, + "wsql_by_level": [ + 0.007101228748713475, + 0.010861830978253082, + 0.013158322116676259, + 0.014334855144178801, + 0.014600036060898824, + 0.013990756171320376, + 0.01248816377722239, + 0.009930413197341842, + 0.006161241189318492 + ], + "n_valid_labels": 37800, + "n_masked_labels": 0, + "mae_median": 18.65643885180906, + "n_mase_elements": 37800, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9320718204011136, + "wql": 0.48156552894464044 + } + }, + { + "config_id": "bizitobs_l2c__T__short", + "leaderboard_key": "bizitobs_l2c/5T/short", + "dataset": "bizitobs_l2c/5T", + "term": "short", + "freq": "5T", + "prediction_length": 48, + "seasonality": 288, + "n_variates": 7, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7721410982041648, + "wql": 0.22094461659341424 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.21586760686694065, + "wql": 0.068313393336314, + "wsql_by_level": [ + 0.04438422324799501, + 0.06722620465286012, + 0.08019259236188038, + 0.0858638447806305, + 0.08590422162516904, + 0.08193848027884454, + 0.07457138619195752, + 0.058897921126029075, + 0.03584166576145984 + ], + "n_valid_labels": 336, + "n_masked_labels": 0, + "mae_median": 2.2068155450480327, + "n_mase_elements": 336, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.27957015546640707, + "wql": 0.30918786069372933 + } + }, + { + "config_id": "bizitobs_l2c__T__medium", + "leaderboard_key": "bizitobs_l2c/5T/medium", + "dataset": "bizitobs_l2c/5T", + "term": "medium", + "freq": "5T", + "prediction_length": 480, + "seasonality": 288, + "n_variates": 7, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.4416925389331963, + "wql": 0.47091183801289255 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.4360644039231397, + "wql": 0.14956312335013747, + "wsql_by_level": [ + 0.11612084958407652, + 0.15309440141849454, + 0.17030048895114672, + 0.17452729380270204, + 0.17462004675542203, + 0.17211782764325634, + 0.16111471339595135, + 0.13574355531608664, + 0.08842893328410113 + ], + "n_valid_labels": 3360, + "n_masked_labels": 0, + "mae_median": 3.8862782767131216, + "n_mase_elements": 3360, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.3024669908091587, + "wql": 0.31760323541928615 + } + }, + { + "config_id": "bizitobs_l2c__T__long", + "leaderboard_key": "bizitobs_l2c/5T/long", + "dataset": "bizitobs_l2c/5T", + "term": "long", + "freq": "5T", + "prediction_length": 720, + "seasonality": 288, + "n_variates": 7, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.6820288964143004, + "wql": 0.6755692567838184 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6355636615190283, + "wql": 0.2559146890577243, + "wsql_by_level": [ + 0.13864498530377325, + 0.21285484517948342, + 0.2577756765596843, + 0.29374992215866946, + 0.3271852394596567, + 0.3365290517696887, + 0.31738031347011475, + 0.2604455983450883, + 0.15866656927336012 + ], + "n_valid_labels": 5040, + "n_masked_labels": 0, + "mae_median": 5.985398235704218, + "n_mase_elements": 5040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.37785537625061266, + "wql": 0.37881340290121696 + } + }, + { + "config_id": "bizitobs_l2c__H__short", + "leaderboard_key": "bizitobs_l2c/H/short", + "dataset": "bizitobs_l2c/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.5845833438972332, + "wql": 0.5573763030242874 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6244419046019888, + "wql": 0.20190246079510518, + "wsql_by_level": [ + 0.13328116544653304, + 0.21152984183237458, + 0.25830942221389885, + 0.27976825250254067, + 0.2806810670453333, + 0.2567682786140248, + 0.20386841098342634, + 0.12359406227872032, + 0.06932164623909463 + ], + "n_valid_labels": 336, + "n_masked_labels": 0, + "mae_median": 5.872479298285076, + "n_mase_elements": 336, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.39407324771330327, + "wql": 0.36223725282111136 + } + }, + { + "config_id": "bizitobs_l2c__H__medium", + "leaderboard_key": "bizitobs_l2c/H/medium", + "dataset": "bizitobs_l2c/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.6159633796006725, + "wql": 1.1167911109559348 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.3580894317841367, + "wql": 0.21376007954227527, + "wsql_by_level": [ + 0.11380737453866044, + 0.17502726507483876, + 0.2163298324724155, + 0.24243683559976437, + 0.25736463925625375, + 0.26608930586957624, + 0.25955270441099415, + 0.2291232656211187, + 0.16410949303685543 + ], + "n_valid_labels": 3360, + "n_masked_labels": 0, + "mae_median": 3.5224866266803776, + "n_mase_elements": 3360, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.22159501651121927, + "wql": 0.1914056061561092 + } + }, + { + "config_id": "bizitobs_l2c__H__long", + "leaderboard_key": "bizitobs_l2c/H/long", + "dataset": "bizitobs_l2c/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.280223980485366, + "wql": 1.0134048622912797 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.40083183446403475, + "wql": 0.20349861180910236, + "wsql_by_level": [ + 0.1037193761442143, + 0.1666095499484109, + 0.2050238820383989, + 0.2300337367919583, + 0.24559997720630228, + 0.2536998371074427, + 0.2455128217912824, + 0.21980905645743395, + 0.16147926879647775 + ], + "n_valid_labels": 5040, + "n_masked_labels": 0, + "mae_median": 3.7107263197515823, + "n_mase_elements": 5040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.3130950838087481, + "wql": 0.20080682398641522 + } + } + ] +} diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/EXPERIMENTS.md b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/EXPERIMENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..2e4f81bc49fe65e2c3e7ccf74947006f5a97de04 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/EXPERIMENTS.md @@ -0,0 +1,972 @@ +# Experiments + +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. + +## E0: contract bootstrap +- Hypothesis: maintain a runnable package while training the first candidate. +- Changed factor: none; provided Seasonal Naive formula, with no learned parameters. +- Seed: deterministic. Measured compute: no training. +- Checkpoint hash: not applicable. +- Outcome: provisional package published with atomic directory exchange. + +## E1: direct long-horizon quantile forecasting +- Hypothesis: a direct horizon objective and explicit seasonal context features reduce long-horizon median drift and the underestimation of uncertainty from short-patch autoregression. +- 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. +- 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. +- 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. +- Synthetic generator: newly generated damped trends, Fourier seasonality, AR noise, intermittent demand and changepoints. No downloaded synthetic assets. +- 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. +- 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. +- Completed 12,000 steps in 349.9 seconds on one H100. Measured group skills, checkpoint hashes and outcomes are recorded below. + +## Known limits and next decisions +- This first run jointly changes the architecture and objective; it does not isolate their individual causal contributions. +- 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. +- 10-second daily seasonality exceeds the 4,096-point encoder window. Longer fixed context summaries are a planned ablation after initial diagnostics. + +## E1 control, step 0, screening +- Checkpoint SHA-256: `81be0f24c44a558e29dffcabb4ac15ae3c944e1afe2860851683d155f920ec2f`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 7.037512302398682 seconds. +- Overall skill 0.000921; relative MASE 1.194471; relative WQL 0.835649. +- term skill: long=0.0466, medium=0.0284, short=-0.0280. +- 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. +- 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. +- variates skill: multivariate=0.0528, univariate=-0.0424. +- Outcome: Untrained seasonal-mixture prior barely exceeds Seasonal Naive overall and fails badly on 10-second and low-frequency configurations. + +## E1 step 1000, seed 17, screening +- Checkpoint SHA-256: `ebdd9eaa223c2bb6e38b8faec6f465a227fcd735b654a26f3b617a757addb0d3`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 6.581991195678711 seconds. +- Overall skill 0.210443; relative MASE 0.932765; relative WQL 0.668336. +- term skill: long=0.2339, medium=0.2517, short=0.1848. +- 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. +- 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. +- variates skill: multivariate=0.2140, univariate=0.2076. +- Outcome: Improves the control by 0.2095 screening skill after about 34 seconds on one H100. Selected for first neural publication and full validation. + +## E1 step 1000, full validation +- Checkpoint SHA-256: `see model_manifest.json`. +- Evaluation: 97 configurations, 151170 instances, 0 failed configurations; not separately timed seconds. +- Overall skill 0.206132; relative MASE 0.931220; relative WQL 0.676774. +- term skill: long=0.2265, medium=0.2444, short=0.1829. +- 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. +- 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. +- variates skill: multivariate=0.2097, univariate=0.2033. +- 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. + +## E1 step 2000, screening +- Checkpoint SHA-256: `a513ac4f03aceb93a860d5e5eca70010c0101fdea794df4a9a8ae472647fb9c9`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 5.98806357383728 seconds. +- Overall skill 0.249671; relative MASE 0.890745; relative WQL 0.632048. +- term skill: long=0.2727, medium=0.2872, short=0.2257. +- 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. +- 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. +- variates skill: multivariate=0.2588, univariate=0.2423. +- Outcome: Improves screening skill to 0.2497 after 66.8 seconds of training; candidate for replacement. + +## E1 step 3000, screening +- Checkpoint SHA-256: `74da538d2365426496a12c965c0c0cdc1d3962a798bd2e2c5fed950c1f663f30`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 6.051600933074951 seconds. +- Overall skill 0.246085; relative MASE 0.894210; relative WQL 0.635631. +- term skill: long=0.2835, medium=0.2774, short=0.2187. +- 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. +- 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. +- variates skill: multivariate=0.2552, univariate=0.2388. +- Outcome: Slight regression to 0.2461 relative to step 2000. Negative checkpoint-selection result; not selected. + +## E2 fixed longer-history feature ablation, step 2000 seed 17 +- Checkpoint SHA-256: `25ac85db67c041c92870e2ea2e8b198bb768f5c5ed64f42b78d6ec207ffe3a18`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 6.066685438156128 seconds. +- Overall skill 0.249089; relative MASE 0.890661; relative WQL 0.633088. +- term skill: long=0.2741, medium=0.2855, short=0.2248. +- 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. +- 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. +- variates skill: multivariate=0.2572, univariate=0.2426. +- 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. + +## E1 step 4000, screening +- Checkpoint SHA-256: `f1b4e5f798688a56a693daf799fa21e69ec21c9c1710cae8dafbdb833c9ee069`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 5.961170196533203 seconds. +- Overall skill 0.266471; relative MASE 0.874789; relative WQL 0.615080. +- term skill: long=0.2537, medium=0.2846, short=0.2643. +- 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. +- 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. +- variates skill: multivariate=0.2648, univariate=0.2678. +- Outcome: Best ungated checkpoint so far; improved short-horizon performance, with some long-horizon regression. + +## E1 step 6000, screening +- Checkpoint SHA-256: `f38cdb1b49938007c20bdfdfa7c4fc7d7aba6516192f388f37088891411eab7f`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 6.802650451660156 seconds. +- Overall skill 0.258313; relative MASE 0.878300; relative WQL 0.626324. +- term skill: long=0.2951, medium=0.3035, short=0.2254. +- 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. +- 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. +- variates skill: multivariate=0.2482, univariate=0.2662. +- Outcome: Overall regression relative to step 4000 despite improvement on medium and long horizons. Not selected by overall skill. + +## E3 seasonal confidence gate, step 4000 seed 17 +- Checkpoint SHA-256: `f1b4e5f798688a56a693daf799fa21e69ec21c9c1710cae8dafbdb833c9ee069`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 9.475942373275757 seconds. +- Overall skill 0.301779; relative MASE 0.827721; relative WQL 0.588981. +- term skill: long=0.3338, medium=0.3656, short=0.2627. +- 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. +- 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. +- variates skill: multivariate=0.3379, univariate=0.2716. +- 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. + +## E3 step 4000 gate, full validation +- Checkpoint SHA-256: `see model_manifest.json`. +- Evaluation: 97 configurations, 151170 instances, 0 failed configurations; not separately timed seconds. +- Overall skill 0.296168; relative MASE 0.830141; relative WQL 0.596742. +- term skill: long=0.3262, medium=0.3621, short=0.2569. +- 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. +- 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. +- variates skill: multivariate=0.3332, univariate=0.2652. +- 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. + +## E1 step 8000, seed 17, ungated screening +- Checkpoint SHA-256: `ebbae91cb50acf1b1436fcbcdce1637195dd6e5006580d3d8e94a4e102aed0ad`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 5.500704050064087 seconds. +- Overall skill 0.276275; relative MASE 0.864160; relative WQL 0.606113. +- term skill: long=0.2954, medium=0.3094, short=0.2557. +- 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. +- 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. +- variates skill: multivariate=0.2735, univariate=0.2785. +- Outcome: Included in final checkpoint selection; compare to weight-averaged result below. + +## E1 step 8000, seed 17, gated screening +- Checkpoint SHA-256: `ebbae91cb50acf1b1436fcbcdce1637195dd6e5006580d3d8e94a4e102aed0ad`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 6.228765964508057 seconds. +- Overall skill 0.312772; relative MASE 0.813977; relative WQL 0.580216. +- term skill: long=0.3671, medium=0.3752, short=0.2645. +- 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. +- 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. +- variates skill: multivariate=0.3530, univariate=0.2790. +- Outcome: Included in final checkpoint selection; compare to weight-averaged result below. + +## E1 step 10000, seed 17, ungated screening +- Checkpoint SHA-256: `3845afb6035396030b9a5182037287db092814d68caa4c96a7c415eb1d3b3a0a`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 6.094600439071655 seconds. +- Overall skill 0.285838; relative MASE 0.855761; relative WQL 0.595993. +- term skill: long=0.2974, medium=0.3249, short=0.2658. +- 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. +- 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. +- variates skill: multivariate=0.2917, univariate=0.2812. +- Outcome: Included in final checkpoint selection; compare to weight-averaged result below. + +## E1 step 10000, seed 17, gated screening +- Checkpoint SHA-256: `3845afb6035396030b9a5182037287db092814d68caa4c96a7c415eb1d3b3a0a`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 7.704133749008179 seconds. +- Overall skill 0.317743; relative MASE 0.805746; relative WQL 0.577695. +- term skill: long=0.3656, medium=0.3815, short=0.2718. +- 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. +- 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. +- variates skill: multivariate=0.3600, univariate=0.2821. +- Outcome: Included in final checkpoint selection; compare to weight-averaged result below. + +## E1 step 12000, seed 17, ungated screening +- Checkpoint SHA-256: `629130a69f89561219b286c1e805d89b8b4662fce0e4b75e731e8764d9066e98`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 5.807793855667114 seconds. +- Overall skill 0.284471; relative MASE 0.856118; relative WQL 0.598027. +- term skill: long=0.2877, medium=0.3155, short=0.2710. +- 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. +- 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. +- variates skill: multivariate=0.2854, univariate=0.2837. +- Outcome: Included in final checkpoint selection; compare to weight-averaged result below. + +## E1 step 12000, seed 17, gated screening +- Checkpoint SHA-256: `629130a69f89561219b286c1e805d89b8b4662fce0e4b75e731e8764d9066e98`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 7.750269889831543 seconds. +- Overall skill 0.315453; relative MASE 0.812477; relative WQL 0.576760. +- term skill: long=0.3585, medium=0.3794, short=0.2715. +- 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. +- 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. +- variates skill: multivariate=0.3552, univariate=0.2820. +- Outcome: Included in final checkpoint selection; compare to weight-averaged result below. + +## E4 stochastic weight average, seed 17, gated screening +- Checkpoint SHA-256: `a346a09ba0b8d196b58acc22a76f7944109b2bba04ea2b7cf7566de24aa2d8db`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 7.737564325332642 seconds. +- Overall skill 0.320612; relative MASE 0.803931; relative WQL 0.574139. +- term skill: long=0.3654, medium=0.3823, short=0.2769. +- 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. +- 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. +- variates skill: multivariate=0.3557, univariate=0.2913. +- 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. + +## E3 confidence and quantile-width sweep +- Fixed global settings, selected only on validation; no model updates. Seed and checkpoint: E1 step 8000, seed 17. +- Measured CPU time: 10.7 seconds. The original threshold 0.25 and width multiplier 1.0 won; no tuned change was adopted. +- (variance threshold, width multiplier) (0.25, 1.0): skill 0.312772; term skills {'short': 0.2645319168347662, 'medium': 0.37524061562171485, 'long': 0.36711552655262625}. +- (variance threshold, width multiplier) (0.5, 1.0): skill 0.311338; term skills {'short': 0.26128183571880415, 'medium': 0.3766834137570718, 'long': 0.36686872500364487}. +- (variance threshold, width multiplier) (0.25, 0.75): skill 0.310114; term skills {'short': 0.26357949467631236, 'medium': 0.3710044838302994, 'long': 0.36223509497654094}. +- (variance threshold, width multiplier) (0.1, 1.0): skill 0.309380; term skills {'short': 0.2645827018541862, 'medium': 0.3687788042390393, 'long': 0.3590704635989247}. +- (variance threshold, width multiplier) (0.25, 1.25): skill 0.308716; term skills {'short': 0.25806263726485956, 'medium': 0.3732424245969126, 'long': 0.3664492202082874}. +- (variance threshold, width multiplier) (0.5, 0.75): skill 0.308480; term skills {'short': 0.2599791649373039, 'medium': 0.3724274186615034, 'long': 0.36196930941343286}. +- (variance threshold, width multiplier) (0.5, 1.25): skill 0.307830; term skills {'short': 0.25575126666422066, 'medium': 0.3747816871597687, 'long': 0.3663051398261168}. +- (variance threshold, width multiplier) (0.1, 0.75): skill 0.306923; term skills {'short': 0.26386190560263856, 'medium': 0.3650190620286501, 'long': 0.35398875275507513}. +- (variance threshold, width multiplier) (0.1, 1.25): skill 0.305043; term skills {'short': 0.2579337472130613, 'medium': 0.36611831669487493, 'long': 0.3583403545682865}. +- (variance threshold, width multiplier) (1.0, 1.0): skill 0.300332; term skills {'short': 0.24300377373135085, 'medium': 0.37515035650362993, 'long': 0.3625716315021771}. +- (variance threshold, width multiplier) (1.0, 0.75): skill 0.297470; term skills {'short': 0.24163138399697548, 'medium': 0.37101264403024414, 'long': 0.3577626408389879}. +- (variance threshold, width multiplier) (1.0, 1.25): skill 0.296900; term skills {'short': 0.23759298244372884, 'medium': 0.3732464838258517, 'long': 0.3619922948184182}. +- (variance threshold, width multiplier) (0.0, 1.0): skill 0.276275; term skills {'short': 0.25565045294773825, 'medium': 0.30935443355536374, 'long': 0.29541709470756516}. +- (variance threshold, width multiplier) (0.0, 0.75): skill 0.274035; term skills {'short': 0.2552205537396286, 'medium': 0.30589300644316675, 'long': 0.289930620063797}. +- (variance threshold, width multiplier) (0.0, 1.25): skill 0.271354; term skills {'short': 0.2486798921582145, 'medium': 0.30569315727356094, 'long': 0.29429049771287774}. + +## E5 capacity and exponential averaging +- Hypothesis: increased capacity reduces residual errors after direct-horizon training; exponential weight averaging reduces checkpoint noise. +- 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)). +- Completed on the sole H100; raw and EMA snapshots were evaluated across all 97 configurations. No causal claim isolates size from seed/schedule changes. + +## E4 averaged small model, full validation +- Checkpoint SHA-256: `see model_manifest.json`. +- Evaluation: 97 configurations, 151170 instances, 0 failed configurations; not separately timed seconds. +- Overall skill 0.315325; relative MASE 0.806359; relative WQL 0.581354. +- term skill: long=0.3584, medium=0.3790, short=0.2715. +- 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. +- 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. +- variates skill: multivariate=0.3509, univariate=0.2856. +- 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. + +## E6 sign symmetry, averaged small model, seed 17 +- Checkpoint SHA-256: `a346a09ba0b8d196b58acc22a76f7944109b2bba04ea2b7cf7566de24aa2d8db`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 7.13059401512146 seconds. +- Overall skill 0.328463; relative MASE 0.794174; relative WQL 0.567837. +- term skill: long=0.3740, medium=0.3863, short=0.2861. +- 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. +- 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. +- variates skill: multivariate=0.3628, univariate=0.2998. +- 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. + +## E6 sign symmetry, averaged small model, full validation +- Checkpoint SHA-256: `see model_manifest.json`. +- Evaluation: 97 configurations, 151170 instances, 0 failed configurations; not separately timed seconds. +- Overall skill 0.323978; relative MASE 0.795773; relative WQL 0.574292. +- term skill: long=0.3666, medium=0.3832, short=0.2823. +- 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. +- 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. +- variates skill: multivariate=0.3586, univariate=0.2951. +- 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. + +## E7 coarse temporal resolution at inference, small averaged model +- Checkpoint SHA-256: `a346a09ba0b8d196b58acc22a76f7944109b2bba04ea2b7cf7566de24aa2d8db`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 8.896855354309082 seconds. +- Overall skill 0.320862; relative MASE 0.803289; relative WQL 0.574174. +- term skill: long=0.3616, medium=0.3660, short=0.2861. +- 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. +- 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. +- variates skill: multivariate=0.3567, univariate=0.2909. +- 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. + +## E8 median and predictable-series loss weighting +- Hypothesis: optimizing median error explicitly and weighting by context seasonal error aligns pretraining with MASE and quantile loss. +- Initial weights: E4 averaged small model, trained here from random initialization; no external pretrained assets. +- 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. +- 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. +- Compute: 272.9 seconds elapsed on the sole H100, shared concurrently with E5. Underlying initial pretraining used 349.9 seconds. + +## E8 step 1000, seed 31, symmetric screening +- Checkpoint SHA-256: `e7cb5c4b4f04ba1ca873bc725f5e4345874520a96cbd3f079e4f631fd3c46d50`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 7.978966474533081 seconds. +- Overall skill 0.331642; relative MASE 0.791898; relative WQL 0.564091. +- term skill: long=0.3735, medium=0.3891, short=0.2910. +- 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. +- 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. +- variates skill: multivariate=0.3652, univariate=0.3036. +- Outcome: EMA at 6000 is best overall and selected for full validation; raw checkpoints show greater variance. + +## E8 ema 1000, seed 31, symmetric screening +- Checkpoint SHA-256: `dab309aff5a3a28936391b84b3ebd9d5dfc208e53c1e1602e4f5c599e3004c33`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 8.16230034828186 seconds. +- Overall skill 0.332263; relative MASE 0.790121; relative WQL 0.564310. +- term skill: long=0.3745, medium=0.3873, short=0.2925. +- 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. +- 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. +- variates skill: multivariate=0.3653, univariate=0.3047. +- Outcome: EMA at 6000 is best overall and selected for full validation; raw checkpoints show greater variance. + +## E8 step 2000, seed 31, symmetric screening +- Checkpoint SHA-256: `111cf52c0662c60aebb44355135a65675a09d898995deeb4dd2f8f2b66339a0f`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 9.85259199142456 seconds. +- Overall skill 0.326318; relative MASE 0.796087; relative WQL 0.570097. +- term skill: long=0.3658, medium=0.3826, short=0.2873. +- 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. +- 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. +- variates skill: multivariate=0.3573, univariate=0.3006. +- Outcome: EMA at 6000 is best overall and selected for full validation; raw checkpoints show greater variance. + +## E8 ema 2000, seed 31, symmetric screening +- Checkpoint SHA-256: `5fa525d923b4af5949f2415cf0ad0b325dae7623f07aae06b3131bdbda08c209`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 14.634822130203247 seconds. +- Overall skill 0.332843; relative MASE 0.789360; relative WQL 0.563874. +- term skill: long=0.3745, medium=0.3875, short=0.2936. +- 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. +- 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. +- variates skill: multivariate=0.3645, univariate=0.3065. +- Outcome: EMA at 6000 is best overall and selected for full validation; raw checkpoints show greater variance. + +## E8 step 4000, seed 31, symmetric screening +- Checkpoint SHA-256: `8ce9867a6005c28005b32d163254c088279f2a46febeadc433b403aeffc29066`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 20.403828620910645 seconds. +- Overall skill 0.333292; relative MASE 0.789778; relative WQL 0.562816. +- term skill: long=0.3723, medium=0.3857, short=0.2961. +- 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. +- 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. +- variates skill: multivariate=0.3645, univariate=0.3073. +- Outcome: EMA at 6000 is best overall and selected for full validation; raw checkpoints show greater variance. + +## E8 ema 4000, seed 31, symmetric screening +- Checkpoint SHA-256: `e61535b34efac923328f1dd464f5ab8ab05913438f86125d8b933f1b166281d9`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 10.288180112838745 seconds. +- Overall skill 0.334221; relative MASE 0.787768; relative WQL 0.562681. +- term skill: long=0.3735, medium=0.3879, short=0.2964. +- 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. +- 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. +- variates skill: multivariate=0.3653, univariate=0.3084. +- Outcome: EMA at 6000 is best overall and selected for full validation; raw checkpoints show greater variance. + +## E8 step 6000, seed 31, symmetric screening +- Checkpoint SHA-256: `15833e7668d9cd11ed55a4820b4700d71c6f734415d11490c7e8beb654abfa12`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 21.2668559551239 seconds. +- Overall skill 0.334430; relative MASE 0.788174; relative WQL 0.562038. +- term skill: long=0.3762, medium=0.3886, short=0.2953. +- 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. +- 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. +- variates skill: multivariate=0.3660, univariate=0.3081. +- Outcome: EMA at 6000 is best overall and selected for full validation; raw checkpoints show greater variance. + +## E8 ema 6000, seed 31, symmetric screening +- Checkpoint SHA-256: `70a3768d667df75f0d6565e831cdca8cf7c179c8546252e5902f7b7ec68ab7aa`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 11.340764284133911 seconds. +- Overall skill 0.335038; relative MASE 0.787307; relative WQL 0.561630. +- term skill: long=0.3762, medium=0.3878, short=0.2968. +- 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. +- 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. +- variates skill: multivariate=0.3659, univariate=0.3094. +- Outcome: EMA at 6000 is best overall and selected for full validation; raw checkpoints show greater variance. + +## E9 neural context 512 for horizons <=128, seed 17 +- Checkpoint SHA-256: `a346a09ba0b8d196b58acc22a76f7944109b2bba04ea2b7cf7566de24aa2d8db`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 10.416622161865234 seconds. +- Overall skill 0.320871; relative MASE 0.803968; relative WQL 0.573675. +- term skill: long=0.3740, medium=0.3863, short=0.2718. +- 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. +- 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. +- variates skill: multivariate=0.3665, univariate=0.2822. +- 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. + +## E9 neural context 1024 for horizons <=128, seed 17 +- Checkpoint SHA-256: `a346a09ba0b8d196b58acc22a76f7944109b2bba04ea2b7cf7566de24aa2d8db`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 19.072535276412964 seconds. +- Overall skill 0.329251; relative MASE 0.796444; relative WQL 0.564891. +- term skill: long=0.3740, medium=0.3863, short=0.2876. +- 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. +- 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. +- variates skill: multivariate=0.3738, univariate=0.2915. +- 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. + +## E9 neural context 2048 for horizons <=128, seed 17 +- Checkpoint SHA-256: `a346a09ba0b8d196b58acc22a76f7944109b2bba04ea2b7cf7566de24aa2d8db`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 9.426023244857788 seconds. +- Overall skill 0.329063; relative MASE 0.794285; relative WQL 0.566744. +- term skill: long=0.3740, medium=0.3863, short=0.2872. +- 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. +- 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. +- variates skill: multivariate=0.3651, univariate=0.2989. +- 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. + +## E10 fixed 50/50 ensemble diagnostic +- Checkpoint SHA-256: `see model_manifest.json`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 4.082070589065552 seconds. +- Overall skill 0.332712; relative MASE 0.791350; relative WQL 0.562676. +- term skill: long=0.3746, medium=0.3901, short=0.2921. +- 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. +- 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. +- variates skill: multivariate=0.3658, univariate=0.3052. +- 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. + +## E8 EMA6000, full validation +- Checkpoint SHA-256: `see model_manifest.json`. +- Evaluation: 97 configurations, 151170 instances, 0 failed configurations; not separately timed seconds. +- Overall skill 0.330109; relative MASE 0.789610; relative WQL 0.568323. +- term skill: long=0.3687, medium=0.3851, short=0.2920. +- 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. +- 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. +- variates skill: multivariate=0.3616, univariate=0.3039. +- 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. + +## E11 matched corpus-coverage experiment +- Hypothesis: broader source coverage improves generalization after the initial model has plateaued. +- 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. +- 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. +- Runs share the single H100 with E5; CPU threads are limited to three per new trainer. Completed matched runs: control 363.4 s, expanded 364.8 s; the expanded corpus did not improve either matched checkpoint. Detailed results are below. + +## E12 fixed continuity correction +- 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. +- 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. +- 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. +- CPU sweep took 6.0 seconds; final verified control and all candidate scores follow. Tau 24 selected for package/full validation. +- 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}}. +- 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}}. +- 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}}. +- 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}}. +- 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}}. +- 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}}. + +## E12 continuity prior, full validation +- Checkpoint SHA-256: `see model_manifest.json`. +- Evaluation: 97 configurations, 151170 instances, 0 failed configurations; not separately timed seconds. +- Overall skill 0.336914; relative MASE 0.783869; relative WQL 0.560914. +- term skill: long=0.3705, medium=0.3876, short=0.3028. +- 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. +- 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. +- variates skill: multivariate=0.3731, univariate=0.3066. +- 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. + +## E11 corpus_control_ema1000 +- Checkpoint SHA-256: `f81bf26e2a17265332fdb3b29204d140703d7c3e9d9abdd7e3297715a7b1153a`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 10.393452167510986 seconds. +- Overall skill 0.335216; relative MASE 0.787169; relative WQL 0.561427. +- term skill: long=0.3757, medium=0.3878, short=0.2973. +- domain skill: Econ/Fin=-0.0001, Energy=0.1627, Healthcare=0.3427, Nature=0.4053, Sales=0.3297, Transport=0.4460, Web/CloudOps=0.4926. +- frequency skill: A=0.3085, D=0.3314, H=0.3702, M=0.0765, Q=0.1659, S=0.3764, T=0.3820, W=0.1191. +- variates skill: multivariate=0.3656, univariate=0.3100. +- Outcome: Matched comparison: original sample control stays near the parent model; expanded corpus is consistently slightly worse. Neither continuation is selected. Compute: control 363.4 s, expanded 364.8 s elapsed while sharing one H100. + +## E11 corpus_control_ema3000 +- Checkpoint SHA-256: `c72daec0504f6082965d689dd9a9f1a7005ac0d9694fb8d4de3d2622db9d615b`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 10.011096715927124 seconds. +- Overall skill 0.334832; relative MASE 0.787218; relative WQL 0.562040. +- term skill: long=0.3765, medium=0.3877, short=0.2963. +- domain skill: Econ/Fin=0.0014, Energy=0.1632, Healthcare=0.3213, Nature=0.4049, Sales=0.3317, Transport=0.4468, Web/CloudOps=0.4939. +- frequency skill: A=0.2922, D=0.3214, H=0.3695, M=0.0723, Q=0.1640, S=0.3781, T=0.3850, W=0.1283. +- variates skill: multivariate=0.3670, univariate=0.3081. +- Outcome: Matched comparison: original sample control stays near the parent model; expanded corpus is consistently slightly worse. Neither continuation is selected. Compute: control 363.4 s, expanded 364.8 s elapsed while sharing one H100. + +## E11 corpus_control_ema6000 +- Checkpoint SHA-256: `fa23c895ff4926b3d0df6d15267718a1dda41ad9386abbfef1306becb262da1c`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 7.355180501937866 seconds. +- Overall skill 0.334809; relative MASE 0.788444; relative WQL 0.561205. +- term skill: long=0.3770, medium=0.3879, short=0.2960. +- domain skill: Econ/Fin=-0.0139, Energy=0.1615, Healthcare=0.3361, Nature=0.4053, Sales=0.3305, Transport=0.4466, Web/CloudOps=0.4951. +- frequency skill: A=0.2945, D=0.3215, H=0.3707, M=0.0639, Q=0.1501, S=0.3778, T=0.3855, W=0.1254. +- variates skill: multivariate=0.3680, univariate=0.3071. +- Outcome: Matched comparison: original sample control stays near the parent model; expanded corpus is consistently slightly worse. Neither continuation is selected. Compute: control 363.4 s, expanded 364.8 s elapsed while sharing one H100. + +## E11 corpus_expanded_ema1000 +- Checkpoint SHA-256: `8c0f66d7a2377fa37b4d3358c89ae9b5786a6f5f0223b1480fb7a0b20b17ebc8`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 10.571230411529541 seconds. +- Overall skill 0.333782; relative MASE 0.789135; relative WQL 0.562448. +- term skill: long=0.3749, medium=0.3867, short=0.2955. +- domain skill: Econ/Fin=-0.0143, Energy=0.1614, Healthcare=0.3302, Nature=0.4029, Sales=0.3292, Transport=0.4472, Web/CloudOps=0.4938. +- frequency skill: A=0.2932, D=0.3308, H=0.3695, M=0.0696, Q=0.1628, S=0.3754, T=0.3818, W=0.1103. +- variates skill: multivariate=0.3653, univariate=0.3075. +- Outcome: Matched comparison: original sample control stays near the parent model; expanded corpus is consistently slightly worse. Neither continuation is selected. Compute: control 363.4 s, expanded 364.8 s elapsed while sharing one H100. + +## E11 corpus_expanded_ema3000 +- Checkpoint SHA-256: `51586b5ce1a426dc2f3adf42aba9599b731b62ab316159dafe681e77317015a2`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 10.598361253738403 seconds. +- Overall skill 0.333836; relative MASE 0.789352; relative WQL 0.562201. +- term skill: long=0.3750, medium=0.3869, short=0.2954. +- domain skill: Econ/Fin=-0.0087, Energy=0.1631, Healthcare=0.3250, Nature=0.4036, Sales=0.3303, Transport=0.4468, Web/CloudOps=0.4922. +- frequency skill: A=0.3132, D=0.3259, H=0.3690, M=0.0696, Q=0.1693, S=0.3752, T=0.3829, W=0.1162. +- variates skill: multivariate=0.3659, univariate=0.3071. +- Outcome: Matched comparison: original sample control stays near the parent model; expanded corpus is consistently slightly worse. Neither continuation is selected. Compute: control 363.4 s, expanded 364.8 s elapsed while sharing one H100. + +## E11 corpus_expanded_ema6000 +- Checkpoint SHA-256: `b82b9da6afa6b7ec864a5c4f9829a2a68b29f0923d0c556a998b9d79623d9ba9`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 7.799206972122192 seconds. +- Overall skill 0.333432; relative MASE 0.790380; relative WQL 0.562151. +- term skill: long=0.3759, medium=0.3881, short=0.2938. +- domain skill: Econ/Fin=-0.0272, Energy=0.1621, Healthcare=0.3299, Nature=0.4047, Sales=0.3298, Transport=0.4459, Web/CloudOps=0.4936. +- frequency skill: A=0.3024, D=0.3227, H=0.3691, M=0.0639, Q=0.1574, S=0.3794, T=0.3834, W=0.1166. +- variates skill: multivariate=0.3662, univariate=0.3061. +- Outcome: Matched comparison: original sample control stays near the parent model; expanded corpus is consistently slightly worse. Neither continuation is selected. Compute: control 363.4 s, expanded 364.8 s elapsed while sharing one H100. + +## E5 direct_large_ema12000_gate +- Checkpoint SHA-256: `202e23ba9d7560bf2bd67a609d024449facabdfd338c9268bc013ff6b613168f`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 11.02167820930481 seconds. +- Overall skill 0.314336; relative MASE 0.813757; relative WQL 0.577734. +- term skill: long=0.3670, medium=0.3868, short=0.2623. +- domain skill: Econ/Fin=-0.0160, Energy=0.1404, Healthcare=0.2477, Nature=0.3897, Sales=0.3170, Transport=0.4355, Web/CloudOps=0.4760. +- frequency skill: A=0.3627, D=0.3141, H=0.3649, M=-0.1520, Q=0.1593, S=0.3730, T=0.3518, W=0.1342. +- variates skill: multivariate=0.3564, univariate=0.2788. +- Outcome: 37M capacity run from random initialization; seed 23. Final run: 24,000 steps / 3,072,000 windows in 1073.9 s elapsed on the sole H100, shared with other experiments. Most checkpoints lag the small model; EMA reduces checkpoint variance. Final raw checkpoint is stronger than final EMA in gated inference, so it will receive a full inference-rule comparison. + +## E5 direct_large_ema16000_gate +- Checkpoint SHA-256: `8ba1220059af5a85180b3ad740402a48b2d38172598510da796339378e529a73`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 9.176010131835938 seconds. +- Overall skill 0.322612; relative MASE 0.806599; relative WQL 0.568877. +- term skill: long=0.3668, medium=0.3875, short=0.2777. +- domain skill: Econ/Fin=0.0042, Energy=0.1444, Healthcare=0.3056, Nature=0.3937, Sales=0.3266, Transport=0.4361, Web/CloudOps=0.4847. +- frequency skill: A=0.3573, D=0.3049, H=0.3646, M=-0.0462, Q=0.1603, S=0.3803, T=0.3607, W=0.1797. +- variates skill: multivariate=0.3644, univariate=0.2874. +- Outcome: 37M capacity run from random initialization; seed 23. Final run: 24,000 steps / 3,072,000 windows in 1073.9 s elapsed on the sole H100, shared with other experiments. Most checkpoints lag the small model; EMA reduces checkpoint variance. Final raw checkpoint is stronger than final EMA in gated inference, so it will receive a full inference-rule comparison. + +## E5 direct_large_ema20000_gate +- Checkpoint SHA-256: `1ec9d54fa1270442b0023da3f7fc23f5fa5291e58210a55f63878983afccc606`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 11.57221269607544 seconds. +- Overall skill 0.324943; relative MASE 0.805088; relative WQL 0.566028. +- term skill: long=0.3666, medium=0.3878, short=0.2821. +- domain skill: Econ/Fin=0.0218, Energy=0.1439, Healthcare=0.2912, Nature=0.4039, Sales=0.3250, Transport=0.4352, Web/CloudOps=0.4880. +- frequency skill: A=0.3533, D=0.3058, H=0.3660, M=-0.0485, Q=0.1544, S=0.3756, T=0.3665, W=0.1840. +- variates skill: multivariate=0.3678, univariate=0.2887. +- Outcome: 37M capacity run from random initialization; seed 23. Final run: 24,000 steps / 3,072,000 windows in 1073.9 s elapsed on the sole H100, shared with other experiments. Most checkpoints lag the small model; EMA reduces checkpoint variance. Final raw checkpoint is stronger than final EMA in gated inference, so it will receive a full inference-rule comparison. + +## E5 direct_large_ema2000_gate +- Checkpoint SHA-256: `bea7fbebdc754a6cef068a4b835e644d896305e928b4a63974c731874dc49028`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 7.918560028076172 seconds. +- Overall skill 0.279056; relative MASE 0.848285; relative WQL 0.612718. +- term skill: long=0.3485, medium=0.3540, short=0.2185. +- domain skill: Econ/Fin=-0.0871, Energy=0.1232, Healthcare=0.1986, Nature=0.3855, Sales=0.3094, Transport=0.3731, Web/CloudOps=0.4269. +- frequency skill: A=0.3054, D=0.2729, H=0.3360, M=-0.1424, Q=0.1034, S=0.3706, T=0.2968, W=0.1303. +- variates skill: multivariate=0.3283, univariate=0.2373. +- Outcome: 37M capacity run from random initialization; seed 23. Final run: 24,000 steps / 3,072,000 windows in 1073.9 s elapsed on the sole H100, shared with other experiments. Most checkpoints lag the small model; EMA reduces checkpoint variance. Final raw checkpoint is stronger than final EMA in gated inference, so it will receive a full inference-rule comparison. + +## E5 direct_large_ema24000_gate +- Checkpoint SHA-256: `e5bb7f70c0adbf61b4292cfc40a419e6757854a255ef0c47d3d47c7f2d68b7a2`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 8.641167879104614 seconds. +- Overall skill 0.323234; relative MASE 0.806197; relative WQL 0.568114. +- term skill: long=0.3665, medium=0.3864, short=0.2795. +- domain skill: Econ/Fin=0.0385, Energy=0.1492, Healthcare=0.2588, Nature=0.4037, Sales=0.3217, Transport=0.4347, Web/CloudOps=0.4807. +- frequency skill: A=0.3645, D=0.3062, H=0.3653, M=-0.0563, Q=0.1548, S=0.3766, T=0.3656, W=0.1664. +- variates skill: multivariate=0.3653, univariate=0.2877. +- Outcome: 37M capacity run from random initialization; seed 23. Final run: 24,000 steps / 3,072,000 windows in 1073.9 s elapsed on the sole H100, shared with other experiments. Most checkpoints lag the small model; EMA reduces checkpoint variance. Final raw checkpoint is stronger than final EMA in gated inference, so it will receive a full inference-rule comparison. + +## E5 direct_large_ema4000_gate +- Checkpoint SHA-256: `2f45a9ce8bed8e0e3ebe37ba98ac36ab8b9a630a615856760f46c0763fa78b5c`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 8.853939056396484 seconds. +- Overall skill 0.296679; relative MASE 0.830007; relative WQL 0.595971. +- term skill: long=0.3569, medium=0.3692, short=0.2413. +- domain skill: Econ/Fin=-0.0411, Energy=0.1331, Healthcare=0.1511, Nature=0.3889, Sales=0.3253, Transport=0.4031, Web/CloudOps=0.4590. +- frequency skill: A=0.3534, D=0.2760, H=0.3509, M=-0.1255, Q=0.1495, S=0.3734, T=0.3314, W=0.1185. +- variates skill: multivariate=0.3480, univariate=0.2530. +- Outcome: 37M capacity run from random initialization; seed 23. Final run: 24,000 steps / 3,072,000 windows in 1073.9 s elapsed on the sole H100, shared with other experiments. Most checkpoints lag the small model; EMA reduces checkpoint variance. Final raw checkpoint is stronger than final EMA in gated inference, so it will receive a full inference-rule comparison. + +## E5 direct_large_ema8000_gate +- Checkpoint SHA-256: `1b15662821b8c7a20d973f548dacabd237f470ffd1c75457c0b92011d3f0cc88`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 9.06697702407837 seconds. +- Overall skill 0.310188; relative MASE 0.816631; relative WQL 0.582688. +- term skill: long=0.3619, medium=0.3788, short=0.2604. +- domain skill: Econ/Fin=-0.0143, Energy=0.1404, Healthcare=0.2015, Nature=0.3934, Sales=0.3255, Transport=0.4210, Web/CloudOps=0.4744. +- frequency skill: A=0.3680, D=0.2929, H=0.3581, M=-0.0609, Q=0.1607, S=0.3679, T=0.3513, W=0.1178. +- variates skill: multivariate=0.3533, univariate=0.2739. +- Outcome: 37M capacity run from random initialization; seed 23. Final run: 24,000 steps / 3,072,000 windows in 1073.9 s elapsed on the sole H100, shared with other experiments. Most checkpoints lag the small model; EMA reduces checkpoint variance. Final raw checkpoint is stronger than final EMA in gated inference, so it will receive a full inference-rule comparison. + +## E5 direct_large_step12000_gate +- Checkpoint SHA-256: `8788d76e331dcd9cca1d6dab37db34b4c8b1257fc83da49b532c11643cd0ebfa`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 14.492464065551758 seconds. +- Overall skill 0.304901; relative MASE 0.821804; relative WQL 0.587930. +- term skill: long=0.3555, medium=0.3694, short=0.2575. +- domain skill: Econ/Fin=-0.0110, Energy=0.1063, Healthcare=0.2456, Nature=0.3830, Sales=0.2991, Transport=0.4416, Web/CloudOps=0.4763. +- frequency skill: A=0.3131, D=0.3025, H=0.3517, M=-0.0499, Q=0.1271, S=0.3821, T=0.3324, W=0.1350. +- variates skill: multivariate=0.3451, univariate=0.2712. +- Outcome: 37M capacity run from random initialization; seed 23. Final run: 24,000 steps / 3,072,000 windows in 1073.9 s elapsed on the sole H100, shared with other experiments. Most checkpoints lag the small model; EMA reduces checkpoint variance. Final raw checkpoint is stronger than final EMA in gated inference, so it will receive a full inference-rule comparison. + +## E5 direct_large_step16000_gate +- Checkpoint SHA-256: `beb43e784be8db8ee5ec14e83fa9c68f7ce897790441453eb6d72cceedb80650`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 9.434912919998169 seconds. +- Overall skill 0.311197; relative MASE 0.820659; relative WQL 0.578132. +- term skill: long=0.3577, medium=0.3731, short=0.2667. +- domain skill: Econ/Fin=-0.0270, Energy=0.1289, Healthcare=0.2653, Nature=0.3904, Sales=0.3264, Transport=0.4341, Web/CloudOps=0.4732. +- frequency skill: A=0.3445, D=0.2986, H=0.3593, M=-0.0768, Q=0.1596, S=0.3715, T=0.3463, W=0.1472. +- variates skill: multivariate=0.3513, univariate=0.2775. +- Outcome: 37M capacity run from random initialization; seed 23. Final run: 24,000 steps / 3,072,000 windows in 1073.9 s elapsed on the sole H100, shared with other experiments. Most checkpoints lag the small model; EMA reduces checkpoint variance. Final raw checkpoint is stronger than final EMA in gated inference, so it will receive a full inference-rule comparison. + +## E5 direct_large_step20000_gate +- Checkpoint SHA-256: `9332e5088244bd4a2a1ad5b6470a108ebaa6bc387a525202f6bf954d9796b1a6`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 11.937657117843628 seconds. +- Overall skill 0.319529; relative MASE 0.811224; relative WQL 0.570793. +- term skill: long=0.3661, medium=0.3842, short=0.2737. +- domain skill: Econ/Fin=0.0113, Energy=0.1395, Healthcare=0.3332, Nature=0.3983, Sales=0.3058, Transport=0.4236, Web/CloudOps=0.4804. +- frequency skill: A=0.3483, D=0.3114, H=0.3599, M=-0.0666, Q=0.1435, S=0.3671, T=0.3551, W=0.1967. +- variates skill: multivariate=0.3633, univariate=0.2825. +- Outcome: 37M capacity run from random initialization; seed 23. Final run: 24,000 steps / 3,072,000 windows in 1073.9 s elapsed on the sole H100, shared with other experiments. Most checkpoints lag the small model; EMA reduces checkpoint variance. Final raw checkpoint is stronger than final EMA in gated inference, so it will receive a full inference-rule comparison. + +## E5 direct_large_step2000_gate +- Checkpoint SHA-256: `f16c3270e2d4adafc8dbc1416687932a81b040bed29ad21887f7f8953437ba86`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 8.376563549041748 seconds. +- Overall skill 0.284757; relative MASE 0.840864; relative WQL 0.608389. +- term skill: long=0.3356, medium=0.3611, short=0.2319. +- domain skill: Econ/Fin=-0.0840, Energy=0.1152, Healthcare=0.2242, Nature=0.3840, Sales=0.3264, Transport=0.3898, Web/CloudOps=0.4386. +- frequency skill: A=0.2579, D=0.2746, H=0.3418, M=-0.0497, Q=0.1253, S=0.3787, T=0.2935, W=0.1458. +- variates skill: multivariate=0.3309, univariate=0.2458. +- Outcome: 37M capacity run from random initialization; seed 23. Final run: 24,000 steps / 3,072,000 windows in 1073.9 s elapsed on the sole H100, shared with other experiments. Most checkpoints lag the small model; EMA reduces checkpoint variance. Final raw checkpoint is stronger than final EMA in gated inference, so it will receive a full inference-rule comparison. + +## E5 direct_large_step24000_gate +- Checkpoint SHA-256: `b7e4f38aebcd2cf38ce484edaad8d19851317fb3b8df485e2faa0d0423cbcb48`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 7.831688165664673 seconds. +- Overall skill 0.326279; relative MASE 0.802486; relative WQL 0.565617. +- term skill: long=0.3671, medium=0.3874, short=0.2845. +- domain skill: Econ/Fin=0.0453, Energy=0.1487, Healthcare=0.3262, Nature=0.4087, Sales=0.3234, Transport=0.4251, Web/CloudOps=0.4821. +- frequency skill: A=0.3544, D=0.3106, H=0.3612, M=-0.0014, Q=0.1548, S=0.3765, T=0.3668, W=0.1910. +- variates skill: multivariate=0.3662, univariate=0.2927. +- Outcome: 37M capacity run from random initialization; seed 23. Final run: 24,000 steps / 3,072,000 windows in 1073.9 s elapsed on the sole H100, shared with other experiments. Most checkpoints lag the small model; EMA reduces checkpoint variance. Final raw checkpoint is stronger than final EMA in gated inference, so it will receive a full inference-rule comparison. + +## E5 direct_large_step4000_gate +- Checkpoint SHA-256: `a085c48b8bac06dba51118942d58b632dfc8fd934455232b2f1f7c7329f1ae76`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 8.682147979736328 seconds. +- Overall skill 0.291006; relative MASE 0.830831; relative WQL 0.605023. +- term skill: long=0.3451, medium=0.3504, short=0.2444. +- domain skill: Econ/Fin=-0.0403, Energy=0.0877, Healthcare=0.2367, Nature=0.3707, Sales=0.3185, Transport=0.4275, Web/CloudOps=0.4638. +- frequency skill: A=0.2862, D=0.2949, H=0.3327, M=-0.1134, Q=0.1567, S=0.3705, T=0.3243, W=0.1248. +- variates skill: multivariate=0.3352, univariate=0.2538. +- Outcome: 37M capacity run from random initialization; seed 23. Final run: 24,000 steps / 3,072,000 windows in 1073.9 s elapsed on the sole H100, shared with other experiments. Most checkpoints lag the small model; EMA reduces checkpoint variance. Final raw checkpoint is stronger than final EMA in gated inference, so it will receive a full inference-rule comparison. + +## E5 direct_large_step8000_gate +- Checkpoint SHA-256: `7c0ca8d6f3023ecefc12818560b9bac64e044102cb27d478978c48ce82276c38`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 8.785595417022705 seconds. +- Overall skill 0.307945; relative MASE 0.812528; relative WQL 0.589444. +- term skill: long=0.3650, medium=0.3688, short=0.2592. +- domain skill: Econ/Fin=-0.0843, Energy=0.1539, Healthcare=0.1762, Nature=0.3845, Sales=0.3220, Transport=0.4223, Web/CloudOps=0.4730. +- frequency skill: A=0.3235, D=0.2684, H=0.3578, M=-0.0688, Q=0.1156, S=0.3591, T=0.3615, W=0.1148. +- variates skill: multivariate=0.3471, univariate=0.2751. +- Outcome: 37M capacity run from random initialization; seed 23. Final run: 24,000 steps / 3,072,000 windows in 1073.9 s elapsed on the sole H100, shared with other experiments. Most checkpoints lag the small model; EMA reduces checkpoint variance. Final raw checkpoint is stronger than final EMA in gated inference, so it will receive a full inference-rule comparison. + +## E13/E14 matched large-model continuations +- Parent: raw E5 step 24000 (random-init pretraining here, seed 23), selected after final gated and sign-symmetric/continuity comparisons. +- Three runs share seed 43, batch 256, 6,000 steps, AdamW 8e-5 with 400-step warmup/cosine decay, the original packed sample, and the E8 median/seasonal-error-weighted objective. All use EMA. GPU: the one H100; three CPU threads per trainer. +- large_loss: unchanged synthetic generator, control for applying E8 loss to the larger model. +- large_synth: replace half of the 20% synthetic windows with newly generated integrated colored innovations, stochastic local-linear trends with level shifts, or sharp periodic pulses with slowly drifting amplitude. Generator is in large_synth/data.py; no external synthetic assets. +- large_sign: independently negate each sampled context and target with probability 0.5. Context seasonal scales are sign-invariant. Data RNG is shared with augmentation, so later draws diverge from the control despite the matched seed; this is a single-seed comparison. +- All inference rules remain fixed (sign symmetry, seasonal confidence gate and 24-step continuity). Results pending. + +## E15 final-checkpoint ensemble +- Hypothesis: the differently trained small and large models have complementary median and distribution errors. Fixed equal weights, both members forecast every instance. E8 EMA6000 (seed31 continuation of seed17) plus E5 raw24000 (seed23). Same fixed inference rules applied separately before averaging. +- Cached prediction diagnostic skill 0.344733 exceeds the small model 0.341604 and large model 0.343219. Actual bundled inference and full validation are required before publication. + +## E15 actual bundled ensemble screening +- Checkpoint SHA-256: `91cb9b3fc2422fc376ecab7813213a7156b6baee963da620f06e82f1aaeaea39`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 21.611496925354004 seconds. +- Overall skill 0.344715; relative MASE 0.780210; relative WQL 0.550363. +- term skill: long=0.3780, medium=0.3928, short=0.3118. +- domain skill: Econ/Fin=0.0849, Energy=0.1725, Healthcare=0.3305, Nature=0.4119, Sales=0.3307, Transport=0.4448, Web/CloudOps=0.5036. +- frequency skill: A=0.2873, D=0.3348, H=0.3699, M=0.0563, Q=0.1938, S=0.4258, T=0.3912, W=0.1713. +- variates skill: multivariate=0.3825, univariate=0.3130. +- Outcome: Actual package inference skill 0.344715, within 0.000019 of cached averaging; zero failures. The difference comes from numerical batching. Full package inference remains required. + +## E15 bundled ensemble, full validation +- Checkpoint SHA-256: `91cb9b3fc2422fc376ecab7813213a7156b6baee963da620f06e82f1aaeaea39`. +- Evaluation: 97 configurations, 151170 instances, 0 failed configurations; not separately timed seconds. +- Overall skill 0.340239; relative MASE 0.782773; relative WQL 0.556081. +- term skill: long=0.3706, medium=0.3906, short=0.3076. +- domain skill: Econ/Fin=0.0668, Energy=0.1633, Healthcare=0.3369, Nature=0.4112, Sales=0.3436, Transport=0.4446, Web/CloudOps=0.4963. +- frequency skill: A=0.2315, D=0.3371, H=0.3638, M=0.0773, Q=0.1704, S=0.4258, T=0.3837, W=0.1660. +- variates skill: multivariate=0.3783, univariate=0.3083. +- Outcome: Full skill 0.340239, relative MASE 0.782773, relative WQL 0.556081, zero failed configurations. Improves the previous published 0.336914. Relocated package inference took 119.3 seconds while three 37M trainers shared the sole H100. Repeated example calls were bitwise identical, finite and monotone. Selected for atomic publication. + +## E16 earlier-window diagnostic +- Hypothesis: a second cutoff reveals whether gains on single-series configurations are stable over time. +- Constructed the immediately preceding nonoverlapping window from each selected validation context (never used for training). All 97 configurations remain; short histories with fewer than H+8 points are omitted. Seasonal-error scales use the available capped prefix and Seasonal Naive is recomputed on that same input, so these are diagnostic scores on a separate scale. +- The small E8 EMA6000 model improves from 0.308552 without continuity to 0.314127 with it. The large parent scores 0.312321; the first sign-augmented checkpoint scores 0.312240. Thus continuity is supported at both cutoffs, while the first sign-augmentation gain does not yet repeat on the earlier cutoff. No weights or rules are adapted on the diagnostic contexts. + +## Full-validation checkpoint identity audit +- valid-report-1000.json: `ebdd9eaa223c2bb6e38b8faec6f465a227fcd735b654a26f3b617a757addb0d3`, skill 0.206132. +- valid-report-4000-gate.json: `f1b4e5f798688a56a693daf799fa21e69ec21c9c1710cae8dafbdb833c9ee069`, skill 0.296168. +- valid-report-swa-gate.json: `a346a09ba0b8d196b58acc22a76f7944109b2bba04ea2b7cf7566de24aa2d8db`, skill 0.315325. +- valid-report-symmetric.json: `a346a09ba0b8d196b58acc22a76f7944109b2bba04ea2b7cf7566de24aa2d8db`, skill 0.323978. +- valid-report-objective.json: `70a3768d667df75f0d6565e831cdca8cf7c179c8546252e5902f7b7ec68ab7aa`, skill 0.330109. +- valid-report-continuity.json: `70a3768d667df75f0d6565e831cdca8cf7c179c8546252e5902f7b7ec68ab7aa`, skill 0.336914. +- valid-report-ensemble.json: `91cb9b3fc2422fc376ecab7813213a7156b6baee963da620f06e82f1aaeaea39`, skill 0.340239. + +## E13/E14 large_loss_ema1000_continuity +- Checkpoint SHA-256: `872c92ee27b0d63f310b7be7434ffe3d5342b19a42d48fefd0a468b87501b28e`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 14.880280256271362 seconds. +- Overall skill 0.342546; relative MASE 0.782779; relative WQL 0.552194. +- term skill: long=0.3792, medium=0.3907, short=0.3082. +- domain skill: Econ/Fin=0.0879, Energy=0.1741, Healthcare=0.2781, Nature=0.4155, Sales=0.3277, Transport=0.4454, Web/CloudOps=0.5007. +- frequency skill: A=0.2788, D=0.3141, H=0.3715, M=0.0511, Q=0.1869, S=0.4248, T=0.3925, W=0.1774. +- variates skill: multivariate=0.3827, univariate=0.3087. +- Outcome: Matched large-model continuation. Final EMA6000: sign augmentation wins (0.349298) over revised-loss control (0.346864) and richer synthetic generator (0.343184). Compute: control 618.3 s, synthetic 613.1 s, sign 617.9 s elapsed while sharing one H100. + +## E13/E14 large_loss_ema3000_continuity +- Checkpoint SHA-256: `18c2788192e4028dd45255512b1c4bcddf12a50eb813e34fa0987b8949d75f15`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 14.631194829940796 seconds. +- Overall skill 0.345993; relative MASE 0.778768; relative WQL 0.549233. +- term skill: long=0.3793, medium=0.3902, short=0.3147. +- domain skill: Econ/Fin=0.0850, Energy=0.1714, Healthcare=0.3423, Nature=0.4181, Sales=0.3281, Transport=0.4479, Web/CloudOps=0.5015. +- frequency skill: A=0.2956, D=0.3232, H=0.3727, M=0.0705, Q=0.1917, S=0.4274, T=0.3904, W=0.1972. +- variates skill: multivariate=0.3829, univariate=0.3150. +- Outcome: Matched large-model continuation. Final EMA6000: sign augmentation wins (0.349298) over revised-loss control (0.346864) and richer synthetic generator (0.343184). Compute: control 618.3 s, synthetic 613.1 s, sign 617.9 s elapsed while sharing one H100. + +## E13/E14 large_loss_ema6000_continuity +- Checkpoint SHA-256: `f5c7327b365832e8bd2d1b7b01e61c334f5bf620f5cae5f4d45feef2041090e8`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 9.797317266464233 seconds. +- Overall skill 0.346864; relative MASE 0.778052; relative WQL 0.548275. +- term skill: long=0.3803, medium=0.3907, short=0.3157. +- domain skill: Econ/Fin=0.0848, Energy=0.1765, Healthcare=0.3460, Nature=0.4171, Sales=0.3275, Transport=0.4491, Web/CloudOps=0.4990. +- frequency skill: A=0.2988, D=0.3201, H=0.3724, M=0.0715, Q=0.1909, S=0.4236, T=0.3942, W=0.2029. +- variates skill: multivariate=0.3831, univariate=0.3165. +- Outcome: Matched large-model continuation. Final EMA6000: sign augmentation wins (0.349298) over revised-loss control (0.346864) and richer synthetic generator (0.343184). Compute: control 618.3 s, synthetic 613.1 s, sign 617.9 s elapsed while sharing one H100. + +## E13/E14 large_sign_ema1000_continuity +- Checkpoint SHA-256: `393950048f9d0487869b7aa5e6bd01e7ea1715dba16b1367ee8be353eac7f408`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 14.772316932678223 seconds. +- Overall skill 0.347448; relative MASE 0.776694; relative WQL 0.548252. +- term skill: long=0.3829, medium=0.3908, short=0.3157. +- domain skill: Econ/Fin=0.0975, Energy=0.1743, Healthcare=0.3647, Nature=0.4116, Sales=0.3348, Transport=0.4489, Web/CloudOps=0.5001. +- frequency skill: A=0.3764, D=0.3250, H=0.3728, M=0.0605, Q=0.1918, S=0.4294, T=0.3920, W=0.1973. +- variates skill: multivariate=0.3811, univariate=0.3193. +- Outcome: Matched large-model continuation. Final EMA6000: sign augmentation wins (0.349298) over revised-loss control (0.346864) and richer synthetic generator (0.343184). Compute: control 618.3 s, synthetic 613.1 s, sign 617.9 s elapsed while sharing one H100. + +## E13/E14 large_sign_ema3000_continuity +- Checkpoint SHA-256: `24a38240b540c1311317103b880d4be47e17b7de883f535ef95977a3acc596dd`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 14.933598279953003 seconds. +- Overall skill 0.348060; relative MASE 0.775887; relative WQL 0.547794. +- term skill: long=0.3822, medium=0.3909, short=0.3171. +- domain skill: Econ/Fin=0.1095, Energy=0.1761, Healthcare=0.3575, Nature=0.4106, Sales=0.3331, Transport=0.4503, Web/CloudOps=0.5000. +- frequency skill: A=0.3842, D=0.3252, H=0.3741, M=0.0510, Q=0.1966, S=0.4324, T=0.3901, W=0.2089. +- variates skill: multivariate=0.3815, univariate=0.3201. +- Outcome: Matched large-model continuation. Final EMA6000: sign augmentation wins (0.349298) over revised-loss control (0.346864) and richer synthetic generator (0.343184). Compute: control 618.3 s, synthetic 613.1 s, sign 617.9 s elapsed while sharing one H100. + +## E13/E14 large_sign_ema6000_continuity +- Checkpoint SHA-256: `96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 9.297121286392212 seconds. +- Overall skill 0.349298; relative MASE 0.774499; relative WQL 0.546694. +- term skill: long=0.3853, medium=0.3928, short=0.3172. +- domain skill: Econ/Fin=0.1160, Energy=0.1799, Healthcare=0.3608, Nature=0.4057, Sales=0.3338, Transport=0.4511, Web/CloudOps=0.5017. +- frequency skill: A=0.3836, D=0.3247, H=0.3752, M=0.0334, Q=0.1968, S=0.4300, T=0.3937, W=0.2168. +- variates skill: multivariate=0.3827, univariate=0.3214. +- Outcome: Matched large-model continuation. Final EMA6000: sign augmentation wins (0.349298) over revised-loss control (0.346864) and richer synthetic generator (0.343184). Compute: control 618.3 s, synthetic 613.1 s, sign 617.9 s elapsed while sharing one H100. + +## E13/E14 large_synth_ema1000_continuity +- Checkpoint SHA-256: `c04fc8cad141754a2cb540b636cc3ac7744554cc85e201b4b291e777b2aee196`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 15.066582441329956 seconds. +- Overall skill 0.343871; relative MASE 0.781301; relative WQL 0.551010. +- term skill: long=0.3732, medium=0.3938, short=0.3118. +- domain skill: Econ/Fin=0.1001, Energy=0.1746, Healthcare=0.2638, Nature=0.4169, Sales=0.3281, Transport=0.4461, Web/CloudOps=0.5042. +- frequency skill: A=0.3050, D=0.3243, H=0.3716, M=-0.0066, Q=0.1903, S=0.4298, T=0.3943, W=0.1851. +- variates skill: multivariate=0.3847, univariate=0.3094. +- Outcome: Matched large-model continuation. Final EMA6000: sign augmentation wins (0.349298) over revised-loss control (0.346864) and richer synthetic generator (0.343184). Compute: control 618.3 s, synthetic 613.1 s, sign 617.9 s elapsed while sharing one H100. + +## E13/E14 large_synth_ema3000_continuity +- Checkpoint SHA-256: `aa73bdf3e3b2d44e69c716f2dc788789949b96d69f4cd92c2b0169bfd4dc89ce`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 14.854033946990967 seconds. +- Overall skill 0.343138; relative MASE 0.782085; relative WQL 0.551689. +- term skill: long=0.3690, medium=0.3946, short=0.3119. +- domain skill: Econ/Fin=0.1103, Energy=0.1771, Healthcare=0.2214, Nature=0.4199, Sales=0.3279, Transport=0.4472, Web/CloudOps=0.5016. +- frequency skill: A=0.2856, D=0.3228, H=0.3725, M=0.0162, Q=0.1940, S=0.4277, T=0.3929, W=0.1727. +- variates skill: multivariate=0.3849, univariate=0.3079. +- Outcome: Matched large-model continuation. Final EMA6000: sign augmentation wins (0.349298) over revised-loss control (0.346864) and richer synthetic generator (0.343184). Compute: control 618.3 s, synthetic 613.1 s, sign 617.9 s elapsed while sharing one H100. + +## E13/E14 large_synth_ema6000_continuity +- Checkpoint SHA-256: `f23469b8d187d0304e0accdc424ddd2233ed87dd77b97500176eec73644e0591`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 9.708917140960693 seconds. +- Overall skill 0.343184; relative MASE 0.781828; relative WQL 0.551793. +- term skill: long=0.3706, medium=0.3947, short=0.3112. +- domain skill: Econ/Fin=0.1127, Energy=0.1747, Healthcare=0.2160, Nature=0.4195, Sales=0.3267, Transport=0.4485, Web/CloudOps=0.5041. +- frequency skill: A=0.2764, D=0.3186, H=0.3736, M=0.0181, Q=0.1970, S=0.4302, T=0.3934, W=0.1723. +- variates skill: multivariate=0.3851, univariate=0.3077. +- Outcome: Matched large-model continuation. Final EMA6000: sign augmentation wins (0.349298) over revised-loss control (0.346864) and richer synthetic generator (0.343184). Compute: control 618.3 s, synthetic 613.1 s, sign 617.9 s elapsed while sharing one H100. + +## E16 earlier-window diagnostic large_loss6000 +- Checkpoint SHA-256: `f5c7327b365832e8bd2d1b7b01e61c334f5bf620f5cae5f4d45feef2041090e8`. +- Evaluation: 97 configurations, 9330 instances, 0 failed configurations; 9.924073696136475 seconds. +- Overall skill 0.311219; relative MASE 0.824887; relative WQL 0.575132. +- term skill: long=0.3825, medium=0.3465, short=0.2673. +- domain skill: Econ/Fin=0.1171, Energy=0.2168, Healthcare=0.3670, Nature=0.3256, Sales=0.3803, Transport=0.3468, Web/CloudOps=0.4260. +- frequency skill: A=0.2543, D=0.3358, H=0.3410, M=0.1505, Q=0.2187, S=0.3402, T=0.3096, W=0.2343. +- variates skill: multivariate=0.3301, univariate=0.2958. +- Outcome: Model selection only. Seasonal Naive is recomputed on the earlier cutoff and capped-history scale. Final sign augmentation improves both main and earlier cutoffs; the richer synthetic generator does not beat its control. No diagnostic labels enter training. + +## E16 earlier-window diagnostic large_parent +- Checkpoint SHA-256: `b7e4f38aebcd2cf38ce484edaad8d19851317fb3b8df485e2faa0d0423cbcb48`. +- Evaluation: 97 configurations, 9330 instances, 0 failed configurations; 15.111237525939941 seconds. +- Overall skill 0.312321; relative MASE 0.824141; relative WQL 0.573812. +- term skill: long=0.3880, medium=0.3443, short=0.2678. +- domain skill: Econ/Fin=0.1255, Energy=0.2150, Healthcare=0.3460, Nature=0.3326, Sales=0.3821, Transport=0.3403, Web/CloudOps=0.4349. +- frequency skill: A=0.2124, D=0.3388, H=0.3399, M=0.1428, Q=0.2091, S=0.3387, T=0.3160, W=0.2326. +- variates skill: multivariate=0.3359, univariate=0.2930. +- Outcome: Model selection only. Seasonal Naive is recomputed on the earlier cutoff and capped-history scale. Final sign augmentation improves both main and earlier cutoffs; the richer synthetic generator does not beat its control. No diagnostic labels enter training. + +## E16 earlier-window diagnostic large_sign1000 +- Checkpoint SHA-256: `393950048f9d0487869b7aa5e6bd01e7ea1715dba16b1367ee8be353eac7f408`. +- Evaluation: 97 configurations, 9330 instances, 0 failed configurations; 14.428916931152344 seconds. +- Overall skill 0.312240; relative MASE 0.821151; relative WQL 0.576037. +- term skill: long=0.3855, medium=0.3437, short=0.2691. +- domain skill: Econ/Fin=0.1296, Energy=0.2106, Healthcare=0.3560, Nature=0.3340, Sales=0.3905, Transport=0.3466, Web/CloudOps=0.4302. +- frequency skill: A=0.3161, D=0.3390, H=0.3442, M=0.1574, Q=0.2111, S=0.3426, T=0.3054, W=0.2304. +- variates skill: multivariate=0.3287, univariate=0.2988. +- Outcome: Model selection only. Seasonal Naive is recomputed on the earlier cutoff and capped-history scale. Final sign augmentation improves both main and earlier cutoffs; the richer synthetic generator does not beat its control. No diagnostic labels enter training. + +## E16 earlier-window diagnostic large_sign6000 +- Checkpoint SHA-256: `96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547`. +- Evaluation: 97 configurations, 9330 instances, 0 failed configurations; 9.61752462387085 seconds. +- Overall skill 0.318367; relative MASE 0.813893; relative WQL 0.570866. +- term skill: long=0.3826, medium=0.3453, short=0.2811. +- domain skill: Econ/Fin=0.1456, Energy=0.2164, Healthcare=0.3902, Nature=0.3427, Sales=0.3912, Transport=0.3501, Web/CloudOps=0.4291. +- frequency skill: A=0.3181, D=0.3498, H=0.3477, M=0.1673, Q=0.2198, S=0.3427, T=0.3048, W=0.2686. +- variates skill: multivariate=0.3320, univariate=0.3073. +- Outcome: Model selection only. Seasonal Naive is recomputed on the earlier cutoff and capped-history scale. Final sign augmentation improves both main and earlier cutoffs; the richer synthetic generator does not beat its control. No diagnostic labels enter training. + +## E16 earlier-window diagnostic large_synth6000 +- Checkpoint SHA-256: `f23469b8d187d0304e0accdc424ddd2233ed87dd77b97500176eec73644e0591`. +- Evaluation: 97 configurations, 9330 instances, 0 failed configurations; 9.829549789428711 seconds. +- Overall skill 0.311804; relative MASE 0.824530; relative WQL 0.574404. +- term skill: long=0.3704, medium=0.3520, short=0.2715. +- domain skill: Econ/Fin=0.1602, Energy=0.2091, Healthcare=0.3496, Nature=0.3283, Sales=0.3808, Transport=0.3477, Web/CloudOps=0.4301. +- frequency skill: A=0.2270, D=0.3331, H=0.3416, M=0.1436, Q=0.2168, S=0.3434, T=0.3110, W=0.2438. +- variates skill: multivariate=0.3289, univariate=0.2979. +- Outcome: Model selection only. Seasonal Naive is recomputed on the earlier cutoff and capped-history scale. Final sign augmentation improves both main and earlier cutoffs; the richer synthetic generator does not beat its control. No diagnostic labels enter training. + +## E16 earlier-window diagnostic small_continuity +- Checkpoint SHA-256: `70a3768d667df75f0d6565e831cdca8cf7c179c8546252e5902f7b7ec68ab7aa`. +- Evaluation: 97 configurations, 9330 instances, 0 failed configurations; 12.578126668930054 seconds. +- Overall skill 0.314127; relative MASE 0.818301; relative WQL 0.574876. +- term skill: long=0.3797, medium=0.3430, short=0.2755. +- domain skill: Econ/Fin=0.1152, Energy=0.2137, Healthcare=0.3801, Nature=0.3283, Sales=0.3845, Transport=0.3460, Web/CloudOps=0.4366. +- frequency skill: A=0.2537, D=0.3362, H=0.3448, M=0.1858, Q=0.2208, S=0.3366, T=0.3083, W=0.2433. +- variates skill: multivariate=0.3331, univariate=0.2986. +- Outcome: Model selection only. Seasonal Naive is recomputed on the earlier cutoff and capped-history scale. Final sign augmentation improves both main and earlier cutoffs; the richer synthetic generator does not beat its control. No diagnostic labels enter training. + +## E16 earlier-window diagnostic small_no_continuity +- Checkpoint SHA-256: `70a3768d667df75f0d6565e831cdca8cf7c179c8546252e5902f7b7ec68ab7aa`. +- Evaluation: 97 configurations, 9330 instances, 0 failed configurations; 11.378507137298584 seconds. +- Overall skill 0.308552; relative MASE 0.826361; relative WQL 0.578561. +- term skill: long=0.3803, medium=0.3416, short=0.2654. +- domain skill: Econ/Fin=0.0571, Energy=0.2115, Healthcare=0.3152, Nature=0.3257, Sales=0.3845, Transport=0.3471, Web/CloudOps=0.4427. +- frequency skill: A=0.2363, D=0.3288, H=0.3546, M=0.1261, Q=0.1813, S=0.3403, T=0.3019, W=0.2031. +- variates skill: multivariate=0.3334, univariate=0.2881. +- Outcome: Model selection only. Seasonal Naive is recomputed on the earlier cutoff and capped-history scale. Final sign augmentation improves both main and earlier cutoffs; the richer synthetic generator does not beat its control. No diagnostic labels enter training. + +## E14 final sign-augmented single model, full validation +- Checkpoint SHA-256: `96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547`. +- Evaluation: 97 configurations, 151170 instances, 0 failed configurations; not separately timed seconds. +- Overall skill 0.344508; relative MASE 0.777383; relative WQL 0.552713. +- term skill: long=0.3776, medium=0.3912, short=0.3123. +- domain skill: Econ/Fin=0.0926, Energy=0.1707, Healthcare=0.3648, Nature=0.4053, Sales=0.3446, Transport=0.4514, Web/CloudOps=0.4943. +- frequency skill: A=0.2937, D=0.3275, H=0.3694, M=0.0521, Q=0.1776, S=0.4300, T=0.3859, W=0.2124. +- variates skill: multivariate=0.3784, univariate=0.3162. +- Outcome: Full skill 0.344508, relative MASE 0.777383, relative WQL 0.552713, zero failures. Outperforms the published two-model ensemble (0.340239) and also improves the earlier-cutoff diagnostic. Full inference 57.2 s. Relocated repeated example calls are bitwise deterministic, finite and monotone. Selected for atomic publication. + +## E18 remove symmetric inference after sign-augmented training +- Checkpoint SHA-256: `96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 13.020774841308594 seconds. +- Overall skill 0.345482; relative MASE 0.778014; relative WQL 0.550625. +- term skill: long=0.3817, medium=0.3909, short=0.3125. +- domain skill: Econ/Fin=0.1197, Energy=0.1784, Healthcare=0.3304, Nature=0.4074, Sales=0.3304, Transport=0.4474, Web/CloudOps=0.4960. +- frequency skill: A=0.3782, D=0.3248, H=0.3710, M=0.0198, Q=0.1916, S=0.4321, T=0.3889, W=0.2113. +- variates skill: multivariate=0.3767, univariate=0.3195. +- Outcome: Negative result: removing the x/-x average lowers screening skill from 0.349298 to 0.345482 despite sign-augmented training. We retain symmetric inference; the speed saving is not needed for the contract budget. + +## E17 16-point projection conversion before continuation +- Checkpoint SHA-256: `d69531bfde5bf801e7f36c515bf15fd0cae0bd84f7d1479d35f4a7b67f26b508`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 17.147535800933838 seconds. +- Overall skill 0.341987; relative MASE 0.782323; relative WQL 0.553456. +- term skill: long=0.3765, medium=0.3855, short=0.3105. +- domain skill: Econ/Fin=0.0851, Energy=0.1664, Healthcare=0.3542, Nature=0.4067, Sales=0.3482, Transport=0.4386, Web/CloudOps=0.4996. +- frequency skill: A=0.2894, D=0.3469, H=0.3634, M=-0.0442, Q=0.1930, S=0.4414, T=0.3853, W=0.1987. +- variates skill: multivariate=0.3808, univariate=0.3093. +- Outcome: Conversion of our own E14 EMA6000 checkpoint loses screening skill from 0.349298 to 0.341987 before updates. Input/query projection halves are folded by summation, constant-feature activation preserved, first 16 output rows retained, and physical sine positions remain in 32-point units. No external weights. Continuation is needed. + +## E17 matched patch-resolution continuation +- Hypothesis: finer patches improve short-horizon detail and align common seasonal periods more closely without shortening context. +- Control: 32-point patches, 37,002,816 parameters; treatment: 16-point patches, 36,764,960 parameters, initialized by conversion of the same owned parent E14 EMA6000. Only patch projections and positional spacing change. Physical position units remain 32 points; metadata horizon is floored at 32 to preserve short-horizon conditioning. +- Both use the same window stream: seed47, batch256, 6000steps, AdamW8e-5, same sign-augmented sampler and median/seasonal-error-weighted loss/EMA. Context remains4096, maximum output1024. One H100 shared between runs. +- Conversion code: patch16/convert.py. The converted checkpoint retains its parent hash and conversion description. Training and runtime require the model in patch16/model.py, copied to patch16_inference/model.py. Results pending final matched checkpoints. + +## E17 patch16_trial_ema1000 +- Checkpoint SHA-256: `396a7e827e8ddd068535f96f590e710f1931818c4e0b4cc589648bf68c830ba1`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 14.109450101852417 seconds. +- Overall skill 0.348957; relative MASE 0.771301; relative WQL 0.549536. +- term skill: long=0.3832, medium=0.3926, short=0.3175. +- domain skill: Econ/Fin=0.0969, Energy=0.1735, Healthcare=0.3953, Nature=0.4077, Sales=0.3495, Transport=0.4526, Web/CloudOps=0.4982. +- frequency skill: A=0.3699, D=0.3389, H=0.3688, M=0.0874, Q=0.1860, S=0.4381, T=0.3905, W=0.1934. +- variates skill: multivariate=0.3799, univariate=0.3232. +- Outcome: Matched seed47/window-stream comparison. Final patch16 skill 0.351398 exceeds patch32 0.350171, mainly through median error. Compute: control447.6s, patch16 563.2s, sharing one H100. Earlier-cutoff and full-package validation are pending before selection. + +## E17 patch16_trial_ema3000 +- Checkpoint SHA-256: `aad4bb2f079c957b1c2a064fc245e660bd9992bf0a01b57c9a48b0d33a44436e`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 13.450159549713135 seconds. +- Overall skill 0.348611; relative MASE 0.772343; relative WQL 0.549378. +- term skill: long=0.3843, medium=0.3974, short=0.3144. +- domain skill: Econ/Fin=0.1014, Energy=0.1753, Healthcare=0.3863, Nature=0.4037, Sales=0.3479, Transport=0.4516, Web/CloudOps=0.4997. +- frequency skill: A=0.3647, D=0.3298, H=0.3718, M=0.0756, Q=0.1866, S=0.4393, T=0.3930, W=0.1879. +- variates skill: multivariate=0.3823, univariate=0.3204. +- Outcome: Matched seed47/window-stream comparison. Final patch16 skill 0.351398 exceeds patch32 0.350171, mainly through median error. Compute: control447.6s, patch16 563.2s, sharing one H100. Earlier-cutoff and full-package validation are pending before selection. + +## E17 patch16_trial_ema6000 +- Checkpoint SHA-256: `0ff54447074e0271d2e331c7d3e6e9e0fdd73353e4d8cef0175ff627385f71c3`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 10.25124716758728 seconds. +- Overall skill 0.351398; relative MASE 0.770359; relative WQL 0.546090. +- term skill: long=0.3847, medium=0.3993, short=0.3185. +- domain skill: Econ/Fin=0.1048, Energy=0.1768, Healthcare=0.3969, Nature=0.4061, Sales=0.3499, Transport=0.4528, Web/CloudOps=0.5033. +- frequency skill: A=0.3673, D=0.3318, H=0.3738, M=0.0802, Q=0.1913, S=0.4391, T=0.3969, W=0.1924. +- variates skill: multivariate=0.3843, univariate=0.3240. +- Outcome: Matched seed47/window-stream comparison. Final patch16 skill 0.351398 exceeds patch32 0.350171, mainly through median error. Compute: control447.6s, patch16 563.2s, sharing one H100. Earlier-cutoff and full-package validation are pending before selection. + +## E17 patch32_control_ema1000 +- Checkpoint SHA-256: `56edd93dd7e80399be57a359574b2fb89eba843fa1ddf01f1d3f3a2d9c2fd73b`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 12.499926567077637 seconds. +- Overall skill 0.347764; relative MASE 0.775926; relative WQL 0.548263. +- term skill: long=0.3840, medium=0.3930, short=0.3148. +- domain skill: Econ/Fin=0.1090, Energy=0.1783, Healthcare=0.3531, Nature=0.4057, Sales=0.3333, Transport=0.4508, Web/CloudOps=0.5005. +- frequency skill: A=0.3826, D=0.3190, H=0.3738, M=0.0404, Q=0.1937, S=0.4305, T=0.3927, W=0.2146. +- variates skill: multivariate=0.3815, univariate=0.3196. +- Outcome: Matched seed47/window-stream comparison. Final patch16 skill 0.351398 exceeds patch32 0.350171, mainly through median error. Compute: control447.6s, patch16 563.2s, sharing one H100. Earlier-cutoff and full-package validation are pending before selection. + +## E17 patch32_control_ema3000 +- Checkpoint SHA-256: `fe46ac478011854b20eeba3bbde42023f299e2d8544d223f046be0e234ae7c6e`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 15.177376747131348 seconds. +- Overall skill 0.349507; relative MASE 0.774280; relative WQL 0.546496. +- term skill: long=0.3853, medium=0.3964, short=0.3160. +- domain skill: Econ/Fin=0.1062, Energy=0.1803, Healthcare=0.3631, Nature=0.4048, Sales=0.3322, Transport=0.4510, Web/CloudOps=0.5041. +- frequency skill: A=0.3765, D=0.3187, H=0.3755, M=0.0515, Q=0.1928, S=0.4362, T=0.3953, W=0.2095. +- variates skill: multivariate=0.3848, univariate=0.3199. +- Outcome: Matched seed47/window-stream comparison. Final patch16 skill 0.351398 exceeds patch32 0.350171, mainly through median error. Compute: control447.6s, patch16 563.2s, sharing one H100. Earlier-cutoff and full-package validation are pending before selection. + +## E17 patch32_control_ema6000 +- Checkpoint SHA-256: `3ee55007ebabdc41a5bbb6553dcd0c4b86e90b717dd1cff758d2318f538c0929`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 9.685351848602295 seconds. +- Overall skill 0.350171; relative MASE 0.774332; relative WQL 0.545345. +- term skill: long=0.3851, medium=0.3971, short=0.3171. +- domain skill: Econ/Fin=0.1122, Energy=0.1816, Healthcare=0.3633, Nature=0.4023, Sales=0.3323, Transport=0.4516, Web/CloudOps=0.5054. +- frequency skill: A=0.3791, D=0.3172, H=0.3768, M=0.0518, Q=0.1910, S=0.4349, T=0.3964, W=0.2119. +- variates skill: multivariate=0.3854, univariate=0.3207. +- Outcome: Matched seed47/window-stream comparison. Final patch16 skill 0.351398 exceeds patch32 0.350171, mainly through median error. Compute: control447.6s, patch16 563.2s, sharing one H100. Earlier-cutoff and full-package validation are pending before selection. + +## E19 prefix-consistent direct decoder +- Hypothesis: requested total horizon should not change predictions of the same first steps. The context-only probe compared H48 versus H720 after all inference rules; mean absolute median-prefix differences were 0.0059–0.0582 context standard deviations across six sampled configurations (prefix_probe.json). +- Change: future-query self-attention becomes causal and the total-horizon metadata feature is replaced by its constant training-mixture mean. Forecasts remain direct and parallel; no generated output is fed back. Encoder/cross attention and all data/loss settings stay unchanged. +- Seed47, batch256, 6000steps, same original E14 EMA6000 parent and sampled-window stream as E17 patch32_control. Reuse that completed control instead of repeating it. Only the new decoder variant trains. Runtime/model: prefix_consistent/model.py, copied into prefix_inference. +- Results pending. + +## E17 patch16, full validation +- Checkpoint SHA-256: `0ff54447074e0271d2e331c7d3e6e9e0fdd73353e4d8cef0175ff627385f71c3`. +- Evaluation: 97 configurations, 151170 instances, 0 failed configurations; not separately timed seconds. +- Overall skill 0.346729; relative MASE 0.773486; relative WQL 0.551739. +- term skill: long=0.3768, medium=0.3979, short=0.3138. +- domain skill: Econ/Fin=0.0839, Energy=0.1675, Healthcare=0.4022, Nature=0.4059, Sales=0.3593, Transport=0.4530, Web/CloudOps=0.4957. +- frequency skill: A=0.2818, D=0.3356, H=0.3684, M=0.0967, Q=0.1741, S=0.4391, T=0.3887, W=0.1870. +- variates skill: multivariate=0.3799, univariate=0.3190. +- Outcome: Full skill 0.346729, relative MASE 0.773486 and relative WQL 0.551739, zero failures; improves the previous published 0.344508. Inference 57.5 seconds. Earlier-window skill 0.322486 versus control 0.319021. Relocated repeated example outputs are bitwise identical, finite and monotone. Initial assembly failed on a symlinked lineage path, was never published, and was rebuilt after canonicalizing paths; the missing-output score from that failed pipeline is discarded. + +## E19 prefix_consistent_ema1000 +- Checkpoint SHA-256: `aa797f3356c30e1859821bd807202298774b8d44b59b8325cc73956796a83b21`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 10.920389413833618 seconds. +- Overall skill 0.347132; relative MASE 0.775797; relative WQL 0.549418. +- term skill: long=0.3820, medium=0.3928, short=0.3146. +- domain skill: Econ/Fin=0.1091, Energy=0.1769, Healthcare=0.3709, Nature=0.4082, Sales=0.3333, Transport=0.4492, Web/CloudOps=0.4954. +- frequency skill: A=0.3824, D=0.3200, H=0.3727, M=0.0361, Q=0.1918, S=0.4265, T=0.3902, W=0.2278. +- variates skill: multivariate=0.3798, univariate=0.3199. +- Outcome: Final skill 0.349313 is below the reused matched patch32 control (0.350171). This training recipe does not improve the score; not selected. Training elapsed 288.9 seconds on one H100. + +## E19 prefix_consistent_ema3000 +- Checkpoint SHA-256: `11094f18080cd31f38a7f33d1df852adc957d9f1705653360b21e790e55b6648`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 10.28545594215393 seconds. +- Overall skill 0.348148; relative MASE 0.775101; relative WQL 0.548201. +- term skill: long=0.3814, medium=0.3951, short=0.3158. +- domain skill: Econ/Fin=0.1060, Energy=0.1786, Healthcare=0.3758, Nature=0.4101, Sales=0.3323, Transport=0.4489, Web/CloudOps=0.4963. +- frequency skill: A=0.3799, D=0.3215, H=0.3735, M=0.0487, Q=0.1876, S=0.4294, T=0.3915, W=0.2202. +- variates skill: multivariate=0.3812, univariate=0.3206. +- Outcome: Final skill 0.349313 is below the reused matched patch32 control (0.350171). This training recipe does not improve the score; not selected. Training elapsed 288.9 seconds on one H100. + +## E19 prefix_consistent_ema6000 +- Checkpoint SHA-256: `2572d0401c85966c3936b3feed906dee4206ca403a778c2356406aca57988ef7`. +- Evaluation: 97 configurations, 9473 instances, 0 failed configurations; 9.322679996490479 seconds. +- Overall skill 0.349313; relative MASE 0.774658; relative WQL 0.546555. +- term skill: long=0.3800, medium=0.3960, short=0.3181. +- domain skill: Econ/Fin=0.1130, Energy=0.1774, Healthcare=0.3765, Nature=0.4114, Sales=0.3328, Transport=0.4502, Web/CloudOps=0.4987. +- frequency skill: A=0.3795, D=0.3224, H=0.3737, M=0.0589, Q=0.1895, S=0.4294, T=0.3930, W=0.2214. +- variates skill: multivariate=0.3825, univariate=0.3216. +- Outcome: Final skill 0.349313 is below the reused matched patch32 control (0.350171). This training recipe does not improve the score; not selected. Training elapsed 288.9 seconds on one H100. diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/README.md b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4b76c23b3d8e1677dc68fc7feb7174c552c5ba17 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/README.md @@ -0,0 +1,7 @@ +# Direct seasonal foundation forecaster + +Run `bash infer.sh INPUT_DIR OUTPUT_DIR`. All runtime assets are included; package versions are pinned in requirements.txt. This 36,764,960-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/. + +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. + +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. diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/config.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/config.json new file mode 100644 index 0000000000000000000000000000000000000000..078f7b1ce6140da05eadbba8a932c07506ad9495 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/config.json @@ -0,0 +1,9 @@ +{ + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024 +} diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/continuity.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/continuity.py new file mode 100644 index 0000000000000000000000000000000000000000..bebb06b9c20f322b9d5564650889e2236ae94494 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/continuity.py @@ -0,0 +1,18 @@ +"""Fixed continuity prior for histories whose adjacent samples change slowly.""" +import numpy as np + +def apply_continuity(ctx,quant,tau=24.): + b,_,h=quant.shape + bias=np.zeros(b,np.float32) + positive=((ctx>=0)|~np.isfinite(ctx)).all(-1) + for i in range(b): + x=ctx[i,-512:].astype(np.float64) + if len(x)<8 or not np.isfinite(x[-1]):continue + diff=np.diff(x) + if np.isfinite(diff).sum()<8 or not np.isfinite(diff[-8:]).any():continue + ratio=np.nanmean(diff*diff)/(np.nanvar(x)+1e-12) + weight=float(np.clip(1-ratio/.5,0,.95)) + bias[i]=weight*(x[-1]+np.nanmedian(diff[-8:])-quant[i,4,0]) + out=quant+bias[:,None,None]*np.exp(-np.arange(h)/tau)[None,None,:] + out=np.where(positive[:,None,None],np.maximum(0,out),out) + return out.astype(np.float32) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/infer.sh b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/infer.sh new file mode 100644 index 0000000000000000000000000000000000000000..cd8b850fa281f16a1fdf4147cb8e3ce1412f2702 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/infer.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -euo pipefail +export OMP_NUM_THREADS=4 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=4 +exec python3 "$(dirname "$(readlink -f "$0")")/predict.py" "$1" "$2" diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/model.py new file mode 100644 index 0000000000000000000000000000000000000000..06cce56e2ce671b6683f0246900abfcac06bb3c0 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/model.py @@ -0,0 +1,154 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/model_manifest.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/model_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..9726e500b5c7512c54c510b573b3d6eb541895ef --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/model_manifest.json @@ -0,0 +1,185 @@ +{ + "name": "direct-seasonal-foundation", + "contract": "timeseries-forecast/v1", + "parameters": 36764960, + "pretrained_assets": [], + "sources_used": [ + "gifteval_pretrain/BEIJING_SUBWAY_30MIN", + "gifteval_pretrain/HZMETRO", + "gifteval_pretrain/LOS_LOOP", + "gifteval_pretrain/PEMS03", + "gifteval_pretrain/PEMS04", + "gifteval_pretrain/PEMS07", + "gifteval_pretrain/PEMS08", + "gifteval_pretrain/PEMS_BAY", + "gifteval_pretrain/Q-TRAFFIC", + "gifteval_pretrain/SHMETRO", + "gifteval_pretrain/alibaba_cluster_trace_2018", + "gifteval_pretrain/australian_electricity_demand", + "gifteval_pretrain/azure_vm_traces_2017", + "gifteval_pretrain/bdg-2_bear", + "gifteval_pretrain/bdg-2_fox", + "gifteval_pretrain/bdg-2_panther", + "gifteval_pretrain/bdg-2_rat", + "gifteval_pretrain/bitcoin_with_missing", + "gifteval_pretrain/borealis", + "gifteval_pretrain/borg_cluster_data_2011", + "gifteval_pretrain/buildings_900k", + "gifteval_pretrain/bull", + "gifteval_pretrain/cdc_fluview_ilinet", + "gifteval_pretrain/cdc_fluview_who_nrevss", + "gifteval_pretrain/china_air_quality", + "gifteval_pretrain/cif_2016_12", + "gifteval_pretrain/cif_2016_6", + "gifteval_pretrain/cmip6_2000", + "gifteval_pretrain/cmip6_2005", + "gifteval_pretrain/cmip6_2010", + "gifteval_pretrain/cockatoo", + "gifteval_pretrain/covid19_energy", + "gifteval_pretrain/covid_mobility", + "gifteval_pretrain/elecdemand", + "gifteval_pretrain/elf", + "gifteval_pretrain/era5_2010", + "gifteval_pretrain/era5_2011", + "gifteval_pretrain/era5_2012", + "gifteval_pretrain/era5_2013", + "gifteval_pretrain/era5_2014", + "gifteval_pretrain/era5_2015", + "gifteval_pretrain/era5_2016", + "gifteval_pretrain/era5_2017", + "gifteval_pretrain/era5_2018", + "gifteval_pretrain/extended_web_traffic_with_missing", + "gifteval_pretrain/favorita_sales", + "gifteval_pretrain/favorita_transactions", + "gifteval_pretrain/gfc12_load", + "gifteval_pretrain/gfc14_load", + "gifteval_pretrain/gfc17_load", + "gifteval_pretrain/godaddy", + "gifteval_pretrain/hog", + "gifteval_pretrain/ideal", + "gifteval_pretrain/kaggle_web_traffic_weekly", + "gifteval_pretrain/kdd2022", + "gifteval_pretrain/largest_2017", + "gifteval_pretrain/largest_2018", + "gifteval_pretrain/largest_2019", + "gifteval_pretrain/largest_2020", + "gifteval_pretrain/largest_2021", + "gifteval_pretrain/lcl", + "gifteval_pretrain/london_smart_meters_with_missing", + "gifteval_pretrain/m1_monthly", + "gifteval_pretrain/m1_quarterly", + "gifteval_pretrain/m1_yearly", + "gifteval_pretrain/m5", + "gifteval_pretrain/monash_m3_monthly", + "gifteval_pretrain/monash_m3_other", + "gifteval_pretrain/monash_m3_quarterly", + "gifteval_pretrain/nn5_daily_with_missing", + "gifteval_pretrain/nn5_weekly", + "gifteval_pretrain/oikolab_weather", + "gifteval_pretrain/pdb", + "gifteval_pretrain/project_tycho", + "gifteval_pretrain/residential_load_power", + "gifteval_pretrain/residential_pv_power", + "gifteval_pretrain/rideshare_with_missing", + "gifteval_pretrain/sceaux", + "gifteval_pretrain/smart", + "gifteval_pretrain/solar_power", + "gifteval_pretrain/spain", + "gifteval_pretrain/subseasonal", + "gifteval_pretrain/subseasonal_precip", + "gifteval_pretrain/sunspot_with_missing", + "gifteval_pretrain/taxi_30min", + "gifteval_pretrain/tourism_quarterly", + "gifteval_pretrain/tourism_yearly", + "gifteval_pretrain/traffic_hourly", + "gifteval_pretrain/traffic_weekly", + "gifteval_pretrain/uber_tlc_daily", + "gifteval_pretrain/uber_tlc_hourly", + "gifteval_pretrain/vehicle_trips_with_missing", + "gifteval_pretrain/wiki-rolling_nips", + "gifteval_pretrain/wind_farms_with_missing", + "gifteval_pretrain/wind_power", + "synthetic:independent sign reflection of sampled allowed-corpus and locally generated windows, probability 0.5, seeds 43 and 47", + "synthetic:own direct_v1 Fourier seasons, damped trends, AR noise, changepoints and intermittent demand; seeds 23,43,47" + ], + "weights_sha256": "0ff54447074e0271d2e331c7d3e6e9e0fdd73353e4d8cef0175ff627385f71c3", + "config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024 + }, + "training_lineage": [ + { + "checkpoint": "runs/patch16_trial/ema006000.pt", + "sha256": "0ff54447074e0271d2e331c7d3e6e9e0fdd73353e4d8cef0175ff627385f71c3", + "step": 6000, + "seed": 47, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789 + }, + { + "checkpoint": "patch16_init.pt", + "sha256": "d69531bfde5bf801e7f36c515bf15fd0cae0bd84f7d1479d35f4a7b67f26b508", + "step": 6000, + "seed": 43, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "conversion": { + "from_checkpoint": "/run-state/workspace/research/runs/large_sign/ema006000.pt", + "from_sha256": "96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547", + "method": "fold input/query halves by summation; retain first 16 output rows; preserve physical positional units" + } + }, + { + "checkpoint": "runs/large_sign/ema006000.pt", + "sha256": "96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547", + "step": 6000, + "seed": 43, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789 + }, + { + "checkpoint": "runs/direct_large/step024000.pt", + "sha256": "b7e4f38aebcd2cf38ce484edaad8d19851317fb3b8df485e2faa0d0423cbcb48", + "step": 24000, + "seed": 23, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "initialization": "random initialization in this workspace" + } + ], + "symmetric_averaging": true, + "seasonal_gate": { + "variance_ratio_threshold": 0.25, + "maximum_weight": 0.98, + "cycles_averaged": 4 + }, + "continuity": { + "decay_steps": 24, + "variance_ratio_threshold": 0.5, + "maximum_weight": 0.95, + "lookback": 512, + "slope_median_differences": 8 + }, + "notes": "All training lineage originates from random initialization here, using only the declared corpus and locally generated series. Validation was used only for selection and diagnostics. Context transformations are fixed formulas; there is no inference-time fitting or parameter adaptation.", + "runtime_code_sha256": { + "seasonal.py": "96048ea798da867bdf354b4fdf1f3923f05abdf65d5492797795fd5ea5dcf99c", + "infer.sh": "5fe66b4fe9a4787285d830cfd96975701e97286a75ba7c3687bd8891475edf68", + "ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "predict.py": "39ef28a00ee5c2d97c0bed77851340b76fe7ef323c3b0f00649d2803cf20231d", + "model.py": "8031c597b354eb2cf464140bee40c3ec8dff86c775b5c55c5ce910302b443582", + "continuity.py": "dbb08d2229ad80ad00f638b0b9f2f6ca13c663e0fd6730058e5fee8ff54545d5" + } +} diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..729bace71aafe70f5a8014197fc10b2007a6f78f --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/predict.py @@ -0,0 +1,53 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +from seasonal import apply_gate +from continuity import apply_continuity +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16): + qq,mu,scale=model(torch.cat((x,-x),0),p.repeat(2,1),h) + qq=qq*scale[:,:,None]+mu[:,:,None] + qq=(qq[:len(ids)]-qq[len(ids):].flip(-1))*.5 + positive=((x>=0)|~torch.isfinite(x)).all(-1) + qq=torch.where(positive[:,None,None],qq.clamp(min=0),qq) + q=qq.transpose(1,2).float().cpu().numpy() + q=apply_gate(ctx,p.cpu().numpy(),q) + q=apply_continuity(ctx,q) + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/direct_large/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/direct_large/data.py new file mode 100644 index 0000000000000000000000000000000000000000..2378e33d7352ba5ad97d566148782e63e64b367c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/direct_large/data.py @@ -0,0 +1,71 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + return ctx,tgt,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/direct_large/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/direct_large/model.py new file mode 100644 index 0000000000000000000000000000000000000000..7a224cc12a159446a1e427b2052b53d1d1f7e83e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/direct_large/model.py @@ -0,0 +1,142 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional(torch.arange(-nt,0,device=z.device),self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + q=self.query(base.reshape(b,h//p,p*9))+positional(torch.arange(h//p,device=z.device),self.d)[None]+emb + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + pin=torch.maximum(levels*err,(levels-1)*err).mean(-1) + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + return per.mean() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/direct_large/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/direct_large/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/direct_large/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/direct_large/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/direct_large/train.py new file mode 100644 index 0000000000000000000000000000000000000000..a2ccc736bfef804259199a2dd315347d9854b680 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/direct_large/train.py @@ -0,0 +1,67 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(6);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/large_sign/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/large_sign/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/large_sign/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/large_sign/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/large_sign/model.py new file mode 100644 index 0000000000000000000000000000000000000000..60aeb14b5f4fa298521ddce8a3276d076c1bb631 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/large_sign/model.py @@ -0,0 +1,154 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional(torch.arange(-nt,0,device=z.device),self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + q=self.query(base.reshape(b,h//p,p*9))+positional(torch.arange(h//p,device=z.device),self.d)[None]+emb + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/large_sign/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/large_sign/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/large_sign/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/large_sign/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/large_sign/train.py new file mode 100644 index 0000000000000000000000000000000000000000..d089166fb1612ddf4955fcd2f096cb0b33624dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/large_sign/train.py @@ -0,0 +1,70 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(3);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/patch16/convert.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/patch16/convert.py new file mode 100644 index 0000000000000000000000000000000000000000..b2cbc8fc919be6a77eca9ab19c4faa06060a2e0d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/patch16/convert.py @@ -0,0 +1,18 @@ +"""Convert only our own trained checkpoint from 32- to 16-point patches. + +Context/query projections fold the two halves by summation, preserving the +embedding of constant features. The output projection keeps the first half. +Attention/MLP weights are inherited unchanged; position units remain 32 points. +""" +import argparse,torch,hashlib +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('--input',required=True);ap.add_argument('--output',required=True);a=ap.parse_args() +ck=torch.load(a.input,map_location='cpu',weights_only=False);state=ck['model'];d=ck['config']['d'];assert ck['config']['patch']==32 +old=state['embed.0.weight'].reshape(d,2,32);state['embed.0.weight']=(old[:,:,:16]+old[:,:,16:]).reshape(d,32) +old=state['query.0.weight'].reshape(d,32,9);state['query.0.weight']=(old[:,:16]+old[:,16:]).reshape(d,16*9) +state['head.weight']=state['head.weight'].reshape(32,18,d)[:16].reshape(16*18,d).clone() +state['head.bias']=state['head.bias'].reshape(32,18)[:16].reshape(16*18).clone() +ck['config']['patch']=16 +ck['conversion']={'from_checkpoint':str(Path(a.input).resolve()),'from_sha256':hashlib.sha256(Path(a.input).read_bytes()).hexdigest(),'method':'fold input/query halves by summation; retain first 16 output rows; preserve physical positional units'} +ck['args']={**ck['args'],'initialize_from':str(Path(a.input).resolve()),'converted':True} +torch.save(ck,a.output) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/patch16/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/patch16/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/patch16/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/patch16/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/patch16/model.py new file mode 100644 index 0000000000000000000000000000000000000000..06cce56e2ce671b6683f0246900abfcac06bb3c0 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/patch16/model.py @@ -0,0 +1,154 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/patch16/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/patch16/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/patch16/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/patch16/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/patch16/train.py new file mode 100644 index 0000000000000000000000000000000000000000..3cdc106980371c99d81c71d6746943c47206be83 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/provenance/patch16/train.py @@ -0,0 +1,71 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(3);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/requirements.txt b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..ca733199990e5dc8e6a90509cc691f00ab8e9f5d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/requirements.txt @@ -0,0 +1,12 @@ +# Runtime pins recorded from the contributor's working environment on 2026-09-17 (Python 3.11). +# torch comes from the pytorch/pytorch:2.14.0-cuda12.6-cudnn9-runtime base image (cu130 needs driver >= 580). +torch==2.14.0 +numpy==2.4.6 +h5py==3.16.0 +pandas==2.3.3 +scipy==1.17.1 +pyarrow==25.0.1 +huggingface-hub==0.36.2 +einops==0.8.2 +safetensors==0.8.0 +pytest==9.1.1 diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/seasonal.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/seasonal.py new file mode 100644 index 0000000000000000000000000000000000000000..4eaeca9b9a0e7a64cef2a27f074e57ea3b810489 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/seasonal.py @@ -0,0 +1,38 @@ +"""A fixed confidence gate for highly repeatable history; no fitted parameters.""" +import numpy as np + +def apply_gate(ctx,periods,quant,threshold=.25,strength=1.): + # Each row uses only its own context. Quantile blending preserves ordering. + b,_,h=quant.shape + out=quant.copy() + for i in range(b): + x=ctx[i];valid=np.isfinite(x) + if not valid.any():continue + x=x[np.flatnonzero(valid)[0]:] + best=None + for p in periods[i]: + p=int(p) + if p<2 or len(x)<3*p:continue + k=min(len(x)//p,8);history=x[-k*p:] + pairs=np.isfinite(history[p:])&np.isfinite(history[:-p]) + if pairs.sum()0) + # Error of a season relative to the previous one, corrected for averaging. + sigma=float(np.sqrt(np.mean(err.astype(np.float64)**2)/2*(1+1/min(k,4)))) + idx=np.arange(h)%p;median=mu[idx] + z=np.array([-1.2815515655,-.8416212336,-.5244005127,-.2533471031,0,.2533471031,.5244005127,.8416212336,1.2815515655]) + sq=median[None]+z[:,None]*sigma + sq=np.where(np.isfinite(sq),sq,quant[i]) + if np.nanmin(x)>=0:sq=np.maximum(0,sq) + best=(weight,sq) + if best is not None:out[i]=(1-best[0])*quant[i]+best[0]*best[1] + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/validation_report.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/validation_report.json new file mode 100644 index 0000000000000000000000000000000000000000..cdec1e938b6fe1e08957ba92e094db228974b641 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S011/validation_report.json @@ -0,0 +1,4888 @@ +{ + "contract": "timeseries-forecast/v1", + "split": "valid", + "reward": 0.3467292398596037, + "skill_score": 0.3467292398596037, + "rel_mase_gmean": 0.7734863890027569, + "rel_wql_gmean": 0.5517391024871545, + "n_configs": 97, + "n_failed": 0, + "n_instances": 151170, + "n_instances_scored": 151170, + "n_partial": 0, + "failures": [], + "groups": { + "term": { + "long": { + "n_configs": 21, + "rel_mase_gmean": 0.7593353194430665, + "rel_wql_gmean": 0.5115504273645738 + }, + "medium": { + "n_configs": 21, + "rel_mase_gmean": 0.7127988835643092, + "rel_wql_gmean": 0.5085396508947161 + }, + "short": { + "n_configs": 55, + "rel_mase_gmean": 0.8036437593108613, + "rel_wql_gmean": 0.5858608534462506 + } + }, + "domain": { + "Econ/Fin": { + "n_configs": 6, + "rel_mase_gmean": 0.9416692263882858, + "rel_wql_gmean": 0.8913216104839734 + }, + "Energy": { + "n_configs": 32, + "rel_mase_gmean": 0.9655127780608993, + "rel_wql_gmean": 0.7177522998852056 + }, + "Healthcare": { + "n_configs": 5, + "rel_mase_gmean": 0.6325516416026641, + "rel_wql_gmean": 0.5649069396734797 + }, + "Nature": { + "n_configs": 15, + "rel_mase_gmean": 0.8377442827193792, + "rel_wql_gmean": 0.4212656971963676 + }, + "Sales": { + "n_configs": 4, + "rel_mase_gmean": 0.8142265091173622, + "rel_wql_gmean": 0.5042192875626954 + }, + "Transport": { + "n_configs": 15, + "rel_mase_gmean": 0.6608611751032142, + "rel_wql_gmean": 0.45280667201232155 + }, + "Web/CloudOps": { + "n_configs": 20, + "rel_mase_gmean": 0.5641229854795369, + "rel_wql_gmean": 0.4507848090110932 + } + }, + "frequency": { + "A": { + "n_configs": 1, + "rel_mase_gmean": 0.6944056867986844, + "rel_wql_gmean": 0.7427394334262339 + }, + "D": { + "n_configs": 15, + "rel_mase_gmean": 0.8005983962380007, + "rel_wql_gmean": 0.5513611229983304 + }, + "H": { + "n_configs": 31, + "rel_mase_gmean": 0.7564775116569121, + "rel_wql_gmean": 0.5273547853038317 + }, + "M": { + "n_configs": 5, + "rel_mase_gmean": 0.9804930497671763, + "rel_wql_gmean": 0.8322199018629278 + }, + "Q": { + "n_configs": 1, + "rel_mase_gmean": 0.803916398910778, + "rel_wql_gmean": 0.8484491320684553 + }, + "S": { + "n_configs": 6, + "rel_mase_gmean": 0.6365044248540928, + "rel_wql_gmean": 0.494345396933374 + }, + "T": { + "n_configs": 30, + "rel_mase_gmean": 0.7412742404131689, + "rel_wql_gmean": 0.504075275968857 + }, + "W": { + "n_configs": 8, + "rel_mase_gmean": 0.9331977779228706, + "rel_wql_gmean": 0.708301591232302 + } + }, + "variates": { + "multivariate": { + "n_configs": 43, + "rel_mase_gmean": 0.7227938531623267, + "rel_wql_gmean": 0.5319631139161088 + }, + "univariate": { + "n_configs": 54, + "rel_mase_gmean": 0.8163835132635164, + "rel_wql_gmean": 0.5680111326451796 + } + } + }, + "quantile_crossing_fraction_mean": 0.0, + "configs": [ + { + "config_id": "m4_yearly__A__short", + "leaderboard_key": "m4_yearly/A/short", + "dataset": "m4_yearly", + "term": "short", + "freq": "A-DEC", + "prediction_length": 6, + "seasonality": 1, + "n_variates": 1, + "n_instances": 22728, + "domain": "Econ/Fin", + "n_cohorts": 3, + "skipped_series": 235, + "dropped_containers": 11, + "status": "ok", + "baseline": { + "mase": 4.730803330645802, + "wql": 0.15602350647819704 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 22728, + "instances": 22728, + "fraction": 1.0 + }, + "metrics": { + "mase": 3.285096735926602, + "wql": 0.11588481080279041, + "wsql_by_level": [ + 0.0652703229770519, + 0.10106714851667874, + 0.12439043776519876, + 0.13508146390566278, + 0.1405542028613566, + 0.14002616019621944, + 0.1327957998772841, + 0.11710166221733585, + 0.08667609890832557 + ], + "n_valid_labels": 136368, + "n_masked_labels": 0, + "mae_median": 729.6039570803938, + "n_mase_elements": 136356, + "n_seasonal_error_zero": 2, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6944056867986844, + "wql": 0.7427394334262339 + } + }, + { + "config_id": "m4_quarterly__Q__short", + "leaderboard_key": "m4_quarterly/Q/short", + "dataset": "m4_quarterly", + "term": "short", + "freq": "Q-DEC", + "prediction_length": 8, + "seasonality": 4, + "n_variates": 1, + "n_instances": 23905, + "domain": "Econ/Fin", + "n_cohorts": 3, + "dropped_containers": 95, + "status": "ok", + "baseline": { + "mase": 1.5909093331240343, + "wql": 0.0995990835037221 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 23905, + "instances": 23905, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.278958102078621, + "wql": 0.08450475595354662, + "wsql_by_level": [ + 0.04998223264191499, + 0.07513437149194373, + 0.09065480946548592, + 0.09921196954962949, + 0.10244163404453334, + 0.10161432396254168, + 0.096277024311297, + 0.08416343490233186, + 0.061063003212241555 + ], + "n_valid_labels": 191240, + "n_masked_labels": 0, + "mae_median": 583.3323972056137, + "n_mase_elements": 191232, + "n_seasonal_error_zero": 1, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.803916398910778, + "wql": 0.8484491320684553 + } + }, + { + "config_id": "m4_monthly__M__short", + "leaderboard_key": "m4_monthly/M/short", + "dataset": "m4_monthly", + "term": "short", + "freq": "M", + "prediction_length": 18, + "seasonality": 12, + "n_variates": 1, + "n_instances": 47501, + "domain": "Econ/Fin", + "n_cohorts": 3, + "dropped_containers": 499, + "status": "ok", + "baseline": { + "mase": 1.2366691185612824, + "wql": 0.11781121192744513 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 47501, + "instances": 47501, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0091944968818667, + "wql": 0.09420700037523033, + "wsql_by_level": [ + 0.05634231839468196, + 0.08445598774412749, + 0.10179265046974986, + 0.1113553619105695, + 0.11531904885545276, + 0.11400747379927453, + 0.10645535037774012, + 0.09188674948978329, + 0.06624806233569348 + ], + "n_valid_labels": 855018, + "n_masked_labels": 0, + "mae_median": 546.8068375718956, + "n_mase_elements": 855018, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8160586220960581, + "wql": 0.799643759146187 + } + }, + { + "config_id": "m4_weekly__W__short", + "leaderboard_key": "m4_weekly/W/short", + "dataset": "m4_weekly", + "term": "short", + "freq": "W-SUN", + "prediction_length": 13, + "seasonality": 1, + "n_variates": 1, + "n_instances": 355, + "domain": "Econ/Fin", + "n_cohorts": 2, + "dropped_containers": 4, + "status": "ok", + "baseline": { + "mase": 2.895128591740639, + "wql": 0.06508715280630521 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 355, + "instances": 355, + "fraction": 1.0 + }, + "metrics": { + "mase": 3.3980190114163595, + "wql": 0.053338397431413845, + "wsql_by_level": [ + 0.027000498580017074, + 0.04219358555154517, + 0.05397852522625041, + 0.0617269779369588, + 0.06628436778210263, + 0.0679105065204559, + 0.06503314435292691, + 0.056222927454864964, + 0.039695043477602734 + ], + "n_valid_labels": 4615, + "n_masked_labels": 0, + "mae_median": 345.00061534414573, + "n_mase_elements": 4615, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.1737022739198495, + "wql": 0.8194919447489916 + } + }, + { + "config_id": "m4_daily__D__short", + "leaderboard_key": "m4_daily/D/short", + "dataset": "m4_daily", + "term": "short", + "freq": "D", + "prediction_length": 14, + "seasonality": 1, + "n_variates": 1, + "n_instances": 4204, + "domain": "Econ/Fin", + "n_cohorts": 2, + "dropped_containers": 23, + "status": "ok", + "baseline": { + "mase": 3.2161164077095057, + "wql": 0.02310161661155265 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 4204, + "instances": 4204, + "fraction": 1.0 + }, + "metrics": { + "mase": 3.364987221377677, + "wql": 0.022474790140769443, + "wsql_by_level": [ + 0.013910109224198082, + 0.020204963573216588, + 0.02413496041494582, + 0.026400407616302014, + 0.027394088293604194, + 0.02718752065820905, + 0.02548976469806429, + 0.02190160362657996, + 0.015649693161804985 + ], + "n_valid_labels": 58856, + "n_masked_labels": 0, + "mae_median": 175.52072377222396, + "n_mase_elements": 58842, + "n_seasonal_error_zero": 1, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.0462890003954166, + "wql": 0.9728665538294085 + } + }, + { + "config_id": "m4_hourly__H__short", + "leaderboard_key": "m4_hourly/H/short", + "dataset": "m4_hourly", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 414, + "domain": "Econ/Fin", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.22836124915778, + "wql": 0.034474947608819397 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 414, + "instances": 414, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.5309508748615828, + "wql": 0.043028224588481906, + "wsql_by_level": [ + 0.020946693036999718, + 0.03479227781122329, + 0.044832910072165236, + 0.05125267239561959, + 0.054725038385099976, + 0.05533466707298087, + 0.052033691603027274, + 0.04355263803444005, + 0.02978343288478121 + ], + "n_valid_labels": 19872, + "n_masked_labels": 0, + "mae_median": 412.2437466506857, + "n_mase_elements": 19872, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.2463360236341483, + "wql": 1.2481012321386213 + } + }, + { + "config_id": "electricity__T__short", + "leaderboard_key": "electricity/15T/short", + "dataset": "electricity/15T", + "term": "short", + "freq": "15T", + "prediction_length": 48, + "seasonality": 96, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0916823579221513, + "wql": 0.06198863606457304 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0839946286460824, + "wql": 0.058911422194274636, + "wsql_by_level": [ + 0.0326286455727432, + 0.051377988648648155, + 0.06411585231804896, + 0.07230384490899226, + 0.07620898017465949, + 0.07565800810664002, + 0.06929628377981645, + 0.055559415060894846, + 0.03305378117802843 + ], + "n_valid_labels": 17712, + "n_masked_labels": 48, + "mae_median": 77.40946906509402, + "n_mase_elements": 17712, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 0.9929579064640183, + "wql": 0.950358419451383 + } + }, + { + "config_id": "electricity__T__medium", + "leaderboard_key": "electricity/15T/medium", + "dataset": "electricity/15T", + "term": "medium", + "freq": "15T", + "prediction_length": 480, + "seasonality": 96, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.5099936923797364, + "wql": 0.12054261982000446 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.929207293245438, + "wql": 0.08517793862256944, + "wsql_by_level": [ + 0.04111884792773943, + 0.06572598462550647, + 0.08321324537664494, + 0.09515563108547608, + 0.10281721416520213, + 0.10723622820223976, + 0.10552782737540521, + 0.09510776429919797, + 0.07069870454571289 + ], + "n_valid_labels": 177120, + "n_masked_labels": 480, + "mae_median": 73.94832507324013, + "n_mase_elements": 177120, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 0.6153716389245413, + "wql": 0.7066209341538956 + } + }, + { + "config_id": "electricity__T__long", + "leaderboard_key": "electricity/15T/long", + "dataset": "electricity/15T", + "term": "long", + "freq": "15T", + "prediction_length": 720, + "seasonality": 96, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0941077605435365, + "wql": 0.107564338522276 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9032420749380666, + "wql": 0.09238040141247203, + "wsql_by_level": [ + 0.041512537013455364, + 0.06750899463988361, + 0.08637251891329886, + 0.09988918082419154, + 0.10903390348055025, + 0.11517537310236073, + 0.11566525221676226, + 0.10839425003439808, + 0.08787160248734764 + ], + "n_valid_labels": 265680, + "n_masked_labels": 720, + "mae_median": 78.61851091996377, + "n_mase_elements": 265680, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 0.8255512916655936, + "wql": 0.8588385582210459 + } + }, + { + "config_id": "electricity__H__short", + "leaderboard_key": "electricity/H/short", + "dataset": "electricity/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9861593153062442, + "wql": 0.06763119078713985 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.1445217417450337, + "wql": 0.08284295089260249, + "wsql_by_level": [ + 0.04643263208125461, + 0.07051563636924672, + 0.0867570378193566, + 0.09780462943393113, + 0.1025989140665377, + 0.10237115432098212, + 0.09705204947613948, + 0.0842611506374539, + 0.05779335382852028 + ], + "n_valid_labels": 17712, + "n_masked_labels": 48, + "mae_median": 311.59603410653176, + "n_mase_elements": 17712, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 1.1605850332505465, + "wql": 1.224922257443901 + } + }, + { + "config_id": "electricity__H__medium", + "leaderboard_key": "electricity/H/medium", + "dataset": "electricity/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.2478422873379948, + "wql": 0.12311153060577013 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9645866708830317, + "wql": 0.07933529808488596, + "wsql_by_level": [ + 0.044539667168998126, + 0.06711329942505335, + 0.0807057250233657, + 0.08864551836147183, + 0.0934594540102289, + 0.0965705315749401, + 0.09432494919340544, + 0.08491584947404622, + 0.06374268853246404 + ], + "n_valid_labels": 177120, + "n_masked_labels": 480, + "mae_median": 251.5149029945834, + "n_mase_elements": 177120, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 0.773003672556066, + "wql": 0.6444180954823381 + } + }, + { + "config_id": "electricity__H__long", + "leaderboard_key": "electricity/H/long", + "dataset": "electricity/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.356699671272273, + "wql": 0.14674885232557194 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.2799362049947516, + "wql": 0.11145239347830452, + "wsql_by_level": [ + 0.04863287233149969, + 0.0781732104737389, + 0.0997012326317705, + 0.11582071366200275, + 0.12785247674887457, + 0.1372304812639637, + 0.14126931896266864, + 0.13687952644172174, + 0.11751170878850013 + ], + "n_valid_labels": 265680, + "n_masked_labels": 720, + "mae_median": 350.4176832062221, + "n_mase_elements": 265680, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 0.9434189689118633, + "wql": 0.7594771046729557 + } + }, + { + "config_id": "electricity__D__short", + "leaderboard_key": "electricity/D/short", + "dataset": "electricity/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.6456666278884469, + "wql": 0.09261378216375024 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.5120940395583737, + "wql": 0.06955368026647407, + "wsql_by_level": [ + 0.029020194564140008, + 0.04729253490319249, + 0.06459559348824401, + 0.07961574115120515, + 0.0885136744204306, + 0.09151979772833038, + 0.08842422046097018, + 0.07861986994705704, + 0.058381495734696906 + ], + "n_valid_labels": 11070, + "n_masked_labels": 30, + "mae_median": 5822.352295080476, + "n_mase_elements": 11070, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 0.9188337503681047, + "wql": 0.7510078807006969 + } + }, + { + "config_id": "electricity__W__short", + "leaderboard_key": "electricity/W/short", + "dataset": "electricity/W", + "term": "short", + "freq": "W-FRI", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.316880865245498, + "wql": 0.06523927951573125 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.610693320997188, + "wql": 0.0762006982656171, + "wsql_by_level": [ + 0.030382087870668584, + 0.05047882972598704, + 0.06691222537497775, + 0.08502932486095087, + 0.09767594055942698, + 0.1009687958270892, + 0.10160965763408675, + 0.09020050861774846, + 0.06254891391961824 + ], + "n_valid_labels": 2952, + "n_masked_labels": 8, + "mae_median": 42062.97362857395, + "n_mase_elements": 2952, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 1.223112404095048, + "wql": 1.168018697190589 + } + }, + { + "config_id": "solar__T__short", + "leaderboard_key": "solar/10T/short", + "dataset": "solar/10T", + "term": "short", + "freq": "10T", + "prediction_length": 48, + "seasonality": 144, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.016018364778558773, + "wql": 12.118563297136966 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.0768679914526028, + "wql": 2.0980338622011754, + "wsql_by_level": [ + 2.3279344347011253, + 2.395769958573886, + 2.330302428370146, + 2.1734882317711928, + 2.017361474592283, + 1.946605124178102, + 1.86774493390364, + 1.8662534285267127, + 1.9568447451934932 + ], + "n_valid_labels": 6576, + "n_masked_labels": 0, + "mae_median": 0.19495638897877768, + "n_mase_elements": 6576, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 4.798741476751341, + "wql": 0.17312562642609955 + } + }, + { + "config_id": "solar__T__medium", + "leaderboard_key": "solar/10T/medium", + "dataset": "solar/10T", + "term": "medium", + "freq": "10T", + "prediction_length": 480, + "seasonality": 144, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.8331425981399365, + "wql": 0.5650432034501303 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7209963741799365, + "wql": 0.3021834109609904, + "wsql_by_level": [ + 0.22530428042469486, + 0.3351012939131825, + 0.37852333025325147, + 0.37783919975001085, + 0.351520413590254, + 0.31883999094885285, + 0.288655316102147, + 0.25429653638493455, + 0.1895703372815857 + ], + "n_valid_labels": 65760, + "n_masked_labels": 0, + "mae_median": 1.6796344015617692, + "n_mase_elements": 65760, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8653937222627, + "wql": 0.5347970015670857 + } + }, + { + "config_id": "solar__T__long", + "leaderboard_key": "solar/10T/long", + "dataset": "solar/10T", + "term": "long", + "freq": "10T", + "prediction_length": 720, + "seasonality": 144, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 2.1421153816960863, + "wql": 0.9032285592107642 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7422519476351619, + "wql": 0.24926612161819875, + "wsql_by_level": [ + 0.1888108329407509, + 0.2702038567415279, + 0.30277297984226, + 0.3062416812479864, + 0.29656088309091244, + 0.2771694649814947, + 0.24565167008718578, + 0.20502776910549525, + 0.15095595652617597 + ], + "n_valid_labels": 98640, + "n_masked_labels": 0, + "mae_median": 1.7425097013454425, + "n_mase_elements": 98640, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.34650418645864955, + "wql": 0.27597236499696826 + } + }, + { + "config_id": "solar__H__short", + "leaderboard_key": "solar/H/short", + "dataset": "solar/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0569321595099215, + "wql": 0.602297355940449 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0082589114235332, + "wql": 0.4372603811873617, + "wsql_by_level": [ + 0.4563607954276551, + 0.5339670970687495, + 0.5370685225269369, + 0.5124674779093751, + 0.4777842787773365, + 0.43844244819083317, + 0.39588677393176014, + 0.3402630992101183, + 0.24310293764349072 + ], + "n_valid_labels": 6576, + "n_masked_labels": 0, + "mae_median": 13.17812377094628, + "n_mase_elements": 6576, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9539485598498989, + "wql": 0.7259875489650913 + } + }, + { + "config_id": "solar__H__medium", + "leaderboard_key": "solar/H/medium", + "dataset": "solar/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.3782698364748944, + "wql": 0.9679824737641872 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.2115296255006223, + "wql": 0.48905996135977325, + "wsql_by_level": [ + 0.5889690871298017, + 0.6446690051212586, + 0.6273194226190016, + 0.5834188948708839, + 0.5269798929028185, + 0.4730992084353555, + 0.4106053175823184, + 0.3302641319760108, + 0.2162146916005099 + ], + "n_valid_labels": 65760, + "n_masked_labels": 0, + "mae_median": 15.79202192028937, + "n_mase_elements": 65760, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8790220851087244, + "wql": 0.5052363804253283 + } + }, + { + "config_id": "solar__H__long", + "leaderboard_key": "solar/H/long", + "dataset": "solar/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0723400769109404, + "wql": 0.9027882643891623 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0535423065039895, + "wql": 0.3869264457323637, + "wsql_by_level": [ + 0.4842083949222997, + 0.5028490541114451, + 0.48702376563115596, + 0.45448264719072307, + 0.41103250860370355, + 0.3820338944278337, + 0.3341341009170586, + 0.26380381032369776, + 0.16276983546335577 + ], + "n_valid_labels": 98640, + "n_masked_labels": 0, + "mae_median": 13.856300272120759, + "n_mase_elements": 98640, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.982470327453301, + "wql": 0.42859046909982035 + } + }, + { + "config_id": "solar__D__short", + "leaderboard_key": "solar/D/short", + "dataset": "solar/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.1670584568457976, + "wql": 0.4714212933677157 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.1576783594745825, + "wql": 0.29619657953850803, + "wsql_by_level": [ + 0.26899104598045337, + 0.36276338195800867, + 0.3924657273286298, + 0.3881313918178199, + 0.3620140073586836, + 0.31905411969325925, + 0.2624037001376636, + 0.1949584022212775, + 0.11498743935077634 + ], + "n_valid_labels": 4110, + "n_masked_labels": 0, + "mae_median": 292.89214956139705, + "n_mase_elements": 4110, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9919626156546035, + "wql": 0.6283054747539166 + } + }, + { + "config_id": "solar__W__short", + "leaderboard_key": "solar/W/short", + "dataset": "solar/W", + "term": "short", + "freq": "W-FRI", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0078578333938706, + "wql": 0.13890951079671932 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0147792759408558, + "wql": 0.11992407338928977, + "wsql_by_level": [ + 0.0582925657107583, + 0.12108538400237173, + 0.14784144355372428, + 0.15532269057947795, + 0.15185128944534718, + 0.1404519393029158, + 0.12505837094253006, + 0.10300845803284196, + 0.0764045189336409 + ], + "n_valid_labels": 1096, + "n_masked_labels": 0, + "mae_median": 932.4789151379662, + "n_mase_elements": 1096, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.0068674790408463, + "wql": 0.8633251438397699 + } + }, + { + "config_id": "hospital__M__short", + "leaderboard_key": "hospital/M/short", + "dataset": "hospital", + "term": "short", + "freq": "M", + "prediction_length": 12, + "seasonality": 12, + "n_variates": 1, + "n_instances": 767, + "domain": "Healthcare", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9326829101839614, + "wql": 0.0633931064425068 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 767, + "instances": 767, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7872260825505015, + "wql": 0.05412738485473903, + "wsql_by_level": [ + 0.030756202468725458, + 0.04621511185724959, + 0.05572484822905285, + 0.06227089905136022, + 0.06620688391429878, + 0.06665974146912793, + 0.06364457610988208, + 0.05562938487180674, + 0.04003881572114762 + ], + "n_valid_labels": 9204, + "n_masked_labels": 0, + "mae_median": 18.381761541008068, + "n_mase_elements": 9204, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8440447165427636, + "wql": 0.8538370793333634 + } + }, + { + "config_id": "covid_deaths__D__short", + "leaderboard_key": "covid_deaths/D/short", + "dataset": "covid_deaths", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 266, + "domain": "Healthcare", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 50.55549046119792, + "wql": 0.12549070850235644 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 266, + "instances": 266, + "fraction": 1.0 + }, + "metrics": { + "mase": 54.22327305956302, + "wql": 0.10725961190330696, + "wsql_by_level": [ + 0.07375549193970489, + 0.11481708528564523, + 0.14287376802068028, + 0.15567544086647694, + 0.15943366183709662, + 0.1381733088208138, + 0.0952906154803942, + 0.04142390043147192, + 0.04389323444747879 + ], + "n_valid_labels": 7980, + "n_masked_labels": 0, + "mae_median": 323.89863447533514, + "n_mase_elements": 6810, + "n_seasonal_error_zero": 39, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.0725496393152427, + "wql": 0.8547215422032051 + } + }, + { + "config_id": "us_births__D__short", + "leaderboard_key": "us_births/D/short", + "dataset": "us_births/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 1, + "domain": "Healthcare", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 2.328105874599355, + "wql": 0.13056664093780335 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6556065328169987, + "wql": 0.030625373915285265, + "wsql_by_level": [ + 0.009151495214441658, + 0.01658730785498564, + 0.028296955252352703, + 0.03739487607153269, + 0.04254696771501079, + 0.043004134224516606, + 0.04101203206941338, + 0.03495761263172031, + 0.022676984203593663 + ], + "n_valid_labels": 30, + "n_masked_labels": 0, + "mae_median": 432.96787109375, + "n_mase_elements": 30, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.28160511941056904, + "wql": 0.2345574160085343 + } + }, + { + "config_id": "us_births__M__short", + "leaderboard_key": "us_births/M/short", + "dataset": "us_births/M", + "term": "short", + "freq": "M", + "prediction_length": 12, + "seasonality": 12, + "n_variates": 1, + "n_instances": 1, + "domain": "Healthcare", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.3023112362005141, + "wql": 0.011101802850788281 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.2704902866806718, + "wql": 0.008260512335614653, + "wsql_by_level": [ + 0.006781703447254318, + 0.008446538915466855, + 0.007926347928414165, + 0.007329981253553782, + 0.008082115380633557, + 0.0076095586701119215, + 0.009302794526526142, + 0.010414783040810548, + 0.008450787857760607 + ], + "n_valid_labels": 12, + "n_masked_labels": 0, + "mae_median": 2537.1875, + "n_mase_elements": 12, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8947410955683553, + "wql": 0.7440694494973956 + } + }, + { + "config_id": "us_births__W__short", + "leaderboard_key": "us_births/W/short", + "dataset": "us_births/W", + "term": "short", + "freq": "W-TUE", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 1, + "n_instances": 1, + "domain": "Healthcare", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 3.858436986096576, + "wql": 0.04221704717157443 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.7130520549129167, + "wql": 0.019068217655565878, + "wsql_by_level": [ + 0.008990260731815105, + 0.01870463122749415, + 0.023244126109224474, + 0.024802131240096583, + 0.025059669912774335, + 0.023955252737669356, + 0.02099754746077702, + 0.016750654906632745, + 0.009109684573609151 + ], + "n_valid_labels": 8, + "n_masked_labels": 0, + "mae_median": 1864.1982421875, + "n_mase_elements": 8, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.44397564637849424, + "wql": 0.45167104127559365 + } + }, + { + "config_id": "saugeenday__D__short", + "leaderboard_key": "saugeen/D/short", + "dataset": "saugeenday/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 3.898466092444523, + "wql": 0.5418638069109889 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 3.274843404029015, + "wql": 0.3293496839479395, + "wsql_by_level": [ + 0.14381457510250115, + 0.257008685370821, + 0.3485844562595073, + 0.4200544355863347, + 0.4634607316657452, + 0.45455297463761807, + 0.4008022740106051, + 0.26631438551624376, + 0.20955463738207913 + ], + "n_valid_labels": 30, + "n_masked_labels": 0, + "mae_median": 14.39818016688029, + "n_mase_elements": 30, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8400338303251812, + "wql": 0.6078089729326418 + } + }, + { + "config_id": "saugeenday__M__short", + "leaderboard_key": "saugeen/M/short", + "dataset": "saugeenday/M", + "term": "short", + "freq": "M", + "prediction_length": 12, + "seasonality": 12, + "n_variates": 1, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.33228103391864, + "wql": 0.2615013833629034 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.549662163685455, + "wql": 0.2982443699666215, + "wsql_by_level": [ + 0.12108868748079718, + 0.2078138985960868, + 0.263359395628196, + 0.30282250448569353, + 0.32763758136669296, + 0.3348358951579393, + 0.355435370360271, + 0.4075960379976135, + 0.36360995862630363 + ], + "n_valid_labels": 12, + "n_masked_labels": 0, + "mae_median": 9.528441031773886, + "n_mase_elements": 12, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.6542086594687837, + "wql": 1.1405078096765835 + } + }, + { + "config_id": "saugeenday__W__short", + "leaderboard_key": "saugeen/W/short", + "dataset": "saugeenday/W", + "term": "short", + "freq": "W-THU", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 1, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.5685710422753978, + "wql": 0.5994091721735982 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7285964574345278, + "wql": 0.24922618055775228, + "wsql_by_level": [ + 0.10899919609098603, + 0.18202641727883884, + 0.2409029005760858, + 0.30418067542972194, + 0.35709220912487893, + 0.3656578465796535, + 0.2894996550577236, + 0.14487795953133906, + 0.24979876535054304 + ], + "n_valid_labels": 8, + "n_masked_labels": 0, + "mae_median": 8.732179760932922, + "n_mase_elements": 8, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.281451926427197, + "wql": 0.41578639788577093 + } + }, + { + "config_id": "temperature_rain_with_missing__D__short", + "leaderboard_key": "temperature_rain/D/short", + "dataset": "temperature_rain_with_missing", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 32072, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 3.2912255413171745, + "wql": 1.099183165150044 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 32072, + "instances": 32072, + "fraction": 1.0 + }, + "metrics": { + "mase": 2.1268124668650867, + "wql": 0.5259197236518761, + "wsql_by_level": [ + 0.17981547840810042, + 0.33841915359009883, + 0.47415025475240086, + 0.5845380198965998, + 0.6647647109248043, + 0.7056027866770972, + 0.700393530483584, + 0.6289289228289506, + 0.45666465530524913 + ], + "n_valid_labels": 961756, + "n_masked_labels": 404, + "mae_median": 6.67886605394644, + "n_mase_elements": 960736, + "n_seasonal_error_zero": 34, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.646206843063669, + "wql": 0.4784641362116253 + } + }, + { + "config_id": "kdd_cup_2018_with_missing__H__short", + "leaderboard_key": "kdd_cup_2018/H/short", + "dataset": "kdd_cup_2018_with_missing/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 270, + "domain": "Nature", + "n_cohorts": 2, + "status": "ok", + "baseline": { + "mase": 0.6811227593500775, + "wql": 0.6266148384878599 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 270, + "instances": 270, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.5312924097741281, + "wql": 0.3776791109004808, + "wsql_by_level": [ + 0.15311938710583473, + 0.2582833003351677, + 0.34775296398874156, + 0.4230923982917297, + 0.4752700467671379, + 0.5020851601505625, + 0.49000822572083824, + 0.4378528423919104, + 0.31164767335240456 + ], + "n_valid_labels": 11685, + "n_masked_labels": 1275, + "mae_median": 12.21561973510094, + "n_mase_elements": 11685, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7800244559161164, + "wql": 0.6027292807363003 + } + }, + { + "config_id": "kdd_cup_2018_with_missing__H__medium", + "leaderboard_key": "kdd_cup_2018/H/medium", + "dataset": "kdd_cup_2018_with_missing/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 1, + "n_instances": 270, + "domain": "Nature", + "n_cohorts": 2, + "status": "ok", + "baseline": { + "mase": 1.2781450805103305, + "wql": 1.049898934007083 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 270, + "instances": 270, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.917299434312702, + "wql": 0.45665335033749405, + "wsql_by_level": [ + 0.17618939285368543, + 0.3235666525892208, + 0.4443333337856219, + 0.5353655324399187, + 0.5936850567196706, + 0.6097239624553842, + 0.5814639825182019, + 0.4975456919866668, + 0.3480065476890761 + ], + "n_valid_labels": 116458, + "n_masked_labels": 13142, + "mae_median": 19.89814805432194, + "n_mase_elements": 116458, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7176802135376118, + "wql": 0.43494981806926314 + } + }, + { + "config_id": "kdd_cup_2018_with_missing__H__long", + "leaderboard_key": "kdd_cup_2018/H/long", + "dataset": "kdd_cup_2018_with_missing/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 1, + "n_instances": 270, + "domain": "Nature", + "n_cohorts": 2, + "status": "ok", + "baseline": { + "mase": 0.981050679806651, + "wql": 1.2362237298155803 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 270, + "instances": 270, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8690473991224387, + "wql": 0.471452873141483, + "wsql_by_level": [ + 0.18649043351205255, + 0.33286859440010147, + 0.4548165167506451, + 0.5481819645324882, + 0.6085847543877736, + 0.6307425398907802, + 0.6077488924600863, + 0.5250153953347191, + 0.3486267670047002 + ], + "n_valid_labels": 175906, + "n_masked_labels": 18494, + "mae_median": 18.560714061378015, + "n_mase_elements": 175906, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8858333386953197, + "wql": 0.381365331995216 + } + }, + { + "config_id": "kdd_cup_2018_with_missing__D__short", + "leaderboard_key": "kdd_cup_2018/D/short", + "dataset": "kdd_cup_2018_with_missing/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 270, + "domain": "Nature", + "n_cohorts": 2, + "status": "ok", + "baseline": { + "mase": 1.2132840958596942, + "wql": 0.8994855622016019 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 270, + "instances": 270, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0518495136974122, + "wql": 0.4172697439856089, + "wsql_by_level": [ + 0.19334218500786907, + 0.3230325844482593, + 0.4185436212153615, + 0.48194710473366115, + 0.5187676337096575, + 0.5309589917952463, + 0.5120603880682578, + 0.4568777266444619, + 0.3198974602477055 + ], + "n_valid_labels": 7581, + "n_masked_labels": 519, + "mae_median": 16.100720754699395, + "n_mase_elements": 7581, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.866944120743712, + "wql": 0.46389821195605374 + } + }, + { + "config_id": "car_parts_with_missing__M__short", + "leaderboard_key": "car_parts/M/short", + "dataset": "car_parts_with_missing", + "term": "short", + "freq": "M", + "prediction_length": 12, + "seasonality": 12, + "n_variates": 1, + "n_instances": 2674, + "domain": "Sales", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.556811831303017, + "wql": 1.6139130745452677 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 2674, + "instances": 2674, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.3838347518092513, + "wql": 1.1119552943558246, + "wsql_by_level": [ + 0.24431539640267785, + 0.5222585677609529, + 0.8052229801233016, + 1.0802284889119016, + 1.3255518094124066, + 1.5265517918967744, + 1.6110707645521753, + 1.5679400063494704, + 1.3244578437927619 + ], + "n_valid_labels": 30108, + "n_masked_labels": 1980, + "mae_median": 0.6272464670087206, + "n_mase_elements": 28068, + "n_seasonal_error_zero": 215, + "n_seasonal_error_nan": 7 + }, + "relative": { + "mase": 0.8888901818346359, + "wql": 0.6889809072704405 + } + }, + { + "config_id": "restaurant__D__short", + "leaderboard_key": "restaurant/D/short", + "dataset": "restaurant", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 806, + "domain": "Sales", + "n_cohorts": 13, + "skipped_series": 1, + "status": "ok", + "baseline": { + "mase": 1.0028179898604987, + "wql": 0.6760963195065456 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 806, + "instances": 806, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7023181007954793, + "wql": 0.26641146596057164, + "wsql_by_level": [ + 0.1355024434152521, + 0.22007524331957348, + 0.27905549040285677, + 0.3177388435818806, + 0.33697780303011243, + 0.3371431887551111, + 0.3161567452866772, + 0.26904629862979995, + 0.18600713722388118 + ], + "n_valid_labels": 21222, + "n_masked_labels": 2958, + "mae_median": 7.207406121316566, + "n_mase_elements": 21222, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7003445369913819, + "wql": 0.3940436566124398 + } + }, + { + "config_id": "hierarchical_sales__D__short", + "leaderboard_key": "hierarchical_sales/D/short", + "dataset": "hierarchical_sales/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 118, + "domain": "Sales", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0956340453936162, + "wql": 1.4587792906606432 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 118, + "instances": 118, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9307717209475461, + "wql": 0.6228424955531506, + "wsql_by_level": [ + 0.22197180215160506, + 0.39419614479475906, + 0.5338228961234476, + 0.6490763569394317, + 0.7400909431673747, + 0.8014676901218083, + 0.8268588480375666, + 0.7923469779419109, + 0.6457508007004514 + ], + "n_valid_labels": 3304, + "n_masked_labels": 236, + "mae_median": 2.902348169073751, + "n_mase_elements": 3304, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8495279284728307, + "wql": 0.426961432439229 + } + }, + { + "config_id": "hierarchical_sales__W__short", + "leaderboard_key": "hierarchical_sales/W/short", + "dataset": "hierarchical_sales/W", + "term": "short", + "freq": "W-WED", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 1, + "n_instances": 118, + "domain": "Sales", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9952062817493519, + "wql": 0.7382990422957836 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 118, + "instances": 118, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8270971878144624, + "wql": 0.41168964950220643, + "wsql_by_level": [ + 0.15067303785998495, + 0.26962541039233096, + 0.3599958309501474, + 0.4309506149436802, + 0.4865547378151122, + 0.5263458824281837, + 0.5463863837434516, + 0.5235225310335966, + 0.41115241635337046 + ], + "n_valid_labels": 944, + "n_masked_labels": 0, + "mae_median": 11.880388460421967, + "n_mase_elements": 944, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8310811567232163, + "wql": 0.5576191027175569 + } + }, + { + "config_id": "LOOP_SEATTLE__T__short", + "leaderboard_key": "loop_seattle/5T/short", + "dataset": "LOOP_SEATTLE/5T", + "term": "short", + "freq": "5T", + "prediction_length": 48, + "seasonality": 288, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.6088421384511257, + "wql": 0.05736115508602545 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.4100877742088887, + "wql": 0.03016167394273772, + "wsql_by_level": [ + 0.019775426835882435, + 0.027625908732218353, + 0.03267356492668807, + 0.03589269083339583, + 0.037407636723235674, + 0.03726331160258559, + 0.03459563434580184, + 0.028577614325819296, + 0.0176432771590124 + ], + "n_valid_labels": 15504, + "n_masked_labels": 0, + "mae_median": 2.4262053022935786, + "n_mase_elements": 15504, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6735535343400154, + "wql": 0.5258205469799863 + } + }, + { + "config_id": "LOOP_SEATTLE__T__medium", + "leaderboard_key": "loop_seattle/5T/medium", + "dataset": "LOOP_SEATTLE/5T", + "term": "medium", + "freq": "5T", + "prediction_length": 480, + "seasonality": 288, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.5924843577520822, + "wql": 0.14109820582939464 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6136283965574653, + "wql": 0.051418051019836736, + "wsql_by_level": [ + 0.04130574351993589, + 0.05457883943275213, + 0.06125084230654833, + 0.06387462756278288, + 0.06285874287866156, + 0.05926389028817826, + 0.052192575582471805, + 0.04152139473076351, + 0.025915802876436283 + ], + "n_valid_labels": 155040, + "n_masked_labels": 0, + "mae_median": 3.818912886798197, + "n_mase_elements": 155040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.38532773874378917, + "wql": 0.3644132164374052 + } + }, + { + "config_id": "LOOP_SEATTLE__T__long", + "leaderboard_key": "loop_seattle/5T/long", + "dataset": "LOOP_SEATTLE/5T", + "term": "long", + "freq": "5T", + "prediction_length": 720, + "seasonality": 288, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.5910237866124803, + "wql": 0.14753926773607257 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6848148419750002, + "wql": 0.05831947931063795, + "wsql_by_level": [ + 0.0460664434167421, + 0.06297450985257669, + 0.07099853725059516, + 0.07350410501370036, + 0.07171334360469651, + 0.06670074300408968, + 0.05821867080832267, + 0.04600390122035608, + 0.028695059624662355 + ], + "n_valid_labels": 232560, + "n_masked_labels": 0, + "mae_median": 4.2186853435089136, + "n_mase_elements": 232560, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.4304240123480932, + "wql": 0.3952810679185657 + } + }, + { + "config_id": "LOOP_SEATTLE__H__short", + "leaderboard_key": "loop_seattle/H/short", + "dataset": "LOOP_SEATTLE/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 2.0101473993616685, + "wql": 0.13665681786039896 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6901326558883611, + "wql": 0.04548339061595022, + "wsql_by_level": [ + 0.037143466611074025, + 0.04717704640728819, + 0.051723534366009266, + 0.05390366118747655, + 0.05377732476408398, + 0.05223150061745391, + 0.047981726498274375, + 0.039678155138131325, + 0.0257340999537603 + ], + "n_valid_labels": 15504, + "n_masked_labels": 0, + "mae_median": 3.2574009315578807, + "n_mase_elements": 15504, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.34332440303010414, + "wql": 0.3328292823444311 + } + }, + { + "config_id": "LOOP_SEATTLE__H__medium", + "leaderboard_key": "loop_seattle/H/medium", + "dataset": "LOOP_SEATTLE/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.1535310881157237, + "wql": 0.14911283164622935 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7398560427198567, + "wql": 0.05356547770808822, + "wsql_by_level": [ + 0.04705050672010442, + 0.06053664467742173, + 0.06502892410930615, + 0.06517306886113829, + 0.0626417708155978, + 0.0582787027234501, + 0.051942687047827986, + 0.0427809225537166, + 0.02865607186423092 + ], + "n_valid_labels": 155040, + "n_masked_labels": 0, + "mae_median": 3.4948349058958708, + "n_mase_elements": 155040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6413837046458807, + "wql": 0.3592278217556252 + } + }, + { + "config_id": "LOOP_SEATTLE__H__long", + "leaderboard_key": "loop_seattle/H/long", + "dataset": "LOOP_SEATTLE/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.2448539713840052, + "wql": 0.17526380961630228 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7349032276582611, + "wql": 0.05274720859762385, + "wsql_by_level": [ + 0.045358772391787254, + 0.05790599056140879, + 0.06241262628712518, + 0.06307780288934084, + 0.06138929518709324, + 0.057840774635963044, + 0.05229231250158975, + 0.043919297157632535, + 0.03052800576667395 + ], + "n_valid_labels": 232560, + "n_masked_labels": 0, + "mae_median": 3.4455863062949743, + "n_mase_elements": 232560, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.59035296071009, + "wql": 0.300958929930264 + } + }, + { + "config_id": "LOOP_SEATTLE__D__short", + "leaderboard_key": "loop_seattle/D/short", + "dataset": "LOOP_SEATTLE/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.1854124643746355, + "wql": 0.09281728785965133 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6242529301373654, + "wql": 0.029830368095654012, + "wsql_by_level": [ + 0.02182609408081076, + 0.030993323572861258, + 0.03536201762964288, + 0.03690361373756848, + 0.03609496034514822, + 0.033819605984196636, + 0.030376622590614764, + 0.02553174196852931, + 0.01756533295151379 + ], + "n_valid_labels": 9690, + "n_masked_labels": 0, + "mae_median": 2.0258955684854767, + "n_mase_elements": 9690, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.5266124230157223, + "wql": 0.3213880601721567 + } + }, + { + "config_id": "SZ_TAXI__T__short", + "leaderboard_key": "sz_taxi/15T/short", + "dataset": "SZ_TAXI/15T", + "term": "short", + "freq": "15T", + "prediction_length": 48, + "seasonality": 96, + "n_variates": 1, + "n_instances": 156, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7251090475210906, + "wql": 0.3023498132057821 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 156, + "instances": 156, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.5257733661893083, + "wql": 0.19868821922245208, + "wsql_by_level": [ + 0.10406894787083448, + 0.16883135911831357, + 0.21243929243517184, + 0.23983623324328335, + 0.25196588507976203, + 0.2495669708883905, + 0.23181656340056453, + 0.19526824407947083, + 0.13440047688627765 + ], + "n_valid_labels": 7488, + "n_masked_labels": 0, + "mae_median": 2.820113259619013, + "n_mase_elements": 7488, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7250955811222526, + "wql": 0.6571468231310699 + } + }, + { + "config_id": "SZ_TAXI__T__medium", + "leaderboard_key": "sz_taxi/15T/medium", + "dataset": "SZ_TAXI/15T", + "term": "medium", + "freq": "15T", + "prediction_length": 480, + "seasonality": 96, + "n_variates": 1, + "n_instances": 156, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.6350051480164337, + "wql": 0.3916041859838231 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 156, + "instances": 156, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.468918679900259, + "wql": 0.1954581814275207, + "wsql_by_level": [ + 0.1018254128599982, + 0.16224345035504564, + 0.20315632031103523, + 0.2293104653388292, + 0.24211475633182547, + 0.24255812783323297, + 0.22946651817956437, + 0.20084398964101874, + 0.1476045919971362 + ], + "n_valid_labels": 74880, + "n_masked_labels": 0, + "mae_median": 2.679549932784008, + "n_mase_elements": 74880, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.738448627330063, + "wql": 0.49912178782377703 + } + }, + { + "config_id": "SZ_TAXI__T__long", + "leaderboard_key": "sz_taxi/15T/long", + "dataset": "SZ_TAXI/15T", + "term": "long", + "freq": "15T", + "prediction_length": 720, + "seasonality": 96, + "n_variates": 1, + "n_instances": 156, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.6084219160390921, + "wql": 0.45522272202116565 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 156, + "instances": 156, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.49324756443776663, + "wql": 0.21475013345616506, + "wsql_by_level": [ + 0.11553973064090531, + 0.18130556929308456, + 0.223648830909525, + 0.24932909493126215, + 0.2598430767624352, + 0.2589773146454886, + 0.24683206384666542, + 0.22357089064576735, + 0.17370462943035195 + ], + "n_valid_labels": 112320, + "n_masked_labels": 0, + "mae_median": 2.8857445457314923, + "n_mase_elements": 112320, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.81069986375388, + "wql": 0.4717473954346686 + } + }, + { + "config_id": "SZ_TAXI__H__short", + "leaderboard_key": "sz_taxi/H/short", + "dataset": "SZ_TAXI/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 156, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.6087142479652129, + "wql": 0.20653078520030457 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 156, + "instances": 156, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.4825621632184014, + "wql": 0.1320673877513155, + "wsql_by_level": [ + 0.07132920293980814, + 0.11103792438214605, + 0.13657128007497965, + 0.15243338031417153, + 0.1599819113833389, + 0.15977271909088384, + 0.1517586384989044, + 0.13702058803749975, + 0.10870084504010707 + ], + "n_valid_labels": 7488, + "n_masked_labels": 0, + "mae_median": 1.7686231205203575, + "n_mase_elements": 7488, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.792756477824352, + "wql": 0.639456183847989 + } + }, + { + "config_id": "M_DENSE__H__short", + "leaderboard_key": "m_dense/H/short", + "dataset": "M_DENSE/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 30, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.8744657675879529, + "wql": 0.18983266370122717 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 30, + "instances": 30, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7171077714283085, + "wql": 0.12795331147034347, + "wsql_by_level": [ + 0.09684109852810456, + 0.13009023404439743, + 0.1489671003253008, + 0.15755181833874912, + 0.15666379384537493, + 0.14784176090011217, + 0.13255021865956312, + 0.10863557072818675, + 0.07243820786330238 + ], + "n_valid_labels": 1440, + "n_masked_labels": 0, + "mae_median": 98.67588784694672, + "n_mase_elements": 1440, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8200524228710674, + "wql": 0.6740321132074824 + } + }, + { + "config_id": "M_DENSE__H__medium", + "leaderboard_key": "m_dense/H/medium", + "dataset": "M_DENSE/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 1, + "n_instances": 30, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.171624112893389, + "wql": 0.3497462745339787 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 30, + "instances": 30, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8730585454020328, + "wql": 0.1485499476141238, + "wsql_by_level": [ + 0.08313873298802207, + 0.12061397895066771, + 0.14603269250990697, + 0.1645730620350064, + 0.17787279808525702, + 0.18415890424568546, + 0.18060358409634772, + 0.16201012721852162, + 0.11794564839769926 + ], + "n_valid_labels": 14400, + "n_masked_labels": 0, + "mae_median": 104.40431004822254, + "n_mase_elements": 14400, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7451694923263124, + "wql": 0.42473632581808046 + } + }, + { + "config_id": "M_DENSE__H__long", + "leaderboard_key": "m_dense/H/long", + "dataset": "M_DENSE/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 1, + "n_instances": 30, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0805183298420056, + "wql": 0.3841191250034235 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 30, + "instances": 30, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.2393760313044384, + "wql": 0.20675854961059267, + "wsql_by_level": [ + 0.09091269628059663, + 0.14622799009856047, + 0.18909004740367644, + 0.22301727044619596, + 0.25044255746752636, + 0.267140720228899, + 0.2692619633194963, + 0.24687418283813228, + 0.1778595184122506 + ], + "n_valid_labels": 21600, + "n_masked_labels": 0, + "mae_median": 146.77575483158782, + "n_mase_elements": 21600, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.1470199043135725, + "wql": 0.5382667411021254 + } + }, + { + "config_id": "M_DENSE__D__short", + "leaderboard_key": "m_dense/D/short", + "dataset": "M_DENSE/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 30, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.007688577826318, + "wql": 0.1992117768924222 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 30, + "instances": 30, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0941390085189, + "wql": 0.10288553857114299, + "wsql_by_level": [ + 0.06974452684877164, + 0.10910323082866043, + 0.1297976201547912, + 0.13682476427872187, + 0.13288868069432144, + 0.12351034951208739, + 0.10453712329710114, + 0.07302505277136141, + 0.04653849875447044 + ], + "n_valid_labels": 900, + "n_masked_labels": 0, + "mae_median": 77.88147758483886, + "n_mase_elements": 900, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.0857908212863383, + "wql": 0.5164631337368321 + } + }, + { + "config_id": "ett1__T__short", + "leaderboard_key": "ett1/15T/short", + "dataset": "ett1/15T", + "term": "short", + "freq": "15T", + "prediction_length": 48, + "seasonality": 96, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.2054822899524387, + "wql": 0.48104386522982623 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8214261572001123, + "wql": 0.29481597465298226, + "wsql_by_level": [ + 0.18964325761931364, + 0.2745391775694242, + 0.33084893693699724, + 0.36825268857911847, + 0.3778633939334866, + 0.3724945877607387, + 0.33683819371376206, + 0.26032997463098745, + 0.14253356113301166 + ], + "n_valid_labels": 336, + "n_masked_labels": 0, + "mae_median": 1.38100973162095, + "n_mase_elements": 336, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6814087308014463, + "wql": 0.6128671332543225 + } + }, + { + "config_id": "ett1__T__medium", + "leaderboard_key": "ett1/15T/medium", + "dataset": "ett1/15T", + "term": "medium", + "freq": "15T", + "prediction_length": 480, + "seasonality": 96, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7745679584044315, + "wql": 0.4386794376669185 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0092417207126376, + "wql": 0.38839740748493645, + "wsql_by_level": [ + 0.17732621509879212, + 0.3168352937923244, + 0.44548078085103726, + 0.5166194347129901, + 0.534737766382693, + 0.5070514587101248, + 0.44292045740215885, + 0.34306120547048496, + 0.21154405494382228 + ], + "n_valid_labels": 3360, + "n_masked_labels": 0, + "mae_median": 1.7437321115212745, + "n_mase_elements": 3360, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.3029737542869984, + "wql": 0.8853786481322147 + } + }, + { + "config_id": "ett1__T__long", + "leaderboard_key": "ett1/15T/long", + "dataset": "ett1/15T", + "term": "long", + "freq": "15T", + "prediction_length": 720, + "seasonality": 96, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.327073089604087, + "wql": 0.5796800252115644 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.3670236333869228, + "wql": 0.497031202258102, + "wsql_by_level": [ + 0.30944584694169114, + 0.4501347866493699, + 0.5637887045079086, + 0.652018877446299, + 0.6772446123321872, + 0.6322512821436593, + 0.5397144030958743, + 0.4087324194896231, + 0.23994988771630513 + ], + "n_valid_labels": 5040, + "n_masked_labels": 0, + "mae_median": 2.3218302230505894, + "n_mase_elements": 5040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.030104252807021, + "wql": 0.8574233726213039 + } + }, + { + "config_id": "ett1__H__short", + "leaderboard_key": "ett1/H/short", + "dataset": "ett1/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0441605493380515, + "wql": 0.5044116168241106 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7739004248050079, + "wql": 0.35659571309492666, + "wsql_by_level": [ + 0.20216769520853173, + 0.31144442325319316, + 0.38891049126631405, + 0.4345283813603701, + 0.4512722546329992, + 0.4432013287649109, + 0.40793938333569946, + 0.34334075018650373, + 0.2265567098458175 + ], + "n_valid_labels": 336, + "n_masked_labels": 0, + "mae_median": 5.453582210200174, + "n_mase_elements": 336, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7411699525476463, + "wql": 0.7069538075671884 + } + }, + { + "config_id": "ett1__H__medium", + "leaderboard_key": "ett1/H/medium", + "dataset": "ett1/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.2235872159229322, + "wql": 0.5499353323396741 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.4603189147712816, + "wql": 0.4580147504063036, + "wsql_by_level": [ + 0.3039929179294283, + 0.477990125145042, + 0.5528350233162905, + 0.5760975642599011, + 0.5680262573087668, + 0.5317231753205748, + 0.46965532392701004, + 0.3828923222547146, + 0.2589200441950038 + ], + "n_valid_labels": 3360, + "n_masked_labels": 0, + "mae_median": 8.691971091808712, + "n_mase_elements": 3360, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.1934734980618333, + "wql": 0.8328520163592714 + } + }, + { + "config_id": "ett1__H__long", + "leaderboard_key": "ett1/H/long", + "dataset": "ett1/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.4320631719624162, + "wql": 0.5783242328839591 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.4813000687695845, + "wql": 0.4355347526355679, + "wsql_by_level": [ + 0.35153983036240993, + 0.5093147697747166, + 0.5677214210045067, + 0.5730641472102553, + 0.5465693496620524, + 0.4861307811106581, + 0.40326922048855346, + 0.299518875952423, + 0.18268437815453525 + ], + "n_valid_labels": 5040, + "n_masked_labels": 0, + "mae_median": 9.202950997992108, + "n_mase_elements": 5040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.0343817910907498, + "wql": 0.7530978780945499 + } + }, + { + "config_id": "ett1__D__short", + "leaderboard_key": "ett1/D/short", + "dataset": "ett1/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.8181967261759215, + "wql": 0.48528320354978605 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.7125469309965207, + "wql": 0.3259106077562237, + "wsql_by_level": [ + 0.16137053555741737, + 0.27899883815019505, + 0.3727382848101659, + 0.4277406778187874, + 0.44214283502937, + 0.4183139806362204, + 0.36320278374700166, + 0.2868340624617836, + 0.1818534715950715 + ], + "n_valid_labels": 210, + "n_masked_labels": 0, + "mae_median": 140.34686893735613, + "n_mase_elements": 210, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9418930890929463, + "wql": 0.6715884773514276 + } + }, + { + "config_id": "ett1__W__short", + "leaderboard_key": "ett1/W/short", + "dataset": "ett1/W", + "term": "short", + "freq": "W-THU", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.2444126904903803, + "wql": 0.25814356436755426 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.106185120067513, + "wql": 0.21001219538078106, + "wsql_by_level": [ + 0.13727284278957352, + 0.19954607945320055, + 0.22569645937067387, + 0.22249008755102534, + 0.23718526468115747, + 0.2505679563626385, + 0.25300388208202, + 0.2214736424548148, + 0.1428735436819256 + ], + "n_valid_labels": 56, + "n_masked_labels": 0, + "mae_median": 591.9523811340332, + "n_mase_elements": 56, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8889214394234468, + "wql": 0.8135480576295058 + } + }, + { + "config_id": "ett2__T__short", + "leaderboard_key": "ett2/15T/short", + "dataset": "ett2/15T", + "term": "short", + "freq": "15T", + "prediction_length": 48, + "seasonality": 96, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7618250880337474, + "wql": 0.093929612604377 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0937252174522372, + "wql": 0.13560977560954587, + "wsql_by_level": [ + 0.06501174800755238, + 0.10575940326178622, + 0.13561929780139106, + 0.15724727497272703, + 0.1705630957317838, + 0.1751596146031689, + 0.16786222395571773, + 0.14515434078592698, + 0.09811098136585845 + ], + "n_valid_labels": 336, + "n_masked_labels": 0, + "mae_median": 2.7216534854045937, + "n_mase_elements": 336, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.4356644781482797, + "wql": 1.4437382615504009 + } + }, + { + "config_id": "ett2__T__medium", + "leaderboard_key": "ett2/15T/medium", + "dataset": "ett2/15T", + "term": "medium", + "freq": "15T", + "prediction_length": 480, + "seasonality": 96, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9027189688220486, + "wql": 0.13649095157039726 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7970795977761963, + "wql": 0.09696997614964563, + "wsql_by_level": [ + 0.0639106037547191, + 0.09695447629296962, + 0.11465592237105614, + 0.12265742950078251, + 0.1233926652937331, + 0.11737984533539476, + 0.10301051639375607, + 0.08019802601630922, + 0.05057030038809003 + ], + "n_valid_labels": 3360, + "n_masked_labels": 0, + "mae_median": 1.8778263026183204, + "n_mase_elements": 3360, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8829764581288235, + "wql": 0.7104498505868494 + } + }, + { + "config_id": "ett2__T__long", + "leaderboard_key": "ett2/15T/long", + "dataset": "ett2/15T", + "term": "long", + "freq": "15T", + "prediction_length": 720, + "seasonality": 96, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0565955316162643, + "wql": 0.16755935574924186 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0250159293188936, + "wql": 0.12940225184502274, + "wsql_by_level": [ + 0.090808697619562, + 0.1299287094539597, + 0.1531489520157394, + 0.1647845768613013, + 0.16695492342090965, + 0.15670400062046014, + 0.13385394560407404, + 0.103014127062811, + 0.06542233394638784 + ], + "n_valid_labels": 5040, + "n_masked_labels": 0, + "mae_median": 2.518012447257772, + "n_mase_elements": 5040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9701119289714735, + "wql": 0.772277091102436 + } + }, + { + "config_id": "ett2__H__short", + "leaderboard_key": "ett2/H/short", + "dataset": "ett2/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9915624508458626, + "wql": 0.11931409133707109 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7155280441704037, + "wql": 0.07751669029467836, + "wsql_by_level": [ + 0.05470239750834528, + 0.08164794098877232, + 0.09651385260535378, + 0.10140197349954858, + 0.09823493392483736, + 0.08895847717512205, + 0.07336028126027827, + 0.05876049067064031, + 0.04406986501920734 + ], + "n_valid_labels": 336, + "n_masked_labels": 0, + "mae_median": 6.022995185284388, + "n_mase_elements": 336, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7216167207219426, + "wql": 0.6496859627056791 + } + }, + { + "config_id": "ett2__H__medium", + "leaderboard_key": "ett2/H/medium", + "dataset": "ett2/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 2.649073318865916, + "wql": 0.345818716053239 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 2.5477968659334382, + "wql": 0.24405136521038256, + "wsql_by_level": [ + 0.10371340315367442, + 0.17364442741282998, + 0.23387087083806785, + 0.28662610040688397, + 0.3247429175272094, + 0.3373321140447869, + 0.31653528272118536, + 0.25975903186884697, + 0.16023813891995847 + ], + "n_valid_labels": 3360, + "n_masked_labels": 0, + "mae_median": 18.470140754734523, + "n_mase_elements": 3360, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9617691015906518, + "wql": 0.7057205231564468 + } + }, + { + "config_id": "ett2__H__long", + "leaderboard_key": "ett2/H/long", + "dataset": "ett2/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 3.171779953228176, + "wql": 0.3702966971424018 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 3.2001497701375214, + "wql": 0.34593853984107104, + "wsql_by_level": [ + 0.24289980690194787, + 0.3580784821370337, + 0.41845827694334353, + 0.4435272214406277, + 0.44380086517604317, + 0.4140482762459489, + 0.3591835505689428, + 0.27537867132510613, + 0.15807170783064525 + ], + "n_valid_labels": 5040, + "n_masked_labels": 0, + "mae_median": 25.042252096550314, + "n_mase_elements": 5040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.0089444467547224, + "wql": 0.9342198904572903 + } + }, + { + "config_id": "ett2__D__short", + "leaderboard_key": "ett2/D/short", + "dataset": "ett2/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 4.704440132303346, + "wql": 0.31867490583739955 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 4.71552821818059, + "wql": 0.34490967865065597, + "wsql_by_level": [ + 0.33779561806587444, + 0.4161227473111691, + 0.44213557684850474, + 0.4406654201667481, + 0.41776173572790376, + 0.37455821421630564, + 0.3137142848405675, + 0.23325474889699307, + 0.12817876178183726 + ], + "n_valid_labels": 210, + "n_masked_labels": 0, + "mae_median": 564.9172366823469, + "n_mase_elements": 210, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.0023569405849395, + "wql": 1.0823245644156319 + } + }, + { + "config_id": "ett2__W__short", + "leaderboard_key": "ett2/W/short", + "dataset": "ett2/W", + "term": "short", + "freq": "W-THU", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.7680609986327813, + "wql": 0.21133928538207686 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.6738706679621287, + "wql": 0.19017075054529542, + "wsql_by_level": [ + 0.13067139775709152, + 0.19259728231839807, + 0.216638197774929, + 0.23213797128671024, + 0.23524253626707287, + 0.2177096327973739, + 0.1914430751630538, + 0.16732884346085994, + 0.1277678180821696 + ], + "n_valid_labels": 56, + "n_masked_labels": 0, + "mae_median": 2289.5015216554916, + "n_mase_elements": 56, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9467267640972292, + "wql": 0.899836252410378 + } + }, + { + "config_id": "jena_weather__T__short", + "leaderboard_key": "jena_weather/10T/short", + "dataset": "jena_weather/10T", + "term": "short", + "freq": "10T", + "prediction_length": 48, + "seasonality": 144, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7621672521709891, + "wql": 0.1366740261223883 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.4381615959698976, + "wql": 0.019378536241707597, + "wsql_by_level": [ + 0.008430787784852633, + 0.013484815565352748, + 0.017143760832462076, + 0.019775180201104907, + 0.021885751029669595, + 0.023168885962048413, + 0.023626554343826343, + 0.023797191736826644, + 0.023093898719225018 + ], + "n_valid_labels": 1008, + "n_masked_labels": 0, + "mae_median": 3.4488528321306813, + "n_mase_elements": 1008, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.5748890348172527, + "wql": 0.1417865324634147 + } + }, + { + "config_id": "jena_weather__T__medium", + "leaderboard_key": "jena_weather/10T/medium", + "dataset": "jena_weather/10T", + "term": "medium", + "freq": "10T", + "prediction_length": 480, + "seasonality": 144, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9778443284819783, + "wql": 0.22790411536869984 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8894216693398508, + "wql": 0.08439517716357126, + "wsql_by_level": [ + 0.025305702016835924, + 0.051488522994540944, + 0.07513546079250924, + 0.09228389649053131, + 0.10264442070485165, + 0.10977331112911427, + 0.11033524471767135, + 0.10490910031746958, + 0.08768093530861712 + ], + "n_valid_labels": 10080, + "n_masked_labels": 0, + "mae_median": 17.35870784630778, + "n_mase_elements": 10080, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.909573889660539, + "wql": 0.37031001843489314 + } + }, + { + "config_id": "jena_weather__T__long", + "leaderboard_key": "jena_weather/10T/long", + "dataset": "jena_weather/10T", + "term": "long", + "freq": "10T", + "prediction_length": 720, + "seasonality": 144, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9055523182794231, + "wql": 0.2428907683297211 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7511029666546598, + "wql": 0.08054454386843068, + "wsql_by_level": [ + 0.032302425950407554, + 0.05750610532180266, + 0.0762362807461036, + 0.0887185907876682, + 0.09581930659978298, + 0.10022605862045157, + 0.09947892008601508, + 0.09424275951638172, + 0.0803704471872628 + ], + "n_valid_labels": 15120, + "n_masked_labels": 0, + "mae_median": 16.380706850535447, + "n_mase_elements": 15120, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8294418240591315, + "wql": 0.33160809042809114 + } + }, + { + "config_id": "jena_weather__H__short", + "leaderboard_key": "jena_weather/H/short", + "dataset": "jena_weather/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7591774901189448, + "wql": 0.1835169108215369 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.5430859405505467, + "wql": 0.07869415077987135, + "wsql_by_level": [ + 0.06408211852381007, + 0.08914069071390114, + 0.0958327621245457, + 0.09481569845659486, + 0.08936097811288386, + 0.08388528757691857, + 0.07697753425621111, + 0.06623871206044776, + 0.04791357519352917 + ], + "n_valid_labels": 1008, + "n_masked_labels": 0, + "mae_median": 14.93206286219233, + "n_mase_elements": 1008, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7153609631727336, + "wql": 0.42881143992445675 + } + }, + { + "config_id": "jena_weather__H__medium", + "leaderboard_key": "jena_weather/H/medium", + "dataset": "jena_weather/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0707310989927863, + "wql": 0.3640989806826866 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8591114697317427, + "wql": 0.1074129764482036, + "wsql_by_level": [ + 0.07529235040440486, + 0.10791603142718266, + 0.12124674554078534, + 0.12420421551660182, + 0.12111475897423574, + 0.1173236794833584, + 0.11272627477977365, + 0.10339475087664092, + 0.083497981030849 + ], + "n_valid_labels": 10080, + "n_masked_labels": 0, + "mae_median": 20.861429818234747, + "n_mase_elements": 10080, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8023596872640483, + "wql": 0.295010373956016 + } + }, + { + "config_id": "jena_weather__H__long", + "leaderboard_key": "jena_weather/H/long", + "dataset": "jena_weather/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.4925574952113163, + "wql": 0.44387827099252614 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0418108063208493, + "wql": 0.14017419121413696, + "wsql_by_level": [ + 0.11995268931398419, + 0.16183171204027713, + 0.17325900073340783, + 0.17019602421177357, + 0.15906121942317014, + 0.14447089520745499, + 0.13019818525641164, + 0.11278051298151359, + 0.08981748175923963 + ], + "n_valid_labels": 15120, + "n_masked_labels": 0, + "mae_median": 27.72517703107148, + "n_mase_elements": 15120, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6980038019730354, + "wql": 0.31579421741168573 + } + }, + { + "config_id": "jena_weather__D__short", + "leaderboard_key": "jena_weather/D/short", + "dataset": "jena_weather/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.8578467510262653, + "wql": 0.23138296558762514 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.5183736333335538, + "wql": 0.1214588203316676, + "wsql_by_level": [ + 0.04964905481972034, + 0.10500498083261146, + 0.13648173722423493, + 0.1516969490464145, + 0.1569547750272559, + 0.1539005523149912, + 0.14126224053573744, + 0.11827886150763245, + 0.07990023167641004 + ], + "n_valid_labels": 630, + "n_masked_labels": 0, + "mae_median": 27.358012966481166, + "n_mase_elements": 630, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8172760387770476, + "wql": 0.5249255061763436 + } + }, + { + "config_id": "bitbrains_fast_storage__T__short", + "leaderboard_key": "bitbrains_fast_storage/5T/short", + "dataset": "bitbrains_fast_storage/5T", + "term": "short", + "freq": "5T", + "prediction_length": 48, + "seasonality": 288, + "n_variates": 2, + "n_instances": 1250, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.9726733005020567, + "wql": 1.8982594024982165 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1250, + "instances": 1250, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0733563034184141, + "wql": 0.4664786946849542, + "wsql_by_level": [ + 0.1813831751610276, + 0.32363781373972933, + 0.4263731000502317, + 0.507291421640025, + 0.5650406954713425, + 0.600793132161074, + 0.6006618659593367, + 0.5572856864713103, + 0.43584136151051006 + ], + "n_valid_labels": 107692, + "n_masked_labels": 12308, + "mae_median": 165.99265924437958, + "n_mase_elements": 104420, + "n_seasonal_error_zero": 56, + "n_seasonal_error_nan": 52 + }, + "relative": { + "mase": 0.5441125518073564, + "wql": 0.24574022605711415 + } + }, + { + "config_id": "bitbrains_fast_storage__T__medium", + "leaderboard_key": "bitbrains_fast_storage/5T/medium", + "dataset": "bitbrains_fast_storage/5T", + "term": "medium", + "freq": "5T", + "prediction_length": 480, + "seasonality": 288, + "n_variates": 2, + "n_instances": 1250, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.332305698225943, + "wql": 0.7965658755181099 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1250, + "instances": 1250, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.132444124016862, + "wql": 0.6953436862182868, + "wsql_by_level": [ + 0.6291875688174969, + 0.8991746960969769, + 0.9457048891556443, + 0.906920584118667, + 0.8313286116020017, + 0.7241456237345772, + 0.5956889800681762, + 0.4468206176494713, + 0.2791216047215697 + ], + "n_valid_labels": 1151890, + "n_masked_labels": 48110, + "mae_median": 516.7167950984378, + "n_mase_elements": 1112970, + "n_seasonal_error_zero": 58, + "n_seasonal_error_nan": 66 + }, + "relative": { + "mase": 0.849988201300039, + "wql": 0.8729267818132616 + } + }, + { + "config_id": "bitbrains_fast_storage__T__long", + "leaderboard_key": "bitbrains_fast_storage/5T/long", + "dataset": "bitbrains_fast_storage/5T", + "term": "long", + "freq": "5T", + "prediction_length": 720, + "seasonality": 288, + "n_variates": 2, + "n_instances": 1250, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.5068539886984111, + "wql": 0.6979053733746295 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1250, + "instances": 1250, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.2731790221049613, + "wql": 0.5227876126290419, + "wsql_by_level": [ + 0.41992945929689895, + 0.5928086156574576, + 0.6569666797370685, + 0.6673966975017179, + 0.6416817246647006, + 0.5845724361971084, + 0.4994110271222578, + 0.38674274650422563, + 0.25557912697994095 + ], + "n_valid_labels": 1732080, + "n_masked_labels": 67920, + "mae_median": 468.43801571387763, + "n_mase_elements": 1677544, + "n_seasonal_error_zero": 58, + "n_seasonal_error_nan": 66 + }, + "relative": { + "mase": 0.8449252758754062, + "wql": 0.7490809392986492 + } + }, + { + "config_id": "bitbrains_fast_storage__H__short", + "leaderboard_key": "bitbrains_fast_storage/H/short", + "dataset": "bitbrains_fast_storage/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 2, + "n_instances": 1250, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.5571822067903167, + "wql": 0.6231221387021137 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1250, + "instances": 1250, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.3796956392658872, + "wql": 0.4898528983605696, + "wsql_by_level": [ + 0.34667873723717507, + 0.5631315162902976, + 0.6427564183041367, + 0.6514254799139336, + 0.6110948561742231, + 0.5383784494145999, + 0.45333302108146517, + 0.3618924405074848, + 0.2399851663218103 + ], + "n_valid_labels": 116442, + "n_masked_labels": 3558, + "mae_median": 431.43603918025406, + "n_mase_elements": 112610, + "n_seasonal_error_zero": 58, + "n_seasonal_error_nan": 66 + }, + "relative": { + "mase": 0.886020680977169, + "wql": 0.7861266161733116 + } + }, + { + "config_id": "bitbrains_rnd__T__short", + "leaderboard_key": "bitbrains_rnd/5T/short", + "dataset": "bitbrains_rnd/5T", + "term": "short", + "freq": "5T", + "prediction_length": 48, + "seasonality": 288, + "n_variates": 2, + "n_instances": 500, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.8369702659182979, + "wql": 0.895586111036325 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 500, + "instances": 500, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.5638963495490843, + "wql": 0.24095593379450392, + "wsql_by_level": [ + 0.1244706874071127, + 0.19430405924365926, + 0.24116225646420253, + 0.27289092143262234, + 0.2825260890349805, + 0.2810789043768654, + 0.2726327775024443, + 0.26864592208419014, + 0.23089178660445808 + ], + "n_valid_labels": 46368, + "n_masked_labels": 1632, + "mae_median": 151.399121694687, + "n_mase_elements": 45888, + "n_seasonal_error_zero": 10, + "n_seasonal_error_nan": 34 + }, + "relative": { + "mase": 0.6737352239513487, + "wql": 0.2690483146457937 + } + }, + { + "config_id": "bitbrains_rnd__T__medium", + "leaderboard_key": "bitbrains_rnd/5T/medium", + "dataset": "bitbrains_rnd/5T", + "term": "medium", + "freq": "5T", + "prediction_length": 480, + "seasonality": 288, + "n_variates": 2, + "n_instances": 500, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9740075110165132, + "wql": 1.1044931903333195 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 500, + "instances": 500, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8293333644557189, + "wql": 0.8865781219586293, + "wsql_by_level": [ + 0.39596339038727335, + 0.7331672153659989, + 0.9050397303665062, + 0.9989345689205774, + 1.05629281360851, + 1.0618553351251925, + 1.0291596175414257, + 0.9549505078033226, + 0.8438399185088562 + ], + "n_valid_labels": 455110, + "n_masked_labels": 24890, + "mae_median": 317.2242831203783, + "n_mase_elements": 441864, + "n_seasonal_error_zero": 10, + "n_seasonal_error_nan": 54 + }, + "relative": { + "mase": 0.8514650606648746, + "wql": 0.8027013020252965 + } + }, + { + "config_id": "bitbrains_rnd__T__long", + "leaderboard_key": "bitbrains_rnd/5T/long", + "dataset": "bitbrains_rnd/5T", + "term": "long", + "freq": "5T", + "prediction_length": 720, + "seasonality": 288, + "n_variates": 2, + "n_instances": 500, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.1660081104198932, + "wql": 0.9977535818816068 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 500, + "instances": 500, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9747111545586368, + "wql": 0.7566179447667375, + "wsql_by_level": [ + 0.26184261660932495, + 0.439716934573811, + 0.5803021227674623, + 0.7052075763344462, + 0.8190757380436183, + 0.9224470181044289, + 1.0098884171665383, + 1.068062370273175, + 1.0030187090278315 + ], + "n_valid_labels": 684238, + "n_masked_labels": 35762, + "mae_median": 267.93910511134567, + "n_mase_elements": 657984, + "n_seasonal_error_zero": 12, + "n_seasonal_error_nan": 64 + }, + "relative": { + "mase": 0.8359385718231684, + "wql": 0.7583214518156625 + } + }, + { + "config_id": "bitbrains_rnd__H__short", + "leaderboard_key": "bitbrains_rnd/H/short", + "dataset": "bitbrains_rnd/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 2, + "n_instances": 500, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.1175347302132743, + "wql": 0.9314629241561541 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 500, + "instances": 500, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9578091049077081, + "wql": 0.6441955067781584, + "wsql_by_level": [ + 0.2294601005693081, + 0.40249984767414015, + 0.5751254460558541, + 0.7119989333423781, + 0.8088529471659669, + 0.8575265161624389, + 0.8491088827704104, + 0.7576878577669285, + 0.605499029496 + ], + "n_valid_labels": 46216, + "n_masked_labels": 1784, + "mae_median": 262.0172815598249, + "n_mase_elements": 44928, + "n_seasonal_error_zero": 10, + "n_seasonal_error_nan": 54 + }, + "relative": { + "mase": 0.8570732336210405, + "wql": 0.6915954356012166 + } + }, + { + "config_id": "bizitobs_application__S__short", + "leaderboard_key": "bizitobs_application/10S/short", + "dataset": "bizitobs_application", + "term": "short", + "freq": "10S", + "prediction_length": 60, + "seasonality": 360, + "n_variates": 2, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.3935671590031806, + "wql": 0.01840457246049758 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.5202718912184385, + "wql": 0.009290537526640129, + "wsql_by_level": [ + 0.005575283686072811, + 0.00894297207967492, + 0.011108786925524673, + 0.012214488389544611, + 0.012469049353906216, + 0.01178263049906962, + 0.010047293149567831, + 0.0073895921179448635, + 0.004084741538455596 + ], + "n_valid_labels": 120, + "n_masked_labels": 0, + "mae_median": 322.64164037704467, + "n_mase_elements": 120, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.37333822618967955, + "wql": 0.5047950745164419 + } + }, + { + "config_id": "bizitobs_application__S__medium", + "leaderboard_key": "bizitobs_application/10S/medium", + "dataset": "bizitobs_application", + "term": "medium", + "freq": "10S", + "prediction_length": 600, + "seasonality": 360, + "n_variates": 2, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9183336447716528, + "wql": 0.013742470259025481 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.62466068855112, + "wql": 0.008638922960656433, + "wsql_by_level": [ + 0.0051677318327932875, + 0.007981927951224398, + 0.00974759323478173, + 0.010758086945534423, + 0.011061170134747578, + 0.010693610294953769, + 0.009682889331165727, + 0.007820802565535238, + 0.004836494355171747 + ], + "n_valid_labels": 1200, + "n_masked_labels": 0, + "mae_median": 264.8056029001872, + "n_mase_elements": 1200, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6802110454163359, + "wql": 0.6286295547907589 + } + }, + { + "config_id": "bizitobs_application__S__long", + "leaderboard_key": "bizitobs_application/10S/long", + "dataset": "bizitobs_application", + "term": "long", + "freq": "10S", + "prediction_length": 900, + "seasonality": 360, + "n_variates": 2, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7487259254586917, + "wql": 0.012942679940654697 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7101638905675902, + "wql": 0.009778754338471328, + "wsql_by_level": [ + 0.006099153313198013, + 0.009426377919490341, + 0.011314495102680384, + 0.012202480096223354, + 0.012331557460749343, + 0.011886288142863959, + 0.01072417436299317, + 0.008644083346284932, + 0.005380179301758445 + ], + "n_valid_labels": 1800, + "n_masked_labels": 0, + "mae_median": 300.46296051449247, + "n_mase_elements": 1800, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9484964610147869, + "wql": 0.7555432401410891 + } + }, + { + "config_id": "bizitobs_service__S__short", + "leaderboard_key": "bizitobs_service/10S/short", + "dataset": "bizitobs_service", + "term": "short", + "freq": "10S", + "prediction_length": 60, + "seasonality": 360, + "n_variates": 2, + "n_instances": 21, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0559084960397855, + "wql": 0.025515037101462117 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 21, + "instances": 21, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.47435684438223463, + "wql": 0.008370135174398585, + "wsql_by_level": [ + 0.005315289334050302, + 0.008287962523349091, + 0.01013913629931956, + 0.011043941546694497, + 0.011145812337680147, + 0.01051081130818862, + 0.009048180196209399, + 0.006518721495292408, + 0.003321361528803235 + ], + "n_valid_labels": 2520, + "n_masked_labels": 0, + "mae_median": 14.945177835533544, + "n_mase_elements": 2520, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.4492404845318731, + "wql": 0.32804714886810576 + } + }, + { + "config_id": "bizitobs_service__S__medium", + "leaderboard_key": "bizitobs_service/10S/medium", + "dataset": "bizitobs_service", + "term": "medium", + "freq": "10S", + "prediction_length": 600, + "seasonality": 360, + "n_variates": 2, + "n_instances": 21, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9546641394188339, + "wql": 0.023513421962609537 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 21, + "instances": 21, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6599193557554229, + "wql": 0.009664911463417407, + "wsql_by_level": [ + 0.006014162567455485, + 0.00909288407661523, + 0.010917629077656072, + 0.011878477893632243, + 0.012174510363240808, + 0.011851581314791169, + 0.010813065064178132, + 0.008747005912617758, + 0.005494886900569755 + ], + "n_valid_labels": 25200, + "n_masked_labels": 0, + "mae_median": 15.35585357448648, + "n_mase_elements": 25200, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6912581383408397, + "wql": 0.411038064931013 + } + }, + { + "config_id": "bizitobs_service__S__long", + "leaderboard_key": "bizitobs_service/10S/long", + "dataset": "bizitobs_service", + "term": "long", + "freq": "10S", + "prediction_length": 900, + "seasonality": 360, + "n_variates": 2, + "n_instances": 21, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.8316933390369606, + "wql": 0.023678985220657325 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 21, + "instances": 21, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7393852580758685, + "wql": 0.010689527670922645, + "wsql_by_level": [ + 0.006673217505636585, + 0.010173124753461637, + 0.012262735502481071, + 0.013372797380252254, + 0.013633500655135921, + 0.013107414805926781, + 0.011743275871610422, + 0.009389168462323206, + 0.00585051410147592 + ], + "n_valid_labels": 37800, + "n_masked_labels": 0, + "mae_median": 17.42136596428265, + "n_mase_elements": 37800, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8890118789841722, + "wql": 0.4514352102216441 + } + }, + { + "config_id": "bizitobs_l2c__T__short", + "leaderboard_key": "bizitobs_l2c/5T/short", + "dataset": "bizitobs_l2c/5T", + "term": "short", + "freq": "5T", + "prediction_length": 48, + "seasonality": 288, + "n_variates": 7, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7721410982041648, + "wql": 0.22094461659341424 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.20633118806437892, + "wql": 0.06408249411872445, + "wsql_by_level": [ + 0.04205801394530982, + 0.0637837420891585, + 0.07623612010509721, + 0.0816878955772927, + 0.08175377700781443, + 0.07813063255083155, + 0.06966959490002636, + 0.05322809546386391, + 0.030194575429125625 + ], + "n_valid_labels": 336, + "n_masked_labels": 0, + "mae_median": 2.1001937105542137, + "n_mase_elements": 336, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.26721953868828013, + "wql": 0.29003872149847426 + } + }, + { + "config_id": "bizitobs_l2c__T__medium", + "leaderboard_key": "bizitobs_l2c/5T/medium", + "dataset": "bizitobs_l2c/5T", + "term": "medium", + "freq": "5T", + "prediction_length": 480, + "seasonality": 288, + "n_variates": 7, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.4416925389331963, + "wql": 0.47091183801289255 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.4593158210278488, + "wql": 0.1554462185536017, + "wsql_by_level": [ + 0.1110934259091066, + 0.15111239764176193, + 0.17190418886325473, + 0.18106010265440975, + 0.1858072523915044, + 0.18593204255166218, + 0.17442839921436817, + 0.14392057544148734, + 0.09375758231486 + ], + "n_valid_labels": 3360, + "n_masked_labels": 0, + "mae_median": 4.135256530060655, + "n_mase_elements": 3360, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.31859485197012044, + "wql": 0.33009622185235 + } + }, + { + "config_id": "bizitobs_l2c__T__long", + "leaderboard_key": "bizitobs_l2c/5T/long", + "dataset": "bizitobs_l2c/5T", + "term": "long", + "freq": "5T", + "prediction_length": 720, + "seasonality": 288, + "n_variates": 7, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.6820288964143004, + "wql": 0.6755692567838184 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7718811837465762, + "wql": 0.2874656917261269, + "wsql_by_level": [ + 0.13283937189657996, + 0.21909563793914275, + 0.2780583365062052, + 0.3233183355083034, + 0.3736240037204542, + 0.3953303525426985, + 0.3866549918946802, + 0.3176506883976825, + 0.1606195071293959 + ], + "n_valid_labels": 5040, + "n_masked_labels": 0, + "mae_median": 6.834930745587305, + "n_mase_elements": 5040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.45889888419399316, + "wql": 0.4255162425458263 + } + }, + { + "config_id": "bizitobs_l2c__H__short", + "leaderboard_key": "bizitobs_l2c/H/short", + "dataset": "bizitobs_l2c/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.5845833438972332, + "wql": 0.5573763030242874 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6123703286169557, + "wql": 0.19231964280001757, + "wsql_by_level": [ + 0.12593656545198934, + 0.20290163019535087, + 0.24560915106280296, + 0.2673270324282995, + 0.2694550414884239, + 0.23957459937922854, + 0.18486711636295036, + 0.11596986301729496, + 0.07923578581381767 + ], + "n_valid_labels": 336, + "n_masked_labels": 0, + "mae_median": 5.637605591344514, + "n_mase_elements": 336, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.38645510883059647, + "wql": 0.34504452693181203 + } + }, + { + "config_id": "bizitobs_l2c__H__medium", + "leaderboard_key": "bizitobs_l2c/H/medium", + "dataset": "bizitobs_l2c/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.6159633796006725, + "wql": 1.1167911109559348 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.357827537750225, + "wql": 0.2119879699997818, + "wsql_by_level": [ + 0.118904504820854, + 0.18401550046915024, + 0.22357298480345097, + 0.2475530922237098, + 0.2578268521285683, + 0.25757312045125574, + 0.24455322407862878, + 0.21493150946756062, + 0.1589609415548577 + ], + "n_valid_labels": 3360, + "n_masked_labels": 0, + "mae_median": 3.5288128207764764, + "n_mase_elements": 3360, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.221432949698804, + "wql": 0.18981881922244834 + } + }, + { + "config_id": "bizitobs_l2c__H__long", + "leaderboard_key": "bizitobs_l2c/H/long", + "dataset": "bizitobs_l2c/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.280223980485366, + "wql": 1.0134048622912797 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.4310978516579819, + "wql": 0.2183701901837192, + "wsql_by_level": [ + 0.11633293763845164, + 0.18612598938319813, + 0.2309354531452401, + 0.25937289916652106, + 0.2709764128387919, + 0.26841170398609154, + 0.251855281212445, + 0.22060402135316803, + 0.16071701292956514 + ], + "n_valid_labels": 5040, + "n_masked_labels": 0, + "mae_median": 4.094134366747707, + "n_mase_elements": 5040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.3367362728938585, + "wql": 0.21548168783203822 + } + } + ], + "checkpoint_sha256": "0ff54447074e0271d2e331c7d3e6e9e0fdd73353e4d8cef0175ff627385f71c3" +} \ No newline at end of file diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/model_manifest.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/model_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..821ceeb4ed71824c39e89b269637998e2a0846ae --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/model_manifest.json @@ -0,0 +1,1202 @@ +{ + "name": "direct-seasonal-foundation", + "contract": "timeseries-forecast/v1", + "parameters": 36849984, + "pretrained_assets": [], + "sources_used": [ + "gifteval_pretrain/BEIJING_SUBWAY_30MIN", + "gifteval_pretrain/HZMETRO", + "gifteval_pretrain/LOS_LOOP", + "gifteval_pretrain/PEMS03", + "gifteval_pretrain/PEMS04", + "gifteval_pretrain/PEMS07", + "gifteval_pretrain/PEMS08", + "gifteval_pretrain/PEMS_BAY", + "gifteval_pretrain/Q-TRAFFIC", + "gifteval_pretrain/SHMETRO", + "gifteval_pretrain/alibaba_cluster_trace_2018", + "gifteval_pretrain/australian_electricity_demand", + "gifteval_pretrain/azure_vm_traces_2017", + "gifteval_pretrain/bdg-2_bear", + "gifteval_pretrain/bdg-2_fox", + "gifteval_pretrain/bdg-2_panther", + "gifteval_pretrain/bdg-2_rat", + "gifteval_pretrain/bitcoin_with_missing", + "gifteval_pretrain/borealis", + "gifteval_pretrain/borg_cluster_data_2011", + "gifteval_pretrain/buildings_900k", + "gifteval_pretrain/bull", + "gifteval_pretrain/cdc_fluview_ilinet", + "gifteval_pretrain/cdc_fluview_who_nrevss", + "gifteval_pretrain/china_air_quality", + "gifteval_pretrain/cif_2016_12", + "gifteval_pretrain/cif_2016_6", + "gifteval_pretrain/cmip6_2000", + "gifteval_pretrain/cmip6_2005", + "gifteval_pretrain/cmip6_2010", + "gifteval_pretrain/cockatoo", + "gifteval_pretrain/covid19_energy", + "gifteval_pretrain/covid_mobility", + "gifteval_pretrain/elecdemand", + "gifteval_pretrain/elf", + "gifteval_pretrain/era5_2010", + "gifteval_pretrain/era5_2011", + "gifteval_pretrain/era5_2012", + "gifteval_pretrain/era5_2013", + "gifteval_pretrain/era5_2014", + "gifteval_pretrain/era5_2015", + "gifteval_pretrain/era5_2016", + "gifteval_pretrain/era5_2017", + "gifteval_pretrain/era5_2018", + "gifteval_pretrain/extended_web_traffic_with_missing", + "gifteval_pretrain/favorita_sales", + "gifteval_pretrain/favorita_transactions", + "gifteval_pretrain/gfc12_load", + "gifteval_pretrain/gfc14_load", + "gifteval_pretrain/gfc17_load", + "gifteval_pretrain/godaddy", + "gifteval_pretrain/hog", + "gifteval_pretrain/ideal", + "gifteval_pretrain/kaggle_web_traffic_weekly", + "gifteval_pretrain/kdd2022", + "gifteval_pretrain/largest_2017", + "gifteval_pretrain/largest_2018", + "gifteval_pretrain/largest_2019", + "gifteval_pretrain/largest_2020", + "gifteval_pretrain/largest_2021", + "gifteval_pretrain/lcl", + "gifteval_pretrain/london_smart_meters_with_missing", + "gifteval_pretrain/m1_monthly", + "gifteval_pretrain/m1_quarterly", + "gifteval_pretrain/m1_yearly", + "gifteval_pretrain/m5", + "gifteval_pretrain/monash_m3_monthly", + "gifteval_pretrain/monash_m3_other", + "gifteval_pretrain/monash_m3_quarterly", + "gifteval_pretrain/nn5_daily_with_missing", + "gifteval_pretrain/nn5_weekly", + "gifteval_pretrain/oikolab_weather", + "gifteval_pretrain/pdb", + "gifteval_pretrain/project_tycho", + "gifteval_pretrain/residential_load_power", + "gifteval_pretrain/residential_pv_power", + "gifteval_pretrain/rideshare_with_missing", + "gifteval_pretrain/sceaux", + "gifteval_pretrain/smart", + "gifteval_pretrain/solar_power", + "gifteval_pretrain/spain", + "gifteval_pretrain/subseasonal", + "gifteval_pretrain/subseasonal_precip", + "gifteval_pretrain/sunspot_with_missing", + "gifteval_pretrain/taxi_30min", + "gifteval_pretrain/tourism_quarterly", + "gifteval_pretrain/tourism_yearly", + "gifteval_pretrain/traffic_hourly", + "gifteval_pretrain/traffic_weekly", + "gifteval_pretrain/uber_tlc_daily", + "gifteval_pretrain/uber_tlc_hourly", + "gifteval_pretrain/vehicle_trips_with_missing", + "gifteval_pretrain/wiki-rolling_nips", + "gifteval_pretrain/wind_farms_with_missing", + "gifteval_pretrain/wind_power", + "synthetic:both original and sign-reflected orientations of each sampled allowed or locally generated window; paired quantile loss, seed 197", + "synthetic:both original and sign-reflected orientations of each sampled window, seed 197", + "synthetic:independent sign reflection of sampled allowed-corpus and locally generated windows; seeds 43,47,59,79,89,197", + "synthetic:own Fourier/trend/AR/intermittent/changepoint generator at weekly periods52,1, replacing a Bernoulli1/11 share of the original synthetic rows with unchanged total synthetic fraction; independent seed 1000200", + "synthetic:own Fourier/trend/intermittent generator with AR time constant log-uniform from 1 to 10000 steps and zero initial state; seed 79", + "synthetic:own direct_v1 Fourier seasons, damped trends, AR noise, changepoints and intermittent demand; seeds 23,43,47,59,79,89,197,503", + "synthetic:own random requested-horizon prefixes, half of rows retain the full horizon and half use a patch-rounded prefix between one-quarter and the full horizon; independent seed 300200", + "synthetic:own stationary Gaussian residuals generated by FFT, equal Matern0.5/1.5/2.5 and RBF spectral families, length scale log-uniform1to10000, theoretical unit marginal variance, FFT size next power of two at least4times window; replacing half of original synthetic residuals with all other generator components unchanged; independent seed 1100200" + ], + "weights_sha256": "23b775110747f72747a342fb2282366c2a7d7ae74bfab2137d4c6e38df99dc0a", + "config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true + }, + "training_lineage": [ + { + "checkpoint": "long_seasonal_transfer3k.pt", + "sha256": "23b775110747f72747a342fb2282366c2a7d7ae74bfab2137d4c6e38df99dc0a", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true + }, + "conversion": { + "method": "matched training delta after zero extension of new seasonal query/head parameters", + "formula": "extend_zero(base) + candidate - extend_zero(control)", + "coefficient": 1.0, + "new_parameters_from_candidate": [ + "long_head.bias", + "long_head.weight", + "long_query.weight" + ], + "parent_hashes": { + "/workspace/research/spectral_add_delta6k.pt": "c3dfc433d51355228fc13d04913db1a7edf83030c33283b150bdcc50f5ae6ea2", + "/workspace/research/runs/long_seasonal/ema003000.pt": "92e575ca3cb053d9bdf75a010d83ded0025fe97c906fb9930c74dc1a28e1e892", + "/workspace/research/runs/overflow_control/ema003000.pt": "2084f1888f8d9e5afe2c740769ea2b4167086cdd62dfb4014bc3a338c00d4c12" + }, + "base_extension_forward_bitwise_equal": true, + "check_seed": 571, + "seconds": 2.1952822851017118, + "optimizer_updates": 0, + "validation_data_read": false + }, + "parents": [ + "spectral_add_delta6k.pt", + "runs/long_seasonal/ema003000.pt", + "runs/overflow_control/ema003000.pt" + ] + }, + { + "checkpoint": "spectral_add_delta6k.pt", + "sha256": "c3dfc433d51355228fc13d04913db1a7edf83030c33283b150bdcc50f5ae6ea2", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/weekly_slow_ar_delta6k.pt": "c8adf9cadf97dac5e120d8d4d2c8c025bffa2e8b55d8664bf900cce55d00a70b", + "/workspace/research/runs/spectral_synth/ema006000.pt": "683f3824d3c1f605d17bb08d3eef127a54c67eca3867cfbcf1158710a55c4b24", + "/workspace/research/runs/overflow_control/ema006000.pt": "b19875c52ed5024383fb69ccc48cb07a5629ad8011abf134c7dcfcdc50fae2af" + }, + "seconds": 1.4204325219616294 + }, + "parents": [ + "weekly_slow_ar_delta6k.pt", + "runs/spectral_synth/ema006000.pt", + "runs/overflow_control/ema006000.pt" + ] + }, + { + "checkpoint": "runs/long_seasonal/ema003000.pt", + "sha256": "92e575ca3cb053d9bdf75a010d83ded0025fe97c906fb9930c74dc1a28e1e892", + "step": 3000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null, + "teacher_coefficient": null + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true + }, + "parents": [ + "long_seasonal_initial.pt", + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "runs/overflow_control/ema003000.pt", + "sha256": "2084f1888f8d9e5afe2c740769ea2b4167086cdd62dfb4014bc3a338c00d4c12", + "step": 3000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "weekly_slow_ar_delta6k.pt", + "sha256": "c8adf9cadf97dac5e120d8d4d2c8c025bffa2e8b55d8664bf900cce55d00a70b", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/postloss_slow_ar_delta6k.pt": "0ae7875b49b99a44c295dc2b8243327aeacadc25b2354988abb2c37250359a49", + "/workspace/research/runs/weekly_synth/ema006000.pt": "de053e5baf9641e9245519990d6e5193fc91392cb76e72ceffee1ce63f578fca", + "/workspace/research/runs/overflow_control/ema006000.pt": "b19875c52ed5024383fb69ccc48cb07a5629ad8011abf134c7dcfcdc50fae2af" + }, + "seconds": 2.0751679679378867 + }, + "parents": [ + "postloss_slow_ar_delta6k.pt", + "runs/weekly_synth/ema006000.pt", + "runs/overflow_control/ema006000.pt" + ] + }, + { + "checkpoint": "runs/spectral_synth/ema006000.pt", + "sha256": "683f3824d3c1f605d17bb08d3eef127a54c67eca3867cfbcf1158710a55c4b24", + "step": 6000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null, + "teacher_coefficient": null, + "spectral_synthetic_seed": 1100200, + "spectral_replacement_probability": 0.5, + "spectral_length_scale": [ + 1, + 10000 + ], + "spectral_families": [ + "Matern0.5", + "Matern1.5", + "Matern2.5", + "RBF" + ] + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt", + "runs/confidence_query/ema006000.pt", + "runs/horizon_jitter/ema012000.pt", + "runs/large_corpus_control/ema012000.pt" + ] + }, + { + "checkpoint": "runs/overflow_control/ema006000.pt", + "sha256": "b19875c52ed5024383fb69ccc48cb07a5629ad8011abf134c7dcfcdc50fae2af", + "step": 6000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "long_seasonal_initial.pt", + "sha256": "470ef98d69d00b17defbf41c70a92b22574154cdb6e0317993bccf113e4af93b", + "step": 0, + "seed": 503, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "long_seasonal_features": true + }, + "conversion": { + "method": "zero-initialized sixteen-cycle centered seasonal query/head additions", + "parent_sha256": "22c08571978be31ba57368eb983089a40a44d56d4ae5e17da41afd2a761a258c", + "initial_function_bitwise_equal": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "horizon_delta12k.pt", + "sha256": "22c08571978be31ba57368eb983089a40a44d56d4ae5e17da41afd2a761a258c", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/runs/confidence_query/ema006000.pt": "0bad97e8994aac49ea173443db0a4fa8d72d33f9eb9e2660f06de75f7f1403eb", + "/workspace/research/runs/horizon_jitter/ema012000.pt": "830179d763916a1065fc615d2c5e22f4a3b5b19390dde707ab0f057e13cadff6", + "/workspace/research/runs/large_corpus_control/ema012000.pt": "7f9ba5e01ac59c51a3b63d3067b442e23e15d0abc51ddbcccdd04d6083ae4add" + }, + "seconds": 1.2663014469435439 + }, + "parents": [ + "runs/confidence_query/ema006000.pt", + "runs/horizon_jitter/ema012000.pt", + "runs/large_corpus_control/ema012000.pt" + ] + }, + { + "checkpoint": "postloss_slow_ar_delta6k.pt", + "sha256": "0ae7875b49b99a44c295dc2b8243327aeacadc25b2354988abb2c37250359a49", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/runs/postloss/ema003000.pt": "82c785d40998e155a20290c9965c346c26cd397fa0f3cf36278377ad2aed5c7d", + "/workspace/research/runs/long_memory_synth_recovery/ema006000.pt": "fea5b5290a3a9be5618eaeaf67e918e4f677d5be908d562040ce4bdfeb549bd9", + "/workspace/research/runs/partial_targets/ema006000.pt": "67562486b099a350da53c3caa5ff0932fe7fecdfe72c1879b064b2a9bb173dfb" + }, + "seconds": 1.0092943429481238 + }, + "parents": [ + "runs/postloss/ema003000.pt", + "runs/long_memory_synth_recovery/ema006000.pt", + "runs/partial_targets/ema006000.pt" + ] + }, + { + "checkpoint": "runs/weekly_synth/ema006000.pt", + "sha256": "de053e5baf9641e9245519990d6e5193fc91392cb76e72ceffee1ce63f578fca", + "step": 6000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true, + "weekly_synthetic_seed": 1000200, + "weekly_replacement_probability": 0.09090909090909091, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "runs/confidence_query/ema006000.pt", + "sha256": "0bad97e8994aac49ea173443db0a4fa8d72d33f9eb9e2660f06de75f7f1403eb", + "step": 6000, + "seed": 89, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 0.0002, + "steps": 6000 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true + }, + "parents": [ + "runs/recency_features/ema024000.pt" + ] + }, + { + "checkpoint": "runs/horizon_jitter/ema012000.pt", + "sha256": "830179d763916a1065fc615d2c5e22f4a3b5b19390dde707ab0f057e13cadff6", + "step": 12000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "partial_target_lengths": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/large_corpus_control/ema012000.pt", + "sha256": "7f9ba5e01ac59c51a3b63d3067b442e23e15d0abc51ddbcccdd04d6083ae4add", + "step": 12000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/postloss/ema003000.pt", + "sha256": "82c785d40998e155a20290c9965c346c26cd397fa0f3cf36278377ad2aed5c7d", + "step": 3000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "fixed_postprocessing_loss": true, + "normalization_overflow_fallback": true + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "runs/long_memory_synth_recovery/ema006000.pt", + "sha256": "fea5b5290a3a9be5618eaeaf67e918e4f677d5be908d562040ce4bdfeb549bd9", + "step": 6000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "context": null, + "sample_context": 4096, + "synthetic_ar_time_constants": [ + 1, + 10000 + ] + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "partial_target_lengths": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/partial_targets/ema006000.pt", + "sha256": "67562486b099a350da53c3caa5ff0932fe7fecdfe72c1879b064b2a9bb173dfb", + "step": 6000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "partial_target_lengths": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/recency_features/ema024000.pt", + "sha256": "1530fbb577a87ca4eb39da83d6fee9b8ee5bc924202e021e3a7b56493112f564", + "step": 24000, + "seed": 59, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/patch16_trial/ema006000.pt" + ] + }, + { + "checkpoint": "runs/recency_features/ema012000.pt", + "sha256": "8ccb6870a025e1097331a3a288b1183741a413f3460fbf3352d0c589c6a4394c", + "step": 12000, + "seed": 59, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/patch16_trial/ema006000.pt" + ] + }, + { + "checkpoint": "runs/patch16_trial/ema006000.pt", + "sha256": "0ff54447074e0271d2e331c7d3e6e9e0fdd73353e4d8cef0175ff627385f71c3", + "step": 6000, + "seed": 47, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024 + }, + "parents": [ + "patch16_init.pt" + ] + }, + { + "checkpoint": "patch16_init.pt", + "sha256": "d69531bfde5bf801e7f36c515bf15fd0cae0bd84f7d1479d35f4a7b67f26b508", + "step": 6000, + "seed": 43, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024 + }, + "conversion": { + "from_checkpoint": "/run-state/workspace/research/runs/large_sign/ema006000.pt", + "from_sha256": "96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547", + "method": "fold input/query halves by summation; retain first 16 output rows; preserve physical positional units" + }, + "parents": [ + "runs/large_sign/ema006000.pt" + ] + }, + { + "checkpoint": "runs/large_sign/ema006000.pt", + "sha256": "96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547", + "step": 6000, + "seed": 43, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 32, + "max_context": 4096, + "max_horizon": 1024 + }, + "parents": [ + "runs/direct_large/step024000.pt" + ] + }, + { + "checkpoint": "runs/direct_large/step024000.pt", + "sha256": "b7e4f38aebcd2cf38ce484edaad8d19851317fb3b8df485e2faa0d0423cbcb48", + "step": 24000, + "seed": 23, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 128, + "lr": 0.0002, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 32, + "max_context": 4096, + "max_horizon": 1024 + }, + "initialization": "random initialization in this workspace" + } + ], + "symmetric_averaging": true, + "seasonal_gate": { + "variance_ratio_threshold": 0.25, + "maximum_weight": 0.98, + "cycles_averaged": 4, + "template_mode": "aligned", + "amplitude_ratio_clip": [ + 0.5, + 2.0 + ], + "latest_cycle_minimum_coverage": 0.75, + "variance_noise_correction": "mean squared seasonal differences / 2" + }, + "continuity": { + "decay_steps": 24, + "variance_ratio_threshold": 0.5, + "maximum_weight": 0.95, + "lookback": 512, + "slope_median_differences": 8 + }, + "notes": "All training lineage originates from random initialization here, using only the declared corpus and locally generated series. Validation was used only for selection and diagnostics. Context transformations are fixed formulas; there is no inference-time fitting or parameter adaptation.", + "runtime_code_sha256": { + "model.py": "3eaa4aed0a1c62b80d94be6c3084b10a594e9fce17444eac17ca3f1b0b5c549e", + "seasonal.py": "b946e63048196ab5ea8b249137d48c80d8510943caccd0f180e4fb86d9b24b37", + "ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "infer.sh": "5fe66b4fe9a4787285d830cfd96975701e97286a75ba7c3687bd8891475edf68", + "zero_mass.py": "f079d509009bcda409b80eb64467c869b838cfbab11b2bd4c660c2875b6642fe", + "continuity.py": "dbb08d2229ad80ad00f638b0b9f2f6ca13c663e0fd6730058e5fee8ff54545d5", + "predict.py": "9bde896945a2cd8f892e7eeb6328ed2dfda09293532f3a4a64d929c9943614ef" + }, + "checkpoint_composition": { + "method": "matched training delta after zero extension of new seasonal query/head parameters", + "formula": "extend_zero(base) + candidate - extend_zero(control)", + "coefficient": 1.0, + "new_parameters_from_candidate": [ + "long_head.bias", + "long_head.weight", + "long_query.weight" + ], + "parent_hashes": { + "/workspace/research/spectral_add_delta6k.pt": "c3dfc433d51355228fc13d04913db1a7edf83030c33283b150bdcc50f5ae6ea2", + "/workspace/research/runs/long_seasonal/ema003000.pt": "92e575ca3cb053d9bdf75a010d83ded0025fe97c906fb9930c74dc1a28e1e892", + "/workspace/research/runs/overflow_control/ema003000.pt": "2084f1888f8d9e5afe2c740769ea2b4167086cdd62dfb4014bc3a338c00d4c12" + }, + "base_extension_forward_bitwise_equal": true, + "check_seed": 571, + "seconds": 2.1952822851017118, + "optimizer_updates": 0, + "validation_data_read": false + }, + "normalization_overflow_fallback": { + "trigger": "nonfinite float32 context mean or scale", + "arithmetic": "float64 context statistics on affected rows; original arithmetic on ordinary rows", + "inference_fitting": false + }, + "trend_summary": { + "fixed_averaging_width": 128, + "matches_all_pretraining_context_widths": true, + "independent_of_batch_padding": true + }, + "zero_mass_projection": { + "threshold_in_context_standard_deviations": 0.4, + "nonnegative_context_required": true, + "minimum_exact_zeros": 4, + "minimum_zero_fraction": 0.1, + "context_cap": 4096 + }, + "recency_features": { + "query_projection_parameters": 32768, + "latest_vs_four_cycle_level": true, + "amplitude_ratio_clip": [ + 0.5, + 2.0 + ], + "minimum_observed_cycles": 3 + }, + "long_seasonal_features": { + "cycles": [ + 4, + 16 + ], + "each_cycle_centered": true, + "minimum_total_cycles": 8, + "minimum_recent_cycles": 2, + "query_features": [ + "centered16-minus4 phase mean", + "observed16-cycle fraction" + ], + "median_shift": "sum of two learned tanh gates times template differences", + "same_shift_all_quantiles": true, + "maximum_context": 4096, + "parameters_fixed_at_inference": true + }, + "confidence_features": { + "query_projection_parameters": 3072, + "backbone_frozen_during_projection_training": true, + "training_objective": "weighted quantile and median loss after averaging both sign orientations", + "statistics": [ + "mean absolute difference", + "root mean square difference" + ], + "lags": "one and the two frequency-derived periods", + "lookback": "512 for lag one; eight cycles for seasonal lags", + "minimum_valid_pairs": 8, + "insufficient_pair_defaults": [ + 1, + 1.4142135623730951 + ], + "statistic_clip": 10, + "transform": "log1p", + "stage_scope": "Frozen-backbone details refer to projection introduction; subsequent updates are recorded in training_lineage.training_settings." + }, + "partial_target_training": { + "available_horizon": "last finite training-label position rounded up to the patch boundary", + "decoder_future_key_mask": true, + "per_row_horizon_metadata": true, + "inference_uses_requested_horizon_only": true + }, + "training_provenance_code_sha256": { + "confidence_query/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "confidence_query/model.py": "b4f11ba2018e2b50879cdc33acf0138301548971508b58035a7c96a29aaa6f2d", + "confidence_query/train.py": "fc8a7555a5a6b0a6f91e80ac8cc9cbbfddaa2b26468c57f49dfb17671b22ce93", + "direct_large/data.py": "6e6db217936f8dd79380d2ceff3eaa8598a44f1b60b17acae7bfde2363116847", + "direct_large/evaluate.py": "eaea99e8cd44c9f7c70a45fa9abf51354ae5449dbad273fcb55e48ad02652223", + "direct_large/model.py": "146d93a3f95b13bda8b1b437bc36621b91356cf946e94f62999f89e7fb348071", + "direct_large/pack.py": "3bcc4ce9eb3361ad741ceebd7efce7a2fb86fb49543f52c72aabd0e3e8cd17ce", + "direct_large/predict.py": "930a9f18f9f5da47c03859698c9d2f5567d1e1c73fd61edac1ed20b3a6f9bb50", + "direct_large/publish.py": "3c167f33e8571731c26f1cb70168eda54ef9cb4c76423dfd374240b75ca5f106", + "direct_large/record.py": "b3b00b0ed14bc3af00c7b1ad97195238ecb8f06e96bc41f0c07913bc3f6ed949", + "direct_large/train.py": "b9ad6b2adddeaf12961b529d6535dd33f6d044a31979b5c9e49dceafbadd3ac0", + "direct_large/ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "direct_large/validation_subset.py": "8d3eb9d3f3aa124368761ef402ff066935c0be31a62b25b8551a45dcb922e28d", + "full_paired/check.py": "90ac1c78846439d51ab8acd62a19bd536c7c394bd02e94f6d5ff17c0af8bd116", + "full_paired/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "full_paired/model.py": "c27748fa4b1186b513f76eca26052753b8dcd1794994e5989addaf371ca70f2e", + "horizon_jitter/data.py": "5044cf648323420095ed6058d29f837c07ff5559b606df8b00cc8d1e95c8b58e", + "horizon_jitter/model.py": "186bb282236f23cc665a012194d26e58f51004c680393352ec053f5308f1240f", + "horizon_jitter/train.py": "4e9cbca1293f18f7eea2c72dba127815c0934a13c86e8f6cc881a749676d41a6", + "large_corpus/data.py": "27c078cb0ed085717a364f556b5ff976fd803d5af37612cf3a03a0a3ca12a678", + "large_corpus/model.py": "e3a1bc01e89a0d6d750ede2cc969272ad01e1ca580b174af7dee00db029f1cf7", + "large_corpus/train.py": "3baca16c3945e6ef241ccbc9c13644539e3c265f71095cbbaa61a3d338e4fafe", + "large_sign/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "large_sign/evaluate.py": "eaea99e8cd44c9f7c70a45fa9abf51354ae5449dbad273fcb55e48ad02652223", + "large_sign/model.py": "3fff6445a1982a1b3c92f06a9b5f1bb627dda6a291b0b2364bcfb1a6457830d7", + "large_sign/pack.py": "3bcc4ce9eb3361ad741ceebd7efce7a2fb86fb49543f52c72aabd0e3e8cd17ce", + "large_sign/predict.py": "930a9f18f9f5da47c03859698c9d2f5567d1e1c73fd61edac1ed20b3a6f9bb50", + "large_sign/publish.py": "3c167f33e8571731c26f1cb70168eda54ef9cb4c76423dfd374240b75ca5f106", + "large_sign/record.py": "b3b00b0ed14bc3af00c7b1ad97195238ecb8f06e96bc41f0c07913bc3f6ed949", + "large_sign/train.py": "a597f40ab87cce04e96dc654d12e56cdf40ffd87f00034d8bc4d56dff4eb7c68", + "large_sign/ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "large_sign/validation_subset.py": "8d3eb9d3f3aa124368761ef402ff066935c0be31a62b25b8551a45dcb922e28d", + "long_memory_synth/data.py": "2955ec414de97f7ec91c8863873b7ae50ebe8f0ccb7fe48c41599e69da88ec34", + "long_memory_synth/model.py": "186bb282236f23cc665a012194d26e58f51004c680393352ec053f5308f1240f", + "long_memory_synth/train.py": "75918ac02d30ad8289632bc8a3ce1386c949fd670522799af59536d4cab0b9e9", + "long_seasonal/check.py": "e55fe780892204889e210d1591ae3f0b964d72ec1916b9b5e768b938aba28fc1", + "long_seasonal/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "long_seasonal/launch.py": "68c56b8abde125eb8de866807f8deb946c30e4c52866bc0cafcab82198b58def", + "long_seasonal/long_features.py": "270d84ff1208085f65856e8c489998e6248af5c5ea1c3c47b5161f7d6b621b13", + "long_seasonal/model.py": "3eaa4aed0a1c62b80d94be6c3084b10a594e9fce17444eac17ca3f1b0b5c549e", + "long_seasonal/transfer.py": "301df5a793988edbe50b3384c5777d8679161142943578bc7723a552ed4f3d04", + "overflow_control/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "overflow_control/model.py": "44eeb23c037e91b8f67e432615ce46540a7ac4242919785f9c4218de23121499", + "partial_delta/merge.py": "63984a0f46f7d48817037f5bf5a1c9319e45a9b1924cde62c667ac49ce47532e", + "partial_targets/data.py": "27c078cb0ed085717a364f556b5ff976fd803d5af37612cf3a03a0a3ca12a678", + "partial_targets/model.py": "186bb282236f23cc665a012194d26e58f51004c680393352ec053f5308f1240f", + "partial_targets/train.py": "3baca16c3945e6ef241ccbc9c13644539e3c265f71095cbbaa61a3d338e4fafe", + "patch16/convert.py": "11e1d30100ab25311020ac1f4ab8227ec66156836df5de613300867977091c45", + "patch16/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "patch16/evaluate.py": "eaea99e8cd44c9f7c70a45fa9abf51354ae5449dbad273fcb55e48ad02652223", + "patch16/model.py": "8031c597b354eb2cf464140bee40c3ec8dff86c775b5c55c5ce910302b443582", + "patch16/pack.py": "3bcc4ce9eb3361ad741ceebd7efce7a2fb86fb49543f52c72aabd0e3e8cd17ce", + "patch16/predict.py": "930a9f18f9f5da47c03859698c9d2f5567d1e1c73fd61edac1ed20b3a6f9bb50", + "patch16/publish.py": "3c167f33e8571731c26f1cb70168eda54ef9cb4c76423dfd374240b75ca5f106", + "patch16/record.py": "b3b00b0ed14bc3af00c7b1ad97195238ecb8f06e96bc41f0c07913bc3f6ed949", + "patch16/train.py": "3156710f76111a31447cbe638ee27fe2811d060917aa083aab0b5134d98accf8", + "patch16/ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "patch16/validation_subset.py": "8d3eb9d3f3aa124368761ef402ff066935c0be31a62b25b8551a45dcb922e28d", + "postloss/check_numerical_fix.py": "527dffcd94ec1a02b214dd300261d189b06c386f0b8c4d4df3320098f5fc0e68", + "postloss/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "postloss/diagnose_nonfinite.py": "82d10c5751ea1d21ecd36cd5eb54c00aabcaf78a8562b259551d028d452be47b", + "postloss/gpu_check.py": "c0a7e23d9f74cdab4fa04e1a4b9f89c64bb58f5e24228aa5e0f2cf554fef2d1f", + "postloss/launch_completion.py": "ef584b22259e3bc741b16ef876a6120bfcee08e2b9237a7990ed560a0dbf77ae", + "postloss/model.py": "d4b76fb1a63789e091b114dd947abe30be3e47c2e2e9d41cecb3e3353af86ac5", + "postloss/model_before_numerical_fix.py": "1ad846ac7adc16298b9643a79f4ee1b94f4db82fa716c6db77a2fcbb2160c261", + "postloss/restart.py": "5baa9a0947a0d30f7773113c05bd1f53b8ed1817aeaa2365078b06df9ce2fbca", + "postloss/torch_post.py": "0762fc5d330a4039798a81788e4adb8bfe206aba2aa29a1b53ecad0bd3bff217", + "recency_features/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "recency_features/model.py": "e3a1bc01e89a0d6d750ede2cc969272ad01e1ca580b174af7dee00db029f1cf7", + "recency_features/train.py": "a654b9a27b6c27141e1d4e517ab28fcae3f2c23d061742fa2f6c01e3d23c8a00", + "recovery/capacity_curves.py": "2bdc6635705b70a868e115cd13eb529563acacf6f47c71f250a50dce8e943be4", + "recovery/exposure_audit.py": "54c194a626b8876ece84686b39b22360155c9fada7248a393ca9b7d6ee38002b", + "recovery/relaunch_20261022b.py": "f90ddd77928a793c8e151ba74cfa9cc84c8aefad0c0d943a833c74bc07b79313", + "recovery/relaunch_20261023.py": "a4c40c5674b0d05cfe9bb1fffe907f02dec16c53cbddb8b86efbba1b96649097", + "recovery/schedules.py": "7748fd6b2bbbe64037472faf7e6583d03cf339138d2f3c07b1bac9e65bf2d4f5", + "recovery/snapshot.py": "0f241a7e139e47ffff7efea40572205fd84c12efe6fb3c2dccd87c50d678a6c3", + "recovery/train.py": "63bee736565af670877b4cd7c75015fab06a18c66bbe132b0bb3faff5ebd80c7", + "spectral_synth/check.py": "c308c87af0a6756fafefa460751cc370ed44ee98f3f52364b1ed6879a3c4e110", + "spectral_synth/data.py": "1780475ef9573c9731cf67f46c1a339ab2fa466c28bbbee5948322ae3f33ca29", + "spectral_synth/launch.py": "5888c115ae4b38b307ac1ac1bb4a9c200a1aa35850819dab55eaeb47946c38e2", + "spectral_synth/model.py": "44eeb23c037e91b8f67e432615ce46540a7ac4242919785f9c4218de23121499", + "spectral_synth/spectral.py": "347aa6d352df72ff18ef35a267b8e0479546263b26174d5256d4e9903cce5f71", + "spectral_transfer/run.py": "33fb544faca0633cd96440e2e4fa3c0e38c8e8cde8a215bfaf8357ed224bfcd8", + "weekly_synth/check.py": "a122b553d9ddc01a506a36713a0df478b03d7fe0b3f9ee1fa34c22c3e982adbf", + "weekly_synth/data.py": "774d0d5216fa263db9d809289dd3daa877f0bcea6ed44a628dd9f8e53829815f", + "weekly_synth/launch.py": "b28347982ecf6d87b45970824d0961027297296e8a6d4372414caeae28427e9d", + "weekly_synth/model.py": "44eeb23c037e91b8f67e432615ce46540a7ac4242919785f9c4218de23121499" + } +} diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/confidence_query/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/confidence_query/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/confidence_query/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/confidence_query/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/confidence_query/model.py new file mode 100644 index 0000000000000000000000000000000000000000..b881039b3752b3396e06415a8d01d24956fa29a7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/confidence_query/model.py @@ -0,0 +1,190 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + if self.recency is not None: + pos=torch.arange(c,device=z.device)[None,:];extras=[] + for j in range(2): + period=periods[:,j:j+1] + recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + n=ctx.shape[0] + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1]) + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/confidence_query/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/confidence_query/train.py new file mode 100644 index 0000000000000000000000000000000000000000..fd9d2a3a0502cee1a67c41c832266c7f87cc5a80 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/confidence_query/train.py @@ -0,0 +1,54 @@ +"""Train only confidence-query features on a frozen model, using paired-sign forecast loss.""" +import argparse,json,math,time,os +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) +ap.add_argument('--initialize-from',required=True);ap.add_argument('--steps',type=int,default=6000) +ap.add_argument('--batch',type=int,default=128);ap.add_argument('--lr',type=float,default=2e-4) +ap.add_argument('--seed',type=int,default=89);ap.add_argument('--save-every',type=int,default=1000);a=ap.parse_args() +torch.set_num_threads(1);torch.manual_seed(a.seed);torch.backends.cuda.matmul.allow_tf32=True +out=Path(a.out);out.mkdir(parents=True,exist_ok=True) +ck=torch.load(a.initialize_from,map_location='cpu',weights_only=False) +config={**ck['config'],'confidence_features':True};model=DirectForecaster(**config).cuda() +missing,unexpected=model.load_state_dict(ck['model'],strict=False) +assert not unexpected and all(k.startswith('confidence.') for k in missing) +for name,param in model.named_parameters():param.requires_grad_(name.startswith('confidence.')) +params=[p for p in model.parameters() if p.requires_grad] +opt=torch.optim.AdamW(params,lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) +ema={k:v.detach().clone() for k,v in model.state_dict().items()};sampler=Sampler(a.packed,seed=a.seed) +(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)) +rng=np.random.default_rng(a.seed) +def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) +def save(step): + for prefix,weights in [('step',model.state_dict()),('ema',ema)]: + state={'model':weights,'config':model.config,'step':step,'args':vars(a),'ema':prefix=='ema'} + path=out/f'{prefix}{step:06d}.pt';torch.save(state,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) +save(0);pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] +for step in range(1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch);x,y,p=[torch.from_numpy(x).cuda() for x in arrays] + lr=a.lr*min(1,step/200)*(.2+.8*.5*(1+math.cos(math.pi*step/a.steps))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(params,1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items(): + if k.startswith('confidence.'):ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + if step%a.save_every==0 or step==a.steps:save(step) +pool.shutdown() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/direct_large/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/direct_large/data.py new file mode 100644 index 0000000000000000000000000000000000000000..2378e33d7352ba5ad97d566148782e63e64b367c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/direct_large/data.py @@ -0,0 +1,71 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + return ctx,tgt,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/direct_large/evaluate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/direct_large/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..05f086d4d84def4a48165f9e65d2948877675e56 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/direct_large/evaluate.py @@ -0,0 +1,16 @@ +import sys,json,argparse,time,hashlib +from pathlib import Path +import torch +from predict import load_model,run +sys.path.insert(0,'/workspace/evaluation') +from score import score,json_safe + +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);ap.add_argument('--valid',default='/workspace/research/valid_screen');ap.add_argument('--baseline',default='/workspace/research/valid_screen/baseline.json');a=ap.parse_args() +torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cuda.matmul.allow_tf32=False +t0=time.time();out=Path(a.out);v=Path(a.valid) +run(load_model(a.weights),v/'input',out) +base=json.loads(Path(a.baseline).read_text())['configs'] +rep=score(v/'truth',out,base) +rep['checkpoint_sha256']=hashlib.sha256(Path(a.weights).read_bytes()).hexdigest();rep['eval_seconds']=time.time()-t0 +(out/'report.json').write_text(json.dumps(json_safe(rep),indent=1)) +print(json.dumps({k:rep[k] for k in ('skill_score','rel_mase_gmean','rel_wql_gmean','n_failed','groups','eval_seconds')},indent=1)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/direct_large/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/direct_large/model.py new file mode 100644 index 0000000000000000000000000000000000000000..7a224cc12a159446a1e427b2052b53d1d1f7e83e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/direct_large/model.py @@ -0,0 +1,142 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional(torch.arange(-nt,0,device=z.device),self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + q=self.query(base.reshape(b,h//p,p*9))+positional(torch.arange(h//p,device=z.device),self.d)[None]+emb + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + pin=torch.maximum(levels*err,(levels-1)*err).mean(-1) + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + return per.mean() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/direct_large/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/direct_large/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/direct_large/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/direct_large/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/direct_large/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..e20c6630475d6b4fa6906eb4ed9454b7b5aeec2c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/direct_large/predict.py @@ -0,0 +1,43 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):q=model.predict(x,p,h).float().cpu().numpy() + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/direct_large/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/direct_large/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf95c9aec5936076b881c340edb960786f2d40d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/direct_large/publish.py @@ -0,0 +1,31 @@ +"""Assemble a relocatable package, then atomically exchange complete directories.""" +import json,os,shutil,ctypes,hashlib,argparse +from pathlib import Path +import torch +HERE=Path(__file__).resolve().parent + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',default='/workspace/submission');ap.add_argument('--report',required=True);ap.add_argument('--experiments',default=str(HERE/'EXPERIMENTS.md'));a=ap.parse_args() + final=Path(a.out);staging=final.parent/f'.{final.name}-staging-{os.getpid()}' + shutil.rmtree(staging,ignore_errors=True);staging.mkdir(parents=True) + for file in ('model.py','predict.py','infer.sh','ts_io.py'): + shutil.copy(HERE/file,staging/file) + shutil.copy(a.weights,staging/'weights.pt');shutil.copy('/opt/runtime/requirements.txt',staging/'requirements.txt') + ck=torch.load(a.weights,map_location='cpu',weights_only=False);digest=hashlib.sha256((staging/'weights.pt').read_bytes()).hexdigest() + sources=json.loads(Path('/workspace/research/packed_sample/meta.json').read_text())['dirs'] + manifest={'name':'direct-seasonal-quantile-v1','contract':'timeseries-forecast/v1','parameters':sum(x.numel() for x in ck['model'].values()),'pretrained_assets':[],'sources_used':[f'gifteval_pretrain/{d}' for d in sources]+['synthetic:direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; data.py generator seed 17'],'weights_sha256':digest,'training_step':ck['step'],'config':ck['config'],'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.'} + (staging/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') + (staging/'config.json').write_text(json.dumps(ck['config'],indent=2)+'\n') + shutil.copy(a.experiments,staging/'EXPERIMENTS.md');shutil.copy(a.report,staging/'validation_report.json') + # Include generator/sampler provenance, which is not imported by inference. + (staging/'provenance').mkdir() + for file in ('pack.py','data.py','train.py'):shutil.copy(HERE/file,staging/'provenance'/file) + (staging/'README.md').write_text('# Direct seasonal quantile foundation forecaster\n\nRun `bash infer.sh INPUT_DIR OUTPUT_DIR`. This package contains all inference assets and uses only its supplied input directory. The 6.76M 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.\n\nThe 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.\n') + if final.exists(): + libc=ctypes.CDLL(None,use_errno=True) + if libc.renameat2(-100,os.fsencode(staging),-100,os.fsencode(final),2):raise OSError(ctypes.get_errno(),os.strerror(ctypes.get_errno())) + shutil.rmtree(staging) + else:os.replace(staging,final) + print(json.dumps(manifest,indent=1)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/direct_large/record.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/direct_large/record.py new file mode 100644 index 0000000000000000000000000000000000000000..1850a33f46fa3ee4d78cac4a5d6152404801a131 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/direct_large/record.py @@ -0,0 +1,9 @@ +import argparse,json,math +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('report');ap.add_argument('--label',required=True);ap.add_argument('--outcome',default='Screened for model selection.');a=ap.parse_args() +r=json.loads(Path(a.report).read_text());p=Path(__file__).with_name('EXPERIMENTS.md') +lines=[f'\n## {a.label}',f'- Checkpoint SHA-256: `{r.get("checkpoint_sha256","see model_manifest.json")}`.',f'- Evaluation: {r["n_configs"]} configurations, {r["n_instances"]} instances, {r["n_failed"]} failed configurations; {r.get("eval_seconds","not separately timed")} seconds.',f'- Overall skill {r["skill_score"]:.6f}; relative MASE {r["rel_mase_gmean"]:.6f}; relative WQL {r["rel_wql_gmean"]:.6f}.'] +for group,entries in r['groups'].items(): + lines.append(f'- {group} skill: '+', '.join(f'{k}={1-math.sqrt(v["rel_mase_gmean"]*v["rel_wql_gmean"]):.4f}' for k,v in entries.items())+'.') +lines.append('- Outcome: '+a.outcome) +with p.open('a') as f:f.write('\n'.join(lines)+'\n') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/direct_large/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/direct_large/train.py new file mode 100644 index 0000000000000000000000000000000000000000..a2ccc736bfef804259199a2dd315347d9854b680 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/direct_large/train.py @@ -0,0 +1,67 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(6);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/direct_large/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/direct_large/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/direct_large/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/direct_large/validation_subset.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/direct_large/validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..4df83e69c4f9a3365955e5d17ffcfc0af71372b7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/direct_large/validation_subset.py @@ -0,0 +1,18 @@ +"""Model-selection-only subset spanning all 97 configurations, seed 2026.""" +import sys,json,copy +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +import ts_io + +root=Path('/workspace/data/valid');out=Path('/workspace/research/valid_screen') +idx=json.loads((root/'input/index.json').read_text());new=copy.deepcopy(idx);rng=np.random.default_rng(2026) +for cfg in new['configs']: + cid=cfg['config_id'];case=ts_io.CaseFile(root/'input/cases'/f'{cid}.h5') + ids=np.sort(rng.choice(case.n,min(case.n,192),replace=False)) + ts_io.write_case_subset(case,ids,out/'input/cases'/f'{cid}.h5') + lab,se,meta=ts_io.read_truth_file(root/'truth/cases'/f'{cid}.h5') + ts_io.write_truth_file(out/'truth/cases'/f'{cid}.h5',lab[ids],se[ids],meta) + cfg['n_instances']=len(ids);case.close() +for kind in ('input','truth'):(out/kind/'index.json').write_text(json.dumps(new,indent=1)) +print('screen instances',sum(c['n_instances'] for c in new['configs'])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/full_paired/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/full_paired/check.py new file mode 100644 index 0000000000000000000000000000000000000000..fda928e16338305fd9912f7bc08cacff58bd8aa4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/full_paired/check.py @@ -0,0 +1,34 @@ +import importlib.util,json,time +from pathlib import Path +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +r=Path('/workspace/research');torch.set_num_threads(1);torch.manual_seed(197);start=time.monotonic() +ck=torch.load(r/'horizon_delta12k.pt',map_location='cpu',weights_only=False) +spec=importlib.util.spec_from_file_location('parent_model',r/'confidence_inference/model.py') +old=importlib.util.module_from_spec(spec);spec.loader.exec_module(old) +parent=old.DirectForecaster(**ck['config']);parent.load_state_dict(ck['model']) +m=DirectForecaster(**ck['config']);m.load_state_dict(ck['model']) +x=torch.randn(4,512);x[0,:50]=float('nan');p=torch.tensor([[24,168]]*4);y=torch.randn(4,128);y[0,32:]=float('nan') +with torch.inference_mode(): + assert all(torch.equal(a,b) for a,b in zip(m(x,p,48),parent(x,p,48))) + short=m(x,p,32)[0];long=m(x,p,128,forecast_lengths=torch.full((4,),32))[0][:,:32] + assert torch.allclose(short,long,atol=3e-6,rtol=1e-6),(short-long).abs().max() + paired=float(loss_fn(m,x,y,p,paired=True));reverse=float(loss_fn(m,-x,-y,p,paired=True)) + assert abs(paired-reverse)<1e-7,(paired,reverse) +a=Sampler(r/'packed_sample',197);b=Sampler(r/'packed_sample',197) +for c,h in [(512,32),(4096,1024)]: + assert all(np.array_equal(v,w,equal_nan=True) for v,w in zip(a.sample(16,c,h),b.sample(16,c,h))) +assert a.rng.bit_generator.state==b.rng.bit_generator.state and a.horizon_rng.bit_generator.state==b.horizon_rng.bit_generator.state +cpu=time.monotonic()-start;del parent,ck,a,b +m=m.cuda();ema={k:v.detach().clone() for k,v in m.state_dict().items()} +moments=[torch.zeros_like(v) for v in m.parameters() for _ in range(2)] +torch.backends.cuda.matmul.allow_tf32=True;torch.cuda.reset_peak_memory_stats();start=time.monotonic() +x=torch.randn(64,4096,device='cuda');y=torch.randn(64,1024,device='cuda');p=torch.tensor([[24,168]]*64,device='cuda') +with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(m,x,y,p,paired=True) +loss.backward();torch.cuda.synchronize() +assert torch.isfinite(loss) and all(v.grad is not None and torch.isfinite(v.grad).all() for v in m.parameters()) +z={'cpu_seconds':cpu,'initial_forecast_bitwise_parent':True,'unused_future_tokens_do_not_change_requested_prefix':True,'paired_loss_sign_symmetric':True,'matched_sampler_main_and_horizon_rng':True,'gpu_fixture_seconds':time.monotonic()-start,'allocated_mib':torch.cuda.max_memory_allocated()/2**20,'reserved_mib':torch.cuda.max_memory_reserved()/2**20,'optimizer_updates':0} +(r/'full_paired_checks.json').write_text(json.dumps(z,indent=2));print(json.dumps(z),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/full_paired/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/full_paired/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/full_paired/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/full_paired/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/full_paired/model.py new file mode 100644 index 0000000000000000000000000000000000000000..dedcdff4698028a8ba655865f8425d0dc3ef0dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/full_paired/model.py @@ -0,0 +1,204 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/horizon_jitter/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/horizon_jitter/data.py new file mode 100644 index 0000000000000000000000000000000000000000..3d632af7e96a71f30b7964a2b3fd73bc1c3f3f3e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/horizon_jitter/data.py @@ -0,0 +1,86 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/horizon_jitter/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/horizon_jitter/model.py new file mode 100644 index 0000000000000000000000000000000000000000..4ffe50d9aadf21d73949e2052ceb7f3642bf65d3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/horizon_jitter/model.py @@ -0,0 +1,180 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(ctx,periods,target.shape[-1],forecast_lengths=lengths) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/horizon_jitter/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/horizon_jitter/train.py new file mode 100644 index 0000000000000000000000000000000000000000..768d33da4421b24bd760d7d9680d0c2cd9bd84e4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/horizon_jitter/train.py @@ -0,0 +1,74 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler,truncate_targets + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + horizon_rng=np.random.default_rng(a.seed+startstep+300003) + def nextbatch(): + 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])) + return truncate_targets(sampler.sample(a.batch,c,h),horizon_rng,a.patch) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_corpus/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_corpus/data.py new file mode 100644 index 0000000000000000000000000000000000000000..a51e912d3c4b63a3ec0cd85133bf0e7aa3429569 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_corpus/data.py @@ -0,0 +1,73 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_corpus/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_corpus/model.py new file mode 100644 index 0000000000000000000000000000000000000000..f8271c5b0bf9a5edb961e1c7839761fe50a2e40b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_corpus/model.py @@ -0,0 +1,171 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024,recency_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + if self.recency is not None: + pos=torch.arange(c,device=z.device)[None,:];extras=[] + for j in range(2): + period=periods[:,j:j+1] + recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_corpus/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_corpus/train.py new file mode 100644 index 0000000000000000000000000000000000000000..2e77612e443d78dd80bcb6a0cc6d01169f61a3a4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_corpus/train.py @@ -0,0 +1,73 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_sign/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_sign/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_sign/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_sign/evaluate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_sign/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..05f086d4d84def4a48165f9e65d2948877675e56 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_sign/evaluate.py @@ -0,0 +1,16 @@ +import sys,json,argparse,time,hashlib +from pathlib import Path +import torch +from predict import load_model,run +sys.path.insert(0,'/workspace/evaluation') +from score import score,json_safe + +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);ap.add_argument('--valid',default='/workspace/research/valid_screen');ap.add_argument('--baseline',default='/workspace/research/valid_screen/baseline.json');a=ap.parse_args() +torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cuda.matmul.allow_tf32=False +t0=time.time();out=Path(a.out);v=Path(a.valid) +run(load_model(a.weights),v/'input',out) +base=json.loads(Path(a.baseline).read_text())['configs'] +rep=score(v/'truth',out,base) +rep['checkpoint_sha256']=hashlib.sha256(Path(a.weights).read_bytes()).hexdigest();rep['eval_seconds']=time.time()-t0 +(out/'report.json').write_text(json.dumps(json_safe(rep),indent=1)) +print(json.dumps({k:rep[k] for k in ('skill_score','rel_mase_gmean','rel_wql_gmean','n_failed','groups','eval_seconds')},indent=1)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_sign/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_sign/model.py new file mode 100644 index 0000000000000000000000000000000000000000..60aeb14b5f4fa298521ddce8a3276d076c1bb631 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_sign/model.py @@ -0,0 +1,154 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional(torch.arange(-nt,0,device=z.device),self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + q=self.query(base.reshape(b,h//p,p*9))+positional(torch.arange(h//p,device=z.device),self.d)[None]+emb + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_sign/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_sign/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_sign/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_sign/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_sign/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..e20c6630475d6b4fa6906eb4ed9454b7b5aeec2c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_sign/predict.py @@ -0,0 +1,43 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):q=model.predict(x,p,h).float().cpu().numpy() + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_sign/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_sign/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf95c9aec5936076b881c340edb960786f2d40d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_sign/publish.py @@ -0,0 +1,31 @@ +"""Assemble a relocatable package, then atomically exchange complete directories.""" +import json,os,shutil,ctypes,hashlib,argparse +from pathlib import Path +import torch +HERE=Path(__file__).resolve().parent + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',default='/workspace/submission');ap.add_argument('--report',required=True);ap.add_argument('--experiments',default=str(HERE/'EXPERIMENTS.md'));a=ap.parse_args() + final=Path(a.out);staging=final.parent/f'.{final.name}-staging-{os.getpid()}' + shutil.rmtree(staging,ignore_errors=True);staging.mkdir(parents=True) + for file in ('model.py','predict.py','infer.sh','ts_io.py'): + shutil.copy(HERE/file,staging/file) + shutil.copy(a.weights,staging/'weights.pt');shutil.copy('/opt/runtime/requirements.txt',staging/'requirements.txt') + ck=torch.load(a.weights,map_location='cpu',weights_only=False);digest=hashlib.sha256((staging/'weights.pt').read_bytes()).hexdigest() + sources=json.loads(Path('/workspace/research/packed_sample/meta.json').read_text())['dirs'] + manifest={'name':'direct-seasonal-quantile-v1','contract':'timeseries-forecast/v1','parameters':sum(x.numel() for x in ck['model'].values()),'pretrained_assets':[],'sources_used':[f'gifteval_pretrain/{d}' for d in sources]+['synthetic:direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; data.py generator seed 17'],'weights_sha256':digest,'training_step':ck['step'],'config':ck['config'],'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.'} + (staging/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') + (staging/'config.json').write_text(json.dumps(ck['config'],indent=2)+'\n') + shutil.copy(a.experiments,staging/'EXPERIMENTS.md');shutil.copy(a.report,staging/'validation_report.json') + # Include generator/sampler provenance, which is not imported by inference. + (staging/'provenance').mkdir() + for file in ('pack.py','data.py','train.py'):shutil.copy(HERE/file,staging/'provenance'/file) + (staging/'README.md').write_text('# Direct seasonal quantile foundation forecaster\n\nRun `bash infer.sh INPUT_DIR OUTPUT_DIR`. This package contains all inference assets and uses only its supplied input directory. The 6.76M 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.\n\nThe 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.\n') + if final.exists(): + libc=ctypes.CDLL(None,use_errno=True) + if libc.renameat2(-100,os.fsencode(staging),-100,os.fsencode(final),2):raise OSError(ctypes.get_errno(),os.strerror(ctypes.get_errno())) + shutil.rmtree(staging) + else:os.replace(staging,final) + print(json.dumps(manifest,indent=1)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_sign/record.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_sign/record.py new file mode 100644 index 0000000000000000000000000000000000000000..1850a33f46fa3ee4d78cac4a5d6152404801a131 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_sign/record.py @@ -0,0 +1,9 @@ +import argparse,json,math +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('report');ap.add_argument('--label',required=True);ap.add_argument('--outcome',default='Screened for model selection.');a=ap.parse_args() +r=json.loads(Path(a.report).read_text());p=Path(__file__).with_name('EXPERIMENTS.md') +lines=[f'\n## {a.label}',f'- Checkpoint SHA-256: `{r.get("checkpoint_sha256","see model_manifest.json")}`.',f'- Evaluation: {r["n_configs"]} configurations, {r["n_instances"]} instances, {r["n_failed"]} failed configurations; {r.get("eval_seconds","not separately timed")} seconds.',f'- Overall skill {r["skill_score"]:.6f}; relative MASE {r["rel_mase_gmean"]:.6f}; relative WQL {r["rel_wql_gmean"]:.6f}.'] +for group,entries in r['groups'].items(): + lines.append(f'- {group} skill: '+', '.join(f'{k}={1-math.sqrt(v["rel_mase_gmean"]*v["rel_wql_gmean"]):.4f}' for k,v in entries.items())+'.') +lines.append('- Outcome: '+a.outcome) +with p.open('a') as f:f.write('\n'.join(lines)+'\n') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_sign/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_sign/train.py new file mode 100644 index 0000000000000000000000000000000000000000..d089166fb1612ddf4955fcd2f096cb0b33624dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_sign/train.py @@ -0,0 +1,70 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(3);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_sign/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_sign/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_sign/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_sign/validation_subset.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_sign/validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..4df83e69c4f9a3365955e5d17ffcfc0af71372b7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/large_sign/validation_subset.py @@ -0,0 +1,18 @@ +"""Model-selection-only subset spanning all 97 configurations, seed 2026.""" +import sys,json,copy +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +import ts_io + +root=Path('/workspace/data/valid');out=Path('/workspace/research/valid_screen') +idx=json.loads((root/'input/index.json').read_text());new=copy.deepcopy(idx);rng=np.random.default_rng(2026) +for cfg in new['configs']: + cid=cfg['config_id'];case=ts_io.CaseFile(root/'input/cases'/f'{cid}.h5') + ids=np.sort(rng.choice(case.n,min(case.n,192),replace=False)) + ts_io.write_case_subset(case,ids,out/'input/cases'/f'{cid}.h5') + lab,se,meta=ts_io.read_truth_file(root/'truth/cases'/f'{cid}.h5') + ts_io.write_truth_file(out/'truth/cases'/f'{cid}.h5',lab[ids],se[ids],meta) + cfg['n_instances']=len(ids);case.close() +for kind in ('input','truth'):(out/kind/'index.json').write_text(json.dumps(new,indent=1)) +print('screen instances',sum(c['n_instances'] for c in new['configs'])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/long_memory_synth/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/long_memory_synth/data.py new file mode 100644 index 0000000000000000000000000000000000000000..95410ba700e638fc2e1375b14dece4df57c10110 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/long_memory_synth/data.py @@ -0,0 +1,73 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=np.exp(-10**(-r.uniform(0,4)));noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/long_memory_synth/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/long_memory_synth/model.py new file mode 100644 index 0000000000000000000000000000000000000000..4ffe50d9aadf21d73949e2052ceb7f3642bf65d3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/long_memory_synth/model.py @@ -0,0 +1,180 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(ctx,periods,target.shape[-1],forecast_lengths=lengths) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/long_memory_synth/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/long_memory_synth/train.py new file mode 100644 index 0000000000000000000000000000000000000000..61de733eea03837247278d9010c2ed8b955d7359 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/long_memory_synth/train.py @@ -0,0 +1,74 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + a.synthetic_ar_time_constants=[1,10000] + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/long_seasonal/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/long_seasonal/check.py new file mode 100644 index 0000000000000000000000000000000000000000..beba62576fae73576eef907b81c674e96622670d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/long_seasonal/check.py @@ -0,0 +1,145 @@ +"""Check exact initialization, fixed feature arithmetic and allowed-data gradients.""" +import argparse +import hashlib +import importlib.util +import json +import sys +import time +from pathlib import Path + +import numpy as np +import torch + +R = Path('/workspace/research') +sys.path.insert(0, str(R / 'long_seasonal')) +from model import DirectForecaster, centered_seasonal_difference, loss_fn +from data import Sampler + +ap = argparse.ArgumentParser() +ap.add_argument('--gpu', action='store_true') +a = ap.parse_args() +torch.set_num_threads(2) +torch.manual_seed(503) +started = time.monotonic() +spec = importlib.util.spec_from_file_location('long_control_model', R / 'overflow_control/model.py') +control_code = importlib.util.module_from_spec(spec) +spec.loader.exec_module(control_code) +parent_path = R / 'horizon_delta12k.pt' +parent = torch.load(parent_path, map_location='cpu', weights_only=False) +config = dict(parent['config'], long_seasonal_features=True) +candidate = DirectForecaster(**config) +missing, unexpected = candidate.load_state_dict(parent['model'], strict=False) +assert set(missing) == {'long_query.weight', 'long_head.weight', 'long_head.bias'} +assert not unexpected +assert all(torch.count_nonzero(candidate.state_dict()[key]) == 0 for key in missing) +control = control_code.DirectForecaster(**parent['config']) +control.load_state_dict(parent['model']) +assert all(torch.equal(value, candidate.state_dict()[key]) for key, value in parent['model'].items()) + +if a.gpu: + import fcntl + lock = open(R / '.evaluation.lock', 'a') + fcntl.flock(lock, fcntl.LOCK_EX) + device = 'cuda' + torch.backends.cuda.matmul.allow_tf32 = False + candidate = candidate.cuda() + control = control.cuda() + rng = np.random.default_rng(509) + x = torch.tensor(rng.normal(size=(8, 512)).astype(np.float32), device=device) + x[0, :23] = float('nan') + x[1] = 0 + p = torch.tensor([[24,168],[7,365],[12,1],[52,1],[4,1],[1,1],[96,672],[2,14]], device=device) + with torch.inference_mode(), torch.autocast('cuda', dtype=torch.bfloat16): + expected = control(x, p, 128) + actual = candidate(x, p, 128) + assert all(torch.equal(v, w) for v, w in zip(expected, actual)) + del control, expected, actual, x, p + torch.cuda.empty_cache() + torch.cuda.reset_peak_memory_stats() + sampler = Sampler(R / 'packed_sample', seed=509, source_weights_from=R / 'packed_sample') + arrays = sampler.sample(64, 4096, 1024) + tensors = [torch.from_numpy(v).cuda() for v in arrays] + placeholders = [torch.zeros_like(v) for v in candidate.parameters() for _ in range(3)] + with torch.autocast('cuda', dtype=torch.bfloat16): + loss = loss_fn(candidate, *tensors, paired=True) + loss.backward() + assert torch.isfinite(loss) + assert all(v.grad is None or torch.isfinite(v.grad).all() for v in candidate.parameters()) + gradients = {key: float(dict(candidate.named_parameters())[key].grad.norm()) for key in missing} + assert gradients['long_head.weight'] > 0 and gradients['long_query.weight'] > 0 + result = dict(seed=509, gpu_initial_function_bitwise_equal=True, + max_shape=[64,4096,1024], loss=float(loss.detach()), added_gradient_norms=gradients, + reserved_mib=torch.cuda.max_memory_reserved()/2**20, + allocated_mib=torch.cuda.max_memory_allocated()/2**20, + includes_ema_and_adam_placeholders=True, seconds=time.monotonic()-started, + optimizer_updates=0, validation_data_read=False) + (R / 'long_seasonal_gpu_checks.json').write_text(json.dumps(result, indent=2)) + print(json.dumps(result)) + raise SystemExit() + +rng = np.random.default_rng(503) +z = rng.normal(size=(4, 96)).astype(np.float32) +valid = rng.random(z.shape) > .12 +z[~valid] = 0 +periods = np.array([[4,7],[2,3],[12,1],[24,168]], dtype=np.int64) +delta, extra = centered_seasonal_difference(torch.from_numpy(z), torch.from_numpy(valid), + torch.from_numpy(periods), 23) +expected = np.zeros((4,23,2), np.float32) +support = np.zeros_like(expected) +for row in range(4): + for j in range(2): + period = int(periods[row,j]) + for t in range(23): + observations, recent = [], [] + for cycle in range(16): + end = max(0, 96-cycle*period) + start = max(0, 96-(cycle+1)*period) + index = 96-period+t%period-cycle*period + if index < 0 or not valid[row,index]: + continue + mean = z[row,start:end][valid[row,start:end]].mean(dtype=np.float64) + value = float(z[row,index])-mean + observations.append(value) + if cycle < 4: + recent.append(value) + if period>=2 and len(observations)>=8 and len(recent)>=2: + expected[row,t,j] = np.mean(observations)-np.mean(recent) + support[row,t,j] = len(observations)/16 +assert np.max(np.abs(delta.numpy()-expected)) < 1e-6 +assert np.array_equal(extra.numpy()[:,:,[1,3]], support) +# Adding a different constant to each complete cycle leaves centered templates unchanged. +z0 = torch.tensor(rng.normal(size=(1,64)).astype(np.float32)) +offsets = torch.tensor(rng.normal(size=(1,16,1)).astype(np.float32)) +z1 = (z0.view(1,16,4)+offsets).view(1,64) +p = torch.tensor([[4,4]]) +ones = torch.ones_like(z0,dtype=torch.bool) +v0 = centered_seasonal_difference(z0,ones,p,16)[0] +v1 = centered_seasonal_difference(z1,ones,p,16)[0] +assert torch.max(torch.abs(v0-v1)) < 1e-6 +for c,h in [(32,6),(96,23),(512,128)]: + ctx = torch.tensor(rng.normal(size=(4,c)).astype(np.float32)) + ctx[0,:c//3] = float('nan') + ctx[1] = 0 + ctx[2] = float('nan') + with torch.inference_mode(): + expected = control(ctx,torch.from_numpy(periods),h) + actual = candidate(ctx,torch.from_numpy(periods),h) + assert all(torch.equal(v,w) for v,w in zip(expected,actual)) +assert (R/'long_seasonal/data.py').read_bytes()==(R/'overflow_control/data.py').read_bytes() +out = R / 'long_seasonal_initial.pt' +assert not out.exists(), 'Do not overwrite an existing declared initial checkpoint' +checkpoint = dict(model=candidate.state_dict(), config=config, step=0, + args=dict(packed=str(R/'packed_sample'), seed=503), + parent_checkpoints=[str(parent_path)], + conversion=dict(method='zero-initialized sixteen-cycle centered seasonal query/head additions', + parent_sha256=hashlib.sha256(parent_path.read_bytes()).hexdigest(), + initial_function_bitwise_equal=True)) +torch.save(checkpoint,out) +result = dict(seed=503, independent_feature_arithmetic=True, centered_cycle_offset_invariance=True, + initial_function_bitwise_equal=True, inherited_weights_bitwise_equal=True, + sampler_byte_identical=True, added_parameters=sum(candidate.state_dict()[k].numel() for k in missing), + total_parameters=sum(v.numel() for v in candidate.parameters()), + checkpoint_sha256=hashlib.sha256(out.read_bytes()).hexdigest(), + seconds=time.monotonic()-started, optimizer_updates=0, validation_data_read=False) +(R/'long_seasonal_checks.json').write_text(json.dumps(result,indent=2)) +print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/long_seasonal/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/long_seasonal/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/long_seasonal/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/long_seasonal/launch.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/long_seasonal/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..d7fd732aae9def625f17a4d15dd2dbe3f4cd9317 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/long_seasonal/launch.py @@ -0,0 +1,31 @@ +"""Queue the audited learned sixteen-cycle summary after nested-volume training.""" +def main(): + import json + import os + import subprocess + from pathlib import Path + R=Path('/workspace/research') + checks=json.loads((R/'long_seasonal_checks.json').read_text()) + assert checks['initial_function_bitwise_equal'] and checks['inherited_weights_bitwise_equal'] + assert checks['independent_feature_arithmetic'] and checks['sampler_byte_identical'] + gpu=json.loads((R/'long_seasonal_gpu_checks.json').read_text()) + assert gpu['gpu_initial_function_bitwise_equal'] and gpu['reserved_mib']<10000 + env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1') + command=['python3',str(R/'recovery/train.py'),'--code-dir',str(R/'long_seasonal'), + '--packed',str(R/'packed_sample'),'--source-weights-from',str(R/'packed_sample'), + '--out',str(R/'runs/long_seasonal'),'--initialize-from',str(R/'long_seasonal_initial.pt'), + '--steps','12000','--batch','64','--lr','.00002','--seed','197','--loss-mode','paired', + '--stop-file',str(R/'long_seasonal.stop')] + with (R/'long_seasonal_queue.log').open('w') as qlog,(R/'long_seasonal_watch.log').open('w') as wlog: + queued=subprocess.Popen(['python3',str(R/'queued_train.py'),'--label','E107 learned sixteen-cycle summary seed197', + '--log',str(R/'long_seasonal_train.log'),'--receipt',str(R/'long_seasonal_queue.json'), + '--wait-pid','13470','--require-checkpoint',str(R/'runs/stratified_volume/recovery.pt'), + '--',*command],stdout=qlog,stderr=subprocess.STDOUT,env=env) + watch=subprocess.Popen(['python3',str(R/'watch_evaluate.py'),'--run',str(R/'runs/long_seasonal'), + '--evaluator',str(R/'long_seasonal_inference/evaluate.py'),'--name','long_seasonal', + '--expected-packed',str(R/'packed_sample'),'--steps','1000,3000,6000,12000'],stdout=wlog,stderr=subprocess.STDOUT,env=env) + print({'queue_pid':queued.pid,'watch_pid':watch.pid},flush=True) + result=queued.wait() + if result:watch.terminate() + watch.wait();raise SystemExit(result) +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/long_seasonal/long_features.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/long_seasonal/long_features.py new file mode 100644 index 0000000000000000000000000000000000000000..efc6e3ba327c6016d844148fcfcc29ac63863f23 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/long_seasonal/long_features.py @@ -0,0 +1,37 @@ +"""Fixed within-context phase summaries; no estimated or adapted parameters.""" +import torch +from torch.nn import functional as F + + +def centered_seasonal_difference(z, valid, periods, horizon): + b, c = z.shape + time = torch.arange(horizon, device=z.device)[None, :] + sums = F.pad((z * valid).cumsum(-1), (1, 0)) + counts = F.pad(valid.float().cumsum(-1), (1, 0)) + deltas, extras = [], [] + for j in range(2): + period = periods[:, j:j+1].clamp(min=1) + anchor = c - period + time % period + centered, masks = [], [] + for cycle in range(16): + end = (c - cycle * period).clamp(min=0, max=c) + start = (c - (cycle + 1) * period).clamp(min=0, max=c) + count = counts.gather(1, end) - counts.gather(1, start) + mean = (sums.gather(1, end) - sums.gather(1, start)) / count.clamp(min=1) + index = anchor - cycle * period + safe = index.clamp(min=0, max=c-1) + present = (index >= 0) & valid.gather(1, safe) + centered.append(z.gather(1, safe) - mean) + masks.append(present) + values = torch.stack(centered) + seen = torch.stack(masks) + n4 = seen[:4].sum(0) + n16 = seen.sum(0) + mean4 = (values[:4] * seen[:4]).sum(0) / n4.clamp(min=1) + mean16 = (values * seen).sum(0) / n16.clamp(min=1) + active = (period >= 2) & (n4 >= 2) & (n16 >= 8) + delta = torch.where(active, mean16 - mean4, 0.) + support = torch.where(active, n16.float() / 16, 0.) + deltas.append(delta) + extras.extend([delta, support]) + return torch.stack(deltas, -1), torch.stack(extras, -1) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/long_seasonal/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/long_seasonal/model.py new file mode 100644 index 0000000000000000000000000000000000000000..298ee3b840cbc8b7da585ee5e47a3822d06717b0 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/long_seasonal/model.py @@ -0,0 +1,260 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + + +def centered_seasonal_difference(z, valid, periods, horizon): + b, c = z.shape + time = torch.arange(horizon, device=z.device)[None, :] + sums = F.pad((z * valid).cumsum(-1), (1, 0)) + counts = F.pad(valid.float().cumsum(-1), (1, 0)) + deltas, extras = [], [] + for j in range(2): + period = periods[:, j:j+1].clamp(min=1) + anchor = c - period + time % period + centered, masks = [], [] + for cycle in range(16): + end = (c - cycle * period).clamp(min=0, max=c) + start = (c - (cycle + 1) * period).clamp(min=0, max=c) + count = counts.gather(1, end) - counts.gather(1, start) + mean = (sums.gather(1, end) - sums.gather(1, start)) / count.clamp(min=1) + index = anchor - cycle * period + safe = index.clamp(min=0, max=c-1) + present = (index >= 0) & valid.gather(1, safe) + centered.append(z.gather(1, safe) - mean) + masks.append(present) + values = torch.stack(centered) + seen = torch.stack(masks) + n4 = seen[:4].sum(0) + n16 = seen.sum(0) + mean4 = (values[:4] * seen[:4]).sum(0) / n4.clamp(min=1) + mean16 = (values * seen).sum(0) / n16.clamp(min=1) + active = (period >= 2) & (n4 >= 2) & (n16 >= 8) + delta = torch.where(active, mean16 - mean4, 0.) + support = torch.where(active, n16.float() / 16, 0.) + deltas.append(delta) + extras.extend([delta, support]) + return torch.stack(deltas, -1), torch.stack(extras, -1) + + + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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,long_seasonal_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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,long_seasonal_features=long_seasonal_features) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + self.long_query=nn.Linear(patch*4,d,bias=False) if long_seasonal_features else None + self.long_head=nn.Linear(d,patch*2) if long_seasonal_features else None + if long_seasonal_features: + nn.init.zeros_(self.long_query.weight) + nn.init.zeros_(self.long_head.weight);nn.init.zeros_(self.long_head.bias) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + if self.long_query is not None:long_delta,long_extra=centered_seasonal_difference(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + hidden=self.norm(q) + out=self.head(hidden).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + if self.long_head is not None: + gates=self.long_head(hidden).view(b,h,2).float().tanh() + median=median+(gates*long_delta).sum(-1) + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/long_seasonal/transfer.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/long_seasonal/transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..c20a4df852f5b150e634ae2c06510d01c7ea18b3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/long_seasonal/transfer.py @@ -0,0 +1,73 @@ +"""Apply one matched feature-learning difference with explicit zero-extension semantics.""" +import argparse +import hashlib +import importlib.util +import json +import sys +import time +from pathlib import Path + +import numpy as np +import torch + +R = Path('/workspace/research') +parser = argparse.ArgumentParser() +for key in ['base','candidate','control','out']: + parser.add_argument('--'+key,required=True) +args = parser.parse_args() +torch.set_num_threads(2) +torch.manual_seed(571) +started = time.monotonic() +paths = [Path(args.base),Path(args.candidate),Path(args.control)] +base,candidate,control = [torch.load(p,map_location='cpu',weights_only=False) for p in paths] +extra = {'long_query.weight','long_head.weight','long_head.bias'} +assert set(base['model'])==set(control['model']) +assert set(candidate['model'])==set(base['model'])|extra +config = dict(candidate['config']) +assert config.pop('long_seasonal_features') is True +assert config==base['config']==control['config'] +sys.path.insert(0,str(R/'long_seasonal')) +from model import DirectForecaster +extended = DirectForecaster(**candidate['config']) +missing,unexpected = extended.load_state_dict(base['model'],strict=False) +assert set(missing)==extra and not unexpected +assert all(torch.count_nonzero(extended.state_dict()[k])==0 for k in extra) +spec = importlib.util.spec_from_file_location('transfer_original_model',R/'overflow_control/model.py') +code = importlib.util.module_from_spec(spec) +spec.loader.exec_module(code) +original = code.DirectForecaster(**base['config']) +original.load_state_dict(base['model']) +rng = np.random.default_rng(571) +periods = torch.tensor([[24,168],[7,365],[52,1],[1,1]]) +for c,h in [(32,6),(512,128)]: + ctx = torch.tensor(rng.normal(size=(4,c)).astype(np.float32)) + ctx[0,:c//3] = float('nan') + ctx[1] = 0 + ctx[2] = float('nan') + with torch.inference_mode(): + a = original(ctx,periods,h) + b = extended(ctx,periods,h) + assert all(torch.equal(v,w) for v,w in zip(a,b)) +weights = {k:v.clone() for k,v in extended.state_dict().items()} +for k in weights: + if k in extra: + weights[k].copy_(candidate['model'][k]) + else: + assert weights[k].shape==candidate['model'][k].shape==control['model'][k].shape + weights[k].add_(candidate['model'][k]-control['model'][k]) +assert all(torch.isfinite(v).all() for v in weights.values()) +out = Path(args.out) +assert not out.exists(),'Refuse to overwrite a declared fixed candidate' +conversion = dict(method='matched training delta after zero extension of new seasonal query/head parameters', + formula='extend_zero(base) + candidate - extend_zero(control)',coefficient=1.0, + new_parameters_from_candidate=sorted(extra), + parent_hashes={str(p):hashlib.sha256(p.read_bytes()).hexdigest() for p in paths}, + base_extension_forward_bitwise_equal=True,check_seed=571, + seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False) +checkpoint = dict(model=weights,config=candidate['config'],step=0,args={'packed':base['args']['packed']}, + parent_checkpoints=[str(p) for p in paths],conversion=conversion) +torch.save(checkpoint,out) +result = dict(conversion,checkpoint_sha256=hashlib.sha256(out.read_bytes()).hexdigest(), + parameters=sum(v.numel() for v in weights.values())) +out.with_suffix('.json').write_text(json.dumps(result,indent=2)) +print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/overflow_control/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/overflow_control/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/overflow_control/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/overflow_control/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/overflow_control/model.py new file mode 100644 index 0000000000000000000000000000000000000000..3532e5063bd8b5013f6b6e35703707ffef66e00b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/overflow_control/model.py @@ -0,0 +1,213 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/partial_delta/merge.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/partial_delta/merge.py new file mode 100644 index 0000000000000000000000000000000000000000..3dde47d52d25ed2b013942b3887f1bf686e42ed8 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/partial_delta/merge.py @@ -0,0 +1,16 @@ +"""Apply the difference of two matched, locally trained checkpoints to our selected model.""" +import argparse,torch,hashlib,json,time +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('--base',required=True);ap.add_argument('--candidate',required=True);ap.add_argument('--control',required=True);ap.add_argument('--out',required=True);a=ap.parse_args() +torch.set_num_threads(1);start=time.monotonic() +base=torch.load(a.base,map_location='cpu',weights_only=False);candidate=torch.load(a.candidate,map_location='cpu',weights_only=False);control=torch.load(a.control,map_location='cpu',weights_only=False) +assert set(candidate['model'])==set(control['model']) +weights={k:v.clone() for k,v in base['model'].items()} +for k in candidate['model']: + assert k in weights and weights[k].shape==candidate['model'][k].shape==control['model'][k].shape + weights[k].add_(candidate['model'][k]-control['model'][k]) +assert all(torch.isfinite(v).all() for v in weights.values()) +parents=[a.base,a.candidate,a.control] +conversion={'method':'matched training delta','formula':'base + candidate - control','coefficient':1.0,'parent_hashes':{p:hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in parents},'seconds':time.monotonic()-start} +ck={'model':weights,'config':base['config'],'step':0,'args':{'packed':base['args']['packed']},'parent_checkpoints':parents,'conversion':conversion} +torch.save(ck,a.out);print(json.dumps(conversion)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/partial_targets/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/partial_targets/data.py new file mode 100644 index 0000000000000000000000000000000000000000..a51e912d3c4b63a3ec0cd85133bf0e7aa3429569 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/partial_targets/data.py @@ -0,0 +1,73 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/partial_targets/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/partial_targets/model.py new file mode 100644 index 0000000000000000000000000000000000000000..4ffe50d9aadf21d73949e2052ceb7f3642bf65d3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/partial_targets/model.py @@ -0,0 +1,180 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(ctx,periods,target.shape[-1],forecast_lengths=lengths) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/partial_targets/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/partial_targets/train.py new file mode 100644 index 0000000000000000000000000000000000000000..2e77612e443d78dd80bcb6a0cc6d01169f61a3a4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/partial_targets/train.py @@ -0,0 +1,73 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/convert.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/convert.py new file mode 100644 index 0000000000000000000000000000000000000000..b2cbc8fc919be6a77eca9ab19c4faa06060a2e0d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/convert.py @@ -0,0 +1,18 @@ +"""Convert only our own trained checkpoint from 32- to 16-point patches. + +Context/query projections fold the two halves by summation, preserving the +embedding of constant features. The output projection keeps the first half. +Attention/MLP weights are inherited unchanged; position units remain 32 points. +""" +import argparse,torch,hashlib +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('--input',required=True);ap.add_argument('--output',required=True);a=ap.parse_args() +ck=torch.load(a.input,map_location='cpu',weights_only=False);state=ck['model'];d=ck['config']['d'];assert ck['config']['patch']==32 +old=state['embed.0.weight'].reshape(d,2,32);state['embed.0.weight']=(old[:,:,:16]+old[:,:,16:]).reshape(d,32) +old=state['query.0.weight'].reshape(d,32,9);state['query.0.weight']=(old[:,:16]+old[:,16:]).reshape(d,16*9) +state['head.weight']=state['head.weight'].reshape(32,18,d)[:16].reshape(16*18,d).clone() +state['head.bias']=state['head.bias'].reshape(32,18)[:16].reshape(16*18).clone() +ck['config']['patch']=16 +ck['conversion']={'from_checkpoint':str(Path(a.input).resolve()),'from_sha256':hashlib.sha256(Path(a.input).read_bytes()).hexdigest(),'method':'fold input/query halves by summation; retain first 16 output rows; preserve physical positional units'} +ck['args']={**ck['args'],'initialize_from':str(Path(a.input).resolve()),'converted':True} +torch.save(ck,a.output) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/evaluate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..05f086d4d84def4a48165f9e65d2948877675e56 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/evaluate.py @@ -0,0 +1,16 @@ +import sys,json,argparse,time,hashlib +from pathlib import Path +import torch +from predict import load_model,run +sys.path.insert(0,'/workspace/evaluation') +from score import score,json_safe + +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);ap.add_argument('--valid',default='/workspace/research/valid_screen');ap.add_argument('--baseline',default='/workspace/research/valid_screen/baseline.json');a=ap.parse_args() +torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cuda.matmul.allow_tf32=False +t0=time.time();out=Path(a.out);v=Path(a.valid) +run(load_model(a.weights),v/'input',out) +base=json.loads(Path(a.baseline).read_text())['configs'] +rep=score(v/'truth',out,base) +rep['checkpoint_sha256']=hashlib.sha256(Path(a.weights).read_bytes()).hexdigest();rep['eval_seconds']=time.time()-t0 +(out/'report.json').write_text(json.dumps(json_safe(rep),indent=1)) +print(json.dumps({k:rep[k] for k in ('skill_score','rel_mase_gmean','rel_wql_gmean','n_failed','groups','eval_seconds')},indent=1)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/model.py new file mode 100644 index 0000000000000000000000000000000000000000..06cce56e2ce671b6683f0246900abfcac06bb3c0 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/model.py @@ -0,0 +1,154 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..e20c6630475d6b4fa6906eb4ed9454b7b5aeec2c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/predict.py @@ -0,0 +1,43 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):q=model.predict(x,p,h).float().cpu().numpy() + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf95c9aec5936076b881c340edb960786f2d40d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/publish.py @@ -0,0 +1,31 @@ +"""Assemble a relocatable package, then atomically exchange complete directories.""" +import json,os,shutil,ctypes,hashlib,argparse +from pathlib import Path +import torch +HERE=Path(__file__).resolve().parent + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',default='/workspace/submission');ap.add_argument('--report',required=True);ap.add_argument('--experiments',default=str(HERE/'EXPERIMENTS.md'));a=ap.parse_args() + final=Path(a.out);staging=final.parent/f'.{final.name}-staging-{os.getpid()}' + shutil.rmtree(staging,ignore_errors=True);staging.mkdir(parents=True) + for file in ('model.py','predict.py','infer.sh','ts_io.py'): + shutil.copy(HERE/file,staging/file) + shutil.copy(a.weights,staging/'weights.pt');shutil.copy('/opt/runtime/requirements.txt',staging/'requirements.txt') + ck=torch.load(a.weights,map_location='cpu',weights_only=False);digest=hashlib.sha256((staging/'weights.pt').read_bytes()).hexdigest() + sources=json.loads(Path('/workspace/research/packed_sample/meta.json').read_text())['dirs'] + manifest={'name':'direct-seasonal-quantile-v1','contract':'timeseries-forecast/v1','parameters':sum(x.numel() for x in ck['model'].values()),'pretrained_assets':[],'sources_used':[f'gifteval_pretrain/{d}' for d in sources]+['synthetic:direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; data.py generator seed 17'],'weights_sha256':digest,'training_step':ck['step'],'config':ck['config'],'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.'} + (staging/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') + (staging/'config.json').write_text(json.dumps(ck['config'],indent=2)+'\n') + shutil.copy(a.experiments,staging/'EXPERIMENTS.md');shutil.copy(a.report,staging/'validation_report.json') + # Include generator/sampler provenance, which is not imported by inference. + (staging/'provenance').mkdir() + for file in ('pack.py','data.py','train.py'):shutil.copy(HERE/file,staging/'provenance'/file) + (staging/'README.md').write_text('# Direct seasonal quantile foundation forecaster\n\nRun `bash infer.sh INPUT_DIR OUTPUT_DIR`. This package contains all inference assets and uses only its supplied input directory. The 6.76M 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.\n\nThe 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.\n') + if final.exists(): + libc=ctypes.CDLL(None,use_errno=True) + if libc.renameat2(-100,os.fsencode(staging),-100,os.fsencode(final),2):raise OSError(ctypes.get_errno(),os.strerror(ctypes.get_errno())) + shutil.rmtree(staging) + else:os.replace(staging,final) + print(json.dumps(manifest,indent=1)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/record.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/record.py new file mode 100644 index 0000000000000000000000000000000000000000..1850a33f46fa3ee4d78cac4a5d6152404801a131 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/record.py @@ -0,0 +1,9 @@ +import argparse,json,math +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('report');ap.add_argument('--label',required=True);ap.add_argument('--outcome',default='Screened for model selection.');a=ap.parse_args() +r=json.loads(Path(a.report).read_text());p=Path(__file__).with_name('EXPERIMENTS.md') +lines=[f'\n## {a.label}',f'- Checkpoint SHA-256: `{r.get("checkpoint_sha256","see model_manifest.json")}`.',f'- Evaluation: {r["n_configs"]} configurations, {r["n_instances"]} instances, {r["n_failed"]} failed configurations; {r.get("eval_seconds","not separately timed")} seconds.',f'- Overall skill {r["skill_score"]:.6f}; relative MASE {r["rel_mase_gmean"]:.6f}; relative WQL {r["rel_wql_gmean"]:.6f}.'] +for group,entries in r['groups'].items(): + lines.append(f'- {group} skill: '+', '.join(f'{k}={1-math.sqrt(v["rel_mase_gmean"]*v["rel_wql_gmean"]):.4f}' for k,v in entries.items())+'.') +lines.append('- Outcome: '+a.outcome) +with p.open('a') as f:f.write('\n'.join(lines)+'\n') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/train.py new file mode 100644 index 0000000000000000000000000000000000000000..3cdc106980371c99d81c71d6746943c47206be83 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/train.py @@ -0,0 +1,71 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(3);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/validation_subset.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..4df83e69c4f9a3365955e5d17ffcfc0af71372b7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/patch16/validation_subset.py @@ -0,0 +1,18 @@ +"""Model-selection-only subset spanning all 97 configurations, seed 2026.""" +import sys,json,copy +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +import ts_io + +root=Path('/workspace/data/valid');out=Path('/workspace/research/valid_screen') +idx=json.loads((root/'input/index.json').read_text());new=copy.deepcopy(idx);rng=np.random.default_rng(2026) +for cfg in new['configs']: + cid=cfg['config_id'];case=ts_io.CaseFile(root/'input/cases'/f'{cid}.h5') + ids=np.sort(rng.choice(case.n,min(case.n,192),replace=False)) + ts_io.write_case_subset(case,ids,out/'input/cases'/f'{cid}.h5') + lab,se,meta=ts_io.read_truth_file(root/'truth/cases'/f'{cid}.h5') + ts_io.write_truth_file(out/'truth/cases'/f'{cid}.h5',lab[ids],se[ids],meta) + cfg['n_instances']=len(ids);case.close() +for kind in ('input','truth'):(out/kind/'index.json').write_text(json.dumps(new,indent=1)) +print('screen instances',sum(c['n_instances'] for c in new['configs'])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/postloss/check_numerical_fix.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/postloss/check_numerical_fix.py new file mode 100644 index 0000000000000000000000000000000000000000..0dd7f0b04a538020f59a4d4e8d6bc4884e0acd29 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/postloss/check_numerical_fix.py @@ -0,0 +1,26 @@ +"""Regression test for observed variance overflow in permitted training data.""" +import importlib.util +import json +from pathlib import Path +import time +import torch +from model import DirectForecaster,loss_fn + +R=Path('/workspace/research');torch.set_num_threads(1);started=time.monotonic() +spec=importlib.util.spec_from_file_location('original',Path(__file__).with_name('model_before_numerical_fix.py')) +original=importlib.util.module_from_spec(spec);spec.loader.exec_module(original) +torch.manual_seed(331);normal=torch.randn(8,512);normal[0,:200]=float('nan');normal[1]=float('nan');normal[2]=0 +old=original.DirectForecaster.standardize(normal);new=DirectForecaster.standardize(normal) +assert all(torch.equal(a,b) for a,b in zip(old,new)) +f=torch.load(R/'postloss_nonfinite_fixture.pt',map_location='cpu',weights_only=False) +indices=torch.tensor([37]);ctx=f['ctx'][indices];target=f['target'][indices];periods=f['periods'][indices] +z,valid,mu,scale=DirectForecaster.standardize(ctx) +assert torch.isfinite(z).all() and torch.isfinite(mu).all() and torch.isfinite(scale).all() +ck=torch.load(R/'horizon_delta12k.pt',map_location='cpu',weights_only=False) +m=DirectForecaster(**ck['config']).cuda();m.load_state_dict(ck['model']) +with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(m,ctx.cuda(),target.cuda(),periods.cuda(),paired=True) +loss.backward();torch.cuda.synchronize() +assert torch.isfinite(loss) and all(v.grad is not None and torch.isfinite(v.grad).all() for v in m.parameters()) +result={'ordinary_rows_bitwise_original':True,'observed_overflow_row_loss':float(loss.detach()), + 'all_gradients_finite':True,'optimizer_updates':0,'seconds':time.monotonic()-started} +(R/'postloss_numerical_fix_checks.json').write_text(json.dumps(result,indent=2));print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/postloss/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/postloss/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/postloss/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/postloss/diagnose_nonfinite.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/postloss/diagnose_nonfinite.py new file mode 100644 index 0000000000000000000000000000000000000000..770ff91d0718cbb6b947fc91fd61697ea50cbfd6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/postloss/diagnose_nonfinite.py @@ -0,0 +1,42 @@ +"""Find nonfinite fixed-transform outputs on the unchanged allowed-corpus stream.""" +import json +from pathlib import Path +import time +import numpy as np +import torch +from model import DirectForecaster +from data import Sampler +from torch_post import apply_fixed,context_statistics + +R=Path('/workspace/research');torch.set_num_threads(1);torch.manual_seed(197) +torch.backends.cuda.matmul.allow_tf32=True +ck=torch.load(R/'horizon_delta12k.pt',map_location='cpu',weights_only=False) +m=DirectForecaster(**ck['config']).cuda();m.load_state_dict(ck['model']);m.eval() +sampler=Sampler(R/'packed_sample',seed=197,source_weights_from=R/'packed_sample') +rng=np.random.default_rng(197);started=time.monotonic() +for step in range(1,251): + 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])) + arrays=sampler.sample(64,c,h);ctx,target,periods=[torch.from_numpy(v).cuda() for v in arrays] + with torch.no_grad(),torch.autocast('cuda',dtype=torch.bfloat16): + seen=torch.isfinite(target);pos=torch.arange(h,device=ctx.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + raw,mu,scale=m(torch.cat((ctx,-ctx),0),periods.repeat(2,1),h,forecast_lengths=lengths.repeat(2)) + q=(raw[:64]-raw[64:].flip(-1))*.5;mu=mu[:64];scale=scale[:64] + denormalized=q*scale[:,:,None]+mu[:,:,None] + post=apply_fixed(ctx,periods,denormalized) + bad=~torch.isfinite(post).all((1,2)) + if bad.any(): + stats=context_statistics(ctx,periods,h) + badids=torch.nonzero(bad)[:,0] + receipt={'step':step,'context':c,'horizon':h,'bad_rows':badids.tolist(), + 'raw_finite':bool(torch.isfinite(q).all()),'scale_finite':bool(torch.isfinite(scale).all()), + 'denormalized_finite':bool(torch.isfinite(denormalized).all()), + 'statistics_finite':[bool(torch.isfinite(v).all()) for v in stats], + 'bad_scale':scale[bad].tolist(),'bad_mu':mu[bad].tolist(), + 'bad_maximum_context':torch.nan_to_num(ctx[bad]).abs().max(-1).values.tolist(), + 'seconds':time.monotonic()-started,'optimizer_updates':0} + torch.save({'ctx':ctx.cpu(),'target':target.cpu(),'periods':periods.cpu(), + 'raw':denormalized.cpu(),'scale':scale.cpu(),'post':post.cpu(), + 'statistics':[v.cpu() for v in stats]},R/'postloss_nonfinite_fixture.pt') + (R/'postloss_nonfinite_diagnostic.json').write_text(json.dumps(receipt,indent=2));print(json.dumps(receipt));break +else:print(json.dumps({'no_nonfinite_fixed_parent_outputs_in_first_steps':250,'seconds':time.monotonic()-started})) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/postloss/gpu_check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/postloss/gpu_check.py new file mode 100644 index 0000000000000000000000000000000000000000..a457afa8d1dd55d2167434b70f4e1488e41e4049 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/postloss/gpu_check.py @@ -0,0 +1,24 @@ +"""Verify the new training loss at the largest scheduled bf16 shape.""" +import fcntl,json,sys,time +from pathlib import Path +import torch + +r=Path('/workspace/research');sys.path.insert(0,str(r/'postloss')) +from model import DirectForecaster,loss_fn +from data import Sampler +with open(r/'.evaluation.lock','a') as lock: + fcntl.flock(lock,fcntl.LOCK_EX) + torch.set_num_threads(1);torch.manual_seed(281);torch.backends.cuda.matmul.allow_tf32=True + started=time.monotonic() + ck=torch.load(r/'horizon_delta12k.pt',map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).cuda();model.load_state_dict(ck['model']) + x,y,p=[torch.from_numpy(a).cuda() for a in Sampler(r/'packed_sample',281).sample(64,4096,1024)] + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p,paired=True) + loss.backward();torch.cuda.synchronize() + assert torch.isfinite(loss) + assert all(v.grad is not None and torch.isfinite(v.grad).all() for v in model.parameters()) + result={'seed':281,'batch':64,'context':4096,'horizon':1024,'optimizer_updates':0, + 'loss':float(loss.detach()),'seconds':time.monotonic()-started, + 'peak_allocated_mib':torch.cuda.max_memory_allocated()/2**20, + 'peak_reserved_mib':torch.cuda.max_memory_reserved()/2**20} + (r/'postloss_gpu_check.json').write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/postloss/launch_completion.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/postloss/launch_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..8bdf1346b99ae846a2679a7494c9b88c1900bdce --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/postloss/launch_completion.py @@ -0,0 +1,30 @@ +"""Complete the original pruned schedule from its immutable exact training state.""" +def main(): + import json + import os + import subprocess + from pathlib import Path + R=Path('/workspace/research') + receipt=json.loads((R/'postloss_recovery003653.json').read_text()) + assert receipt['step']==3653 + assert json.loads((R/'postloss_completion_code_audit.json').read_text())['matches_original_E75_archived_training_code'] + assert (R/'postloss.stop').exists() + env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1') + command=['python3',str(R/'recovery/train.py'),'--code-dir',str(R/'postloss'), + '--packed',str(R/'packed_sample'),'--source-weights-from',str(R/'packed_sample'), + '--out',str(R/'runs/postloss_completion'),'--initialize-from',str(R/'horizon_delta12k.pt'), + '--resume',str(R/'postloss_recovery003653.pt'),'--steps','12000','--batch','64','--lr','.00002', + '--seed','197','--loss-mode','paired','--stop-file',str(R/'postloss_completion.stop')] + with (R/'postloss_completion_queue.log').open('w') as qlog,(R/'postloss_completion_watch.log').open('w') as wlog: + queued=subprocess.Popen(['python3',str(R/'queued_train.py'),'--label','E98 complete original E75 schedule', + '--log',str(R/'postloss_completion_train.log'),'--receipt',str(R/'postloss_completion_queue.json'), + '--wait-pid','9274','--require-checkpoint',str(R/'runs/split_patch/recovery.pt'), + '--',*command],stdout=qlog,stderr=subprocess.STDOUT,env=env) + watch=subprocess.Popen(['python3',str(R/'watch_evaluate.py'),'--run',str(R/'runs/postloss_completion'), + '--evaluator',str(R/'postloss_inference/evaluate.py'),'--name','postloss_completion', + '--steps','6000,12000'],stdout=wlog,stderr=subprocess.STDOUT,env=env) + print({'queue_pid':queued.pid,'watch_pid':watch.pid},flush=True) + result=queued.wait() + if result:watch.terminate() + watch.wait();raise SystemExit(result) +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/postloss/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/postloss/model.py new file mode 100644 index 0000000000000000000000000000000000000000..014b585df72cc69852a8eedf302320b52fe55aad --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/postloss/model.py @@ -0,0 +1,216 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + from torch_post import apply_fixed + q=apply_fixed(ctx,periods,q*scale[:,:,None]+mu[:,:,None]) + q=(q-mu[:,:,None])/scale[:,:,None] + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/postloss/model_before_numerical_fix.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/postloss/model_before_numerical_fix.py new file mode 100644 index 0000000000000000000000000000000000000000..1dab6e08582e4610693292e765d40a8b5392e97a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/postloss/model_before_numerical_fix.py @@ -0,0 +1,207 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + from torch_post import apply_fixed + q=apply_fixed(ctx,periods,q*scale[:,:,None]+mu[:,:,None]) + q=(q-mu[:,:,None])/scale[:,:,None] + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/postloss/restart.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/postloss/restart.py new file mode 100644 index 0000000000000000000000000000000000000000..fa09bf30ead55ac10ca2d8c9a55277ddd71986f7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/postloss/restart.py @@ -0,0 +1,25 @@ +"""Restart corrected E75 from the declared parent and record process compute.""" +import json +import os +from pathlib import Path +import subprocess +import time + +R=Path('/workspace/research');run=R/'runs/postloss' +receipt=json.loads((R/'postloss_queue_before_recovery2.json').read_text()) +command=receipt['command'] +assert not (run/'recovery.pt').exists(),'This script is only for the documented pre-checkpoint numerical restart.' +env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1') +with (R/'postloss_recovery3.log').open('w') as f: + p=subprocess.Popen(command,stdout=f,stderr=subprocess.STDOUT,env=env) +record={'command':command,'status':'running','pid':p.pid,'log':str(R/'postloss_recovery3.log'), + 'started_utc':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()), + 'note':'Restart own E62 initialization after verified float32 variance-overflow correction; original seed and recipe unchanged.'} +path=R/'postloss_recovery3_receipt.json';path.write_text(json.dumps(record,indent=2)) +watch=['python3',str(R/'watch_evaluate.py'),'--run',str(run),'--evaluator',str(R/'postloss_inference/evaluate.py'), + '--name','postloss','--steps','1000,3000,6000,12000'] +with (R/'postloss_watch_recovery3_fixed.log').open('w') as f: + subprocess.Popen(watch,stdout=f,stderr=subprocess.STDOUT,env=env) +started=time.monotonic();returncode=p.wait() +record.update(status='complete' if returncode==0 else 'failed',returncode=returncode,process_seconds=time.monotonic()-started) +path.write_text(json.dumps(record,indent=2));raise SystemExit(returncode) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/postloss/torch_post.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/postloss/torch_post.py new file mode 100644 index 0000000000000000000000000000000000000000..e19586bcc1677d56cedb6ce02c2f57797157f5f3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/postloss/torch_post.py @@ -0,0 +1,112 @@ +"""Differentiable forecast transforms with the package's fixed context rules. + +Context statistics are constants with respect to model parameters. Gradients +flow only through the forecast, including the continuity correction's anchor. +""" +import torch + + +@torch.no_grad() +def context_statistics(ctx, periods, horizon): + x=ctx.double(); finite=torch.isfinite(x); clean=torch.where(finite,x,0.) + b,c=x.shape; device=x.device + pos=torch.arange(c,device=device)[None,:] + count=finite.sum(-1).clamp(min=1) + mean=clean.sum(-1)/count + variance=(torch.where(finite,x-mean[:,None],0.).square()).sum(-1)/count + positive=((x>=0)|~finite).all(-1) + zeros=((x==0)&finite).sum(-1) + zero_active=positive&(zeros>=4)&(zeros/count>=.1) + cutoff=torch.where(zero_active,.4*variance.sqrt(),0.) + first=torch.where(finite,pos,c).min(-1).values + length=c-first + phase=torch.arange(max(1,c//3),device=device)[None,:] + future=torch.arange(horizon,device=device)[None,:] + z=torch.tensor([-1.2815515655,-.8416212336,-.5244005127,-.2533471031,0, + .2533471031,.5244005127,.8416212336,1.2815515655],device=device) + best_weight=torch.zeros(b,device=device,dtype=torch.float64) + prior=torch.zeros(b,horizon,9,device=device,dtype=torch.float64) + prior_valid=torch.zeros(b,horizon,device=device,dtype=torch.bool) + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + cycles=(length[:,None]//p).clamp(max=8) + history=finite&(pos>=c-cycles*p) + n=history.sum(-1).clamp(min=1) + center=(clean*history).sum(-1)/n + var=torch.where(history,x-center[:,None],0.).square().sum(-1)/n + previous=pos-p;safe=previous.clamp(min=0) + pairs=(previous>=c-cycles*p)&(previous>=0)&finite&finite.gather(1,safe) + pairs_count=pairs.sum(-1) + difference=clean-clean.gather(1,safe) + mse=(difference.square()*pairs).sum(-1)/pairs_count.clamp(min=1) + weight=(1-mse/(var+1e-12)/.25).clamp(0,.98) + eligible=(p[:,0]>=2)&(cycles[:,0]>=3)&(pairs_count>=p[:,0]) + weight=torch.where(eligible,weight,0.) + values=[];observed=[] + for cycle in range(4): + idx=c-p+phase-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(phase=0)&(cycle0 + template=(values*observed).sum(0)/nphase.clamp(min=1) + ntemplate=phase_valid.sum(-1).clamp(min=1) + template_mean=(template*phase_valid).sum(-1)/ntemplate + recent=finite&(pos>=c-p) + nr=recent.sum(-1).clamp(min=1) + recent_mean=(clean*recent).sum(-1)/nr + template=template+(recent_mean-template_mean)[:,None] + template_mean=(template*phase_valid).sum(-1)/ntemplate + recent_var=torch.where(recent,x-recent_mean[:,None],0.).square().sum(-1)/nr + template_var=((template-template_mean[:,None]).square()*phase_valid).sum(-1)/ntemplate + used_cycles=cycles[:,0].clamp(min=1,max=4) + noise=mse/2 + target_var=(recent_var-noise).clamp(min=0) + base_var=(template_var-noise/used_cycles).clamp(min=0) + ratio=(target_var/base_var.clamp(min=1e-12)).sqrt().clamp(.5,2.) + align=nr>=torch.maximum(torch.full_like(nr,2),.75*p[:,0]) + ratio=torch.where(align,ratio,1.) + template=template_mean[:,None]+(template-template_mean[:,None])*ratio[:,None] + sigma=(noise*(1+1/used_cycles)).sqrt() + index=(future%p).clamp(max=phase.shape[-1]-1) + selected=template.gather(1,index) + valid=phase_valid.gather(1,index) + q=selected[:,:,None]+sigma[:,None,None]*z[None,None,:] + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + choose=weight>best_weight + prior=torch.where(choose[:,None,None],q,prior) + prior_valid=torch.where(choose[:,None],valid,prior_valid) + best_weight=torch.maximum(best_weight,weight) + seasonal_weight=best_weight[:,None]*prior_valid + + recent=x[:,-512:];seen=torch.isfinite(recent) + n=seen.sum(-1).clamp(min=1);clean_recent=torch.where(seen,recent,0.) + center=clean_recent.sum(-1)/n + var=torch.where(seen,recent-center[:,None],0.).square().sum(-1)/n + differences=recent[:,1:]-recent[:,:-1] + diff_seen=torch.isfinite(differences);nd=diff_seen.sum(-1) + mse=torch.where(diff_seen,differences,0.).square().sum(-1)/nd.clamp(min=1) + tail=differences[:,-8:] + tail_seen=torch.isfinite(tail);nt=tail_seen.sum(-1) + sorted_tail=torch.where(tail_seen,tail,float('inf')).sort(-1).values + if tail.shape[-1]: + lo=((nt-1).clamp(min=0)//2)[:,None];hi=(nt//2).clamp(max=tail.shape[-1]-1)[:,None] + median=(sorted_tail.gather(1,lo)+sorted_tail.gather(1,hi))[:,0]/2 + else:median=torch.zeros(b,device=device,dtype=x.dtype) + continuity_weight=(1-mse/(var+1e-12)/.5).clamp(0,.95) + active=(nd>=8)&(nt>0)&seen[:,-1] + continuity_weight=torch.where(active,continuity_weight,0.) + anchor=torch.where(active,recent[:,-1]+median,0.) + return seasonal_weight,prior,continuity_weight,anchor,positive,cutoff + + +def apply_fixed(ctx,periods,quant): + """Quantiles are raw-scale tensors of shape (batch,horizon,9).""" + weight,prior,cweight,anchor,positive,cutoff=context_statistics(ctx,periods,quant.shape[1]) + q=torch.where(positive[:,None,None],quant.clamp(min=0),quant) + q=((1-weight[:,:,None])*q+weight[:,:,None]*prior).float() + bias=(cweight*(anchor-q[:,0,4])).float() + decay=torch.exp(-torch.arange(q.shape[1],device=q.device,dtype=torch.float64)/24) + q=(q.double()+bias[:,None,None]*decay[None,:,None]).float() + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return torch.where((q>=0)&(q8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/recency_features/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/recency_features/model.py new file mode 100644 index 0000000000000000000000000000000000000000..f8271c5b0bf9a5edb961e1c7839761fe50a2e40b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/recency_features/model.py @@ -0,0 +1,171 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024,recency_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + if self.recency is not None: + pos=torch.arange(c,device=z.device)[None,:];extras=[] + for j in range(2): + period=periods[:,j:j+1] + recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/recency_features/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/recency_features/train.py new file mode 100644 index 0000000000000000000000000000000000000000..3bfb8b90f1a6656881b7598f864becaa737a76f4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/recency_features/train.py @@ -0,0 +1,73 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(3);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/recovery/exposure_audit.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/recovery/exposure_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..fb67738bc9ed77f87173feda2430365e66c75966 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/recovery/exposure_audit.py @@ -0,0 +1,46 @@ +"""Describe sampled observation exposure and training invested in selected ancestry.""" +import json +import sys +import time +from pathlib import Path +import numpy as np + +R=Path('/workspace/research') +sys.path.insert(0,str(R/'random_capacity')) +from data import Sampler + +started=time.monotonic() +seed=521 +sampler=Sampler(R/'packed_sample',seed=seed,source_weights_from=R/'packed_sample') +rng=np.random.default_rng(seed) +rows=context_points=target_points=0 +for _ in range(320): + 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])) + x,y,p=sampler.sample(64,c,h) + rows+=len(x) + context_points+=int(np.isfinite(x).sum()) + target_points+=int(np.isfinite(y).sum()) +manifest=json.loads(Path('/workspace/submission/model_manifest.json').read_text()) +runs={} +for item in manifest['training_lineage']: + path=Path(item['checkpoint']) + batch=item.get('training_settings',{}).get('batch') + if path.parts[0]!='runs' or not batch: + continue + run=path.parts[1] + step=item.get('step',0) + if step>runs.get(run,{}).get('step',0): + runs[run]=dict(step=step,batch=batch,rows=step*batch,checkpoint=item['checkpoint']) +ancestral_rows=sum(v['rows'] for v in runs.values()) +mean_points=(context_points+target_points)/rows +result=dict(seed=seed,seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False, + sampled_rows=rows,mean_finite_context_points=context_points/rows, + mean_finite_target_points=target_points/rows,mean_finite_points=mean_points, + selected_descriptor=manifest['checkpoint_sha256'],ancestral_runs=runs, + selected_ancestral_rows_before_sign_pairing=ancestral_rows, + fresh96000_batch48_rows=96000*48, + fresh96000_batch48_gross_observation_presentations_estimate=96000*48*mean_points, + note='Gross sampled presentations include overlapping/resampled windows and synthetic values, not unique observations. Ancestral run maxima count compute invested in different branches, including subtracted controls; they are not an equivalent single-model training trajectory. Sign pairing duplicates compute but not distinct sampled rows. No future training recipe is inferred from this audit alone.') +(R/'training_exposure_audit.json').write_text(json.dumps(result,indent=2)) +print(json.dumps({k:v for k,v in result.items() if k!='ancestral_runs'})) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/recovery/relaunch_20261022b.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/recovery/relaunch_20261022b.py new file mode 100644 index 0000000000000000000000000000000000000000..d16fc19cbbb86dba2ff53b445e368b8bbd2ca218 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/recovery/relaunch_20261022b.py @@ -0,0 +1,105 @@ +"""Resume interrupted research jobs and preserve phase-specific recovery receipts.""" +import datetime +import json +import os +from pathlib import Path +import shutil +import subprocess +import time + +R = Path('/workspace/research') +TAG = 'recovery2' +env = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1') +receipt = {'recovery_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(), + 'remaining_research_seconds_at_operator_recovery': 152594, + 'jobs': {}, 'queues': {}} +children = {} + +def launch(name, command, phase=TAG): + log = R / f'{name}_{phase}.log' + assert not log.exists(), log + with log.open('w') as f: + child = subprocess.Popen(command, stdout=f, stderr=subprocess.STDOUT, env=env) + children[name] = child + return {'pid': child.pid, 'command': command, 'log': str(log), 'started_monotonic': time.monotonic()} + +def persist(): + path = R / f'{TAG}_launch_receipt.json' + tmp = path.with_suffix('.tmp') + tmp.write_text(json.dumps(receipt, indent=2)); os.replace(tmp, path) + +for name in ['wide_capacity_146m_recovery', 'wide_capacity_control_recovery', + 'long_memory_synth_recovery', 'recent_normalization_recovery', 'wide_graft', 'patch8']: + run = R / 'runs' / name + cfg = json.loads((run / 'config.json').read_text()) + shutil.copy2(run / 'config.json', run / f'config_before_{TAG}.json') + command = ['python3', str(R / 'recovery/train.py')] + for key in ['code_dir', 'packed', 'source_weights_from', 'out', 'initialize_from', + 'initialize_ema', 'start_step', 'steps', 'batch', 'lr', 'seed', 'context', + 'sample_context', 'save_every', 'stop_file', 'reset_at', 'reset_seed', 'loss_mode']: + if cfg.get(key) is not None: + command += ['--' + key.replace('_', '-'), str(cfg[key])] + if (run / 'recovery.pt').exists(): + command += ['--resume', str(run / 'recovery.pt')] + mode = 'complete optimizer/EMA/RNG/prefetched-batch resume' + else: + mode = 'restart saved own initialization; no complete checkpoint existed' + if cfg.get('compile_loss'): + command += ['--compile-loss'] + command = ['env', 'TORCHINDUCTOR_COMPILE_THREADS=2', 'MAX_JOBS=2', + 'PYTHONPATH=/workspace/research/compiler_support', + 'TRITON_CACHE_MANAGER=sibling_cache:SiblingFileCacheManager', + 'TRITON_CACHE_DIR=/tmp/timeseries-triton-cache', + 'TORCHINDUCTOR_CACHE_DIR=/tmp/timeseries-inductor-cache'] + command + assert not Path(cfg['stop_file']).exists(), cfg['stop_file'] + receipt['jobs'][name] = dict(launch(name, command), mode=mode) + persist() + +watch_specs = { + 'wide_capacity_146m_recovery': ('wide_capacity_inference', '24000,32000'), + 'wide_capacity_control_recovery': ('wide_capacity_inference', '24000,32000'), + 'long_memory_synth_recovery': ('partial_targets_inference', '12000'), + 'recent_normalization_recovery': ('recent_normalization_inference', '12000'), + 'wide_graft': ('wide_graft_inference', '4000,8000,12000,16000,24000,32000'), + 'patch8': ('full_paired_inference', '1000,3000,6000,12000'), + 'volatility_synth': ('partial_targets_inference', '3000,6000,12000'), + 'postloss': ('full_paired_inference', '1000,3000,6000,12000'), + 'paired_long_memory': ('full_paired_inference', '1000,3000,6000,12000'), +} +for name, (runtime, steps) in watch_specs.items(): + command = ['python3', str(R / 'watch_evaluate.py'), '--run', str(R / 'runs' / name), + '--evaluator', str(R / runtime / 'evaluate.py'), '--name', name, '--steps', steps] + launch(name + '_watch', command) + +queue_specs = {'volatility_synth': 'long_memory_synth_recovery', + 'postloss': 'recent_normalization_recovery', + 'paired_long_memory': 'wide_capacity_control_recovery'} +for name, dependency in queue_specs.items(): + old = json.loads((R / (name + '_queue.json')).read_text()) + shutil.copy2(R / (name + '_queue.json'), R / (name + '_queue_before_' + TAG + '.json')) + receipt['queues'][name] = dict(old, dependency=dependency, status='waiting', + wait_pids=[children[dependency].pid]) +persist() + +while True: + for name, job in receipt['jobs'].items(): + if 'returncode' not in job and children[name].poll() is not None: + job.update(returncode=children[name].returncode, + phase_seconds=time.monotonic() - job['started_monotonic']) + persist() + for name, queue in receipt['queues'].items(): + if queue['status'] == 'waiting' and children[queue['dependency']].poll() is not None: + if children[queue['dependency']].returncode != 0 or not all(Path(p).exists() for p in queue['required_checkpoints']): + queue['status'] = 'blocked_by_incomplete_dependency' + else: + receipt['jobs'][name] = launch(name, queue['command']) + queue.update(status='running', pid=children[name].pid, + started_utc=datetime.datetime.now(datetime.timezone.utc).isoformat()) + with (R / 'direct_v1/EXPERIMENTS.md').open('a') as f: + f.write(f'\n{name} started {queue["started_utc"]} after {queue["dependency"]} completed. Original predeclared settings and seed retained.\n') + (R / (name + '_queue.json')).write_text(json.dumps(queue, indent=2)) + persist() + if all(p.poll() is not None for n,p in children.items() if not n.endswith('_watch')) and all(q['status'] != 'waiting' for q in receipt['queues'].values()): + break + time.sleep(5) +persist() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/recovery/relaunch_20261023.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/recovery/relaunch_20261023.py new file mode 100644 index 0000000000000000000000000000000000000000..5f35a9cfcbe7ea66c8837b6d4ada8b84be36b934 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/recovery/relaunch_20261023.py @@ -0,0 +1,104 @@ +"""Resume interrupted research jobs and preserve phase-specific recovery receipts.""" +import datetime +import json +import os +from pathlib import Path +import shutil +import subprocess +import time + +R = Path('/workspace/research') +TAG = 'recovery3' +env = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1') +receipt = {'recovery_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(), + 'remaining_research_seconds_at_operator_recovery': 151596, + 'jobs': {}, 'queues': {}} +children = {} + +def launch(name, command, phase=TAG): + log = R / f'{name}_{phase}.log' + assert not log.exists(), log + with log.open('w') as f: + child = subprocess.Popen(command, stdout=f, stderr=subprocess.STDOUT, env=env) + children[name] = child + return {'pid': child.pid, 'command': command, 'log': str(log), 'started_monotonic': time.monotonic()} + +def persist(): + path = R / f'{TAG}_launch_receipt.json' + tmp = path.with_suffix('.tmp') + tmp.write_text(json.dumps(receipt, indent=2)); os.replace(tmp, path) + +for name in ['wide_capacity_146m_recovery', 'wide_capacity_control_recovery', + 'long_memory_synth_recovery', 'wide_graft', 'patch8']: + run = R / 'runs' / name + cfg = json.loads((run / 'config.json').read_text()) + shutil.copy2(run / 'config.json', run / f'config_before_{TAG}.json') + command = ['python3', str(R / 'recovery/train.py')] + for key in ['code_dir', 'packed', 'source_weights_from', 'out', 'initialize_from', + 'initialize_ema', 'start_step', 'steps', 'batch', 'lr', 'seed', 'context', + 'sample_context', 'save_every', 'stop_file', 'reset_at', 'reset_seed', 'loss_mode']: + if cfg.get(key) is not None: + command += ['--' + key.replace('_', '-'), str(cfg[key])] + if (run / 'recovery.pt').exists(): + command += ['--resume', str(run / 'recovery.pt')] + mode = 'complete optimizer/EMA/RNG/prefetched-batch resume' + else: + mode = 'restart saved own initialization; no complete checkpoint existed' + if cfg.get('compile_loss'): + command += ['--compile-loss'] + command = ['env', 'TORCHINDUCTOR_COMPILE_THREADS=2', 'MAX_JOBS=2', + 'PYTHONPATH=/workspace/research/compiler_support', + 'TRITON_CACHE_MANAGER=sibling_cache:SiblingFileCacheManager', + 'TRITON_CACHE_DIR=/tmp/timeseries-triton-cache', + 'TORCHINDUCTOR_CACHE_DIR=/tmp/timeseries-inductor-cache'] + command + assert not Path(cfg['stop_file']).exists(), cfg['stop_file'] + receipt['jobs'][name] = dict(launch(name, command), mode=mode) + persist() + +watch_specs = { + 'wide_capacity_146m_recovery': ('wide_capacity_inference', '24000,32000'), + 'wide_capacity_control_recovery': ('wide_capacity_inference', '24000,32000'), + 'long_memory_synth_recovery': ('partial_targets_inference', '12000'), + 'recent_normalization_recovery': ('recent_normalization_inference', '12000'), + 'wide_graft': ('wide_graft_inference', '4000,8000,12000,16000,24000,32000'), + 'patch8': ('full_paired_inference', '1000,3000,6000,12000'), + 'volatility_synth': ('partial_targets_inference', '3000,6000,12000'), + 'postloss': ('full_paired_inference', '1000,3000,6000,12000'), + 'paired_long_memory': ('full_paired_inference', '1000,3000,6000,12000'), +} +for name, (runtime, steps) in watch_specs.items(): + command = ['python3', str(R / 'watch_evaluate.py'), '--run', str(R / 'runs' / name), + '--evaluator', str(R / runtime / 'evaluate.py'), '--name', name, '--steps', steps] + launch(name + '_watch', command) + +queue_specs = {'volatility_synth': 'long_memory_synth_recovery', + 'paired_long_memory': 'wide_capacity_control_recovery'} +for name, dependency in queue_specs.items(): + old = json.loads((R / (name + '_queue.json')).read_text()) + shutil.copy2(R / (name + '_queue.json'), R / (name + '_queue_before_' + TAG + '.json')) + receipt['queues'][name] = dict(old, dependency=dependency, status='waiting', + wait_pids=[children[dependency].pid]) +persist() + +while True: + for name, job in receipt['jobs'].items(): + if 'returncode' not in job and children[name].poll() is not None: + job.update(returncode=children[name].returncode, + phase_seconds=time.monotonic() - job['started_monotonic']) + persist() + for name, queue in receipt['queues'].items(): + if queue['status'] == 'waiting' and children[queue['dependency']].poll() is not None: + if children[queue['dependency']].returncode != 0 or not all(Path(p).exists() for p in queue['required_checkpoints']): + queue['status'] = 'blocked_by_incomplete_dependency' + else: + receipt['jobs'][name] = launch(name, queue['command']) + queue.update(status='running', pid=children[name].pid, + started_utc=datetime.datetime.now(datetime.timezone.utc).isoformat()) + with (R / 'direct_v1/EXPERIMENTS.md').open('a') as f: + f.write(f'\n{name} started {queue["started_utc"]} after {queue["dependency"]} completed. Original predeclared settings and seed retained.\n') + (R / (name + '_queue.json')).write_text(json.dumps(queue, indent=2)) + persist() + if all(p.poll() is not None for n,p in children.items() if not n.endswith('_watch')) and all(q['status'] != 'waiting' for q in receipt['queues'].values()): + break + time.sleep(5) +persist() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/recovery/schedules.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/recovery/schedules.py new file mode 100644 index 0000000000000000000000000000000000000000..4c8378f374144b802d2cd5a98afd71efc1ba0a4c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/recovery/schedules.py @@ -0,0 +1,13 @@ +"""Explicit training-only learning-rate schedules; default arithmetic unchanged.""" +import math + + +def learning_rate(step, steps, peak, reset_at=-1, anneal_from_step=None, + anneal_from_lr=None, anneal_final_lr=None): + if anneal_from_step is not None: + assert steps > anneal_from_step + assert 0 < anneal_final_lr <= anneal_from_lr + progress=max(0.,min(1.,(step-anneal_from_step)/(steps-anneal_from_step))) + return anneal_final_lr+.5*(anneal_from_lr-anneal_final_lr)*(1+math.cos(math.pi*progress)) + warm_step=step-reset_at if reset_at>=0 and step>reset_at else step + return peak*min(1,warm_step/400)*(.2+.4*(1+math.cos(math.pi*step/steps))) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/recovery/snapshot.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/recovery/snapshot.py new file mode 100644 index 0000000000000000000000000000000000000000..11ce27e43477f9c685cefeaa5f36e53c59634505 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/recovery/snapshot.py @@ -0,0 +1,99 @@ +"""Write a compact authoritative research recovery index without touching training state.""" +import datetime +import json +import os +from pathlib import Path + +R=Path('/workspace/research');p=R/'CURRENT_RESEARCH_STATE.json' +s=json.loads(p.read_text()) +s['snapshot_utc']=datetime.datetime.now(datetime.timezone.utc).isoformat() +receipt=json.loads((R/'recovery3_launch_receipt.json').read_text()) +s['runs']={} +for name,job in receipt['jobs'].items(): + run=R/'runs'/name + log=Path(job['log']) + records=[] + for line in log.read_text().splitlines(): + try: + record=json.loads(line) + if 'step' in record or 'completed_step' in record:records.append(record) + except json.JSONDecodeError:pass + s['runs'][name]={'config':json.loads((run/'config.json').read_text()) if (run/'config.json').exists() else None, + 'last_phase_record':records[-1] if records else None, + 'phase_log':str(log),'supervisor_receipt':str(R/'recovery3_launch_receipt.json'), + 'latest_saved_ema':str(max(run.glob('ema*.pt'))) if list(run.glob('ema*.pt')) else None, + 'complete_recovery_checkpoint':str(run/'recovery.pt') if (run/'recovery.pt').exists() else None, + 'pid_at_snapshot':job['pid'],'returncode':job.get('returncode'), + 'note':'Check actual live process and checkpoint state before resuming; this is only a snapshot.'} +s['queues']={name:{'status':q['status'],'dependency':q['dependency'],'command':q['command'], + 'required_checkpoints':q['required_checkpoints']} + for name,q in receipt['queues'].items()} +s.pop('prepared_not_launched',None) +s['deferred_unqueued']={'E72':'temporal_mixup, prepared and checked but not queued','ideas':'RESEARCH_IDEAS.md, no jobs attached'} +s['completed_since_previous_recovery']={ + 'E67_control12000':{'skill':.37724286394256845,'training_loop_seconds':2794.8358458959847}, + 'E67_paired12000':{'skill':.377427077277383,'training_loop_seconds':2794.867385860998}, + 'E63_expanded146M':'Stopped8501, complete recovery retained; allocation moved to E73; inconclusive data scaling', + 'E61_slowAR':'Complete12000; E76 used6000 correction, final transfer rejected', + 'E65_recent_normalization':'Complete12000; E81 equal ensemble rejected', + 'E58_small_control':'Complete32000', + 'E58_wide146M':'Complete32000; no gain over37Mcontrol; do not resume', + 'E71_patch8':'Complete12000; selected6000 used in E87/E96/E102 ensembles', + 'E69_volatility':'Complete12000; final below matched control; no transfer', + 'E89_patch8_control':'Complete12000; final0.380847096,loop2729.052105s; selected starting E71parent remains stronger', + 'E89_fullpatch4':'Complete12000,main0.381640078; E96 used6000, E103final cached alternative mixed; loop5066.016522s', + 'E93_split_patch':'Complete12000,main0.381711986; selected final is E102 published thirdmember; loop3153.565149s', + 'E92_robust_normalization':'Complete12000,final0.377099312 belowcontrol; rejected;E97started', + 'E90_metric_scale':'Complete12000; final0.377373344 ties/slightly trailsE80; no selection; loop2702.166704s', + 'E84_coarse':'Complete12000; daily gain but weekly regression; not selected', + 'E88_late_patch8_slowAR':'Complete12000; small9k gain lost atfinal; rejected', + 'E80_overflow':'Complete12000; finaltiesoriginal; selected3k compositeE91rejected', + 'E78_multiscaleAR':'Complete12000; no gain over single slowAR', + 'E86_protected_graft':'Complete8000; below own initialization; no publication', + 'E75_postloss':'Stopped3653 deliberately; immutable snapshot retained; E98 separately declared completion active in another output, original stopfile remains', + 'E73_independent_graft':'Stopped8683 after negative8000; replaced by E86; stopfile remains', + 'E95_stratified_corpus':'Complete12000,final0.377983250,earliermixed; E105collision destroyed only1000weights and optimizer recovery;2k..12k preserved; do not resume', + 'E97_weekly_synth':'Complete12000,final0.380439539; E112final weekly correction now published; loop2600.472750s', + 'E105_stratified_volume':'Complete12000,final0.377529200,earlier0.336713522/0.359535697/0.390349158 mixed; corrected continuationloop2013.982814s plus original incident phase', + 'E106_spectral_synth':'Complete12000,final0.377641399,earlier0.337647555/0.361626447/0.385497870, average matched gap negligible; loop2206.272278s; E114fixed6000transfers in selection', + 'E98_postloss_completion':'Complete12000,final0.376034254 below3000 andcontrol; rejected,loop1995.386513s', + 'E99_early_cooldown':'Complete36000,final0.363306598 trails original36k0.364859034; rejected,loop1603.635706s', + 'E77_pairedslowAR':'Complete12000;6000 strongest main/earlier comparison'} +s['external_receipts']=[str(R/'postloss_recovery3_receipt.json'),str(R/'random_capacity_512_queue.json'),str(R/'random_capacity_1024_queue.json'),str(R/'multiscale_ar_queue.json'),str(R/'overflow_control_queue.json'),str(R/'coarse_aggregate_queue.json'),str(R/'patch8_long_memory_queue.json'),str(R/'wide_graft_frozen_queue.json'),str(R/'patch4_candidate_queue.json'),str(R/'patch4_control_queue.json'),str(R/'metric_scale_queue.json'),str(R/'robust_normalization_queue.json'),str(R/'split_patch_queue.json'),str(R/'random_capacity_1024_halflr_queue.json'),str(R/'stratified_corpus_queue.json'),str(R/'weekly_synth_queue.json'),str(R/'postloss_completion_queue.json'),str(R/'random_capacity_512_anneal_queue.json'),str(R/'distill_ensemble_queue.json'),str(R/'stratified_volume_queue.json'),str(R/'spectral_synth_queue.json'),str(R/'long_seasonal_queue.json'),str(R/'random_capacity_full_queue.json'),str(R/'weekly_replication_control_queue.json'),str(R/'weekly_replication_candidate_queue.json'),str(R/'lowfreq_windows_queue.json'),str(R/'phase_joint_queue.json')] +queue_pids={'random_capacity_512_queue.json':965,'random_capacity_1024_queue.json':967, + 'multiscale_ar_queue.json':1678,'overflow_control_queue.json':1676, + 'coarse_aggregate_queue.json':3086,'patch8_long_memory_queue.json':3739, + 'wide_graft_frozen_queue.json':3931,'patch4_candidate_queue.json':4078, + 'patch4_control_queue.json':4080} +s['external_jobs']={} +for receipt_name in s['external_receipts']: + receipt_path=Path(receipt_name) + if not receipt_path.exists():continue + item=json.loads(receipt_path.read_text());command=item.get('command',[]) + if '--out' not in command:continue + run=Path(command[command.index('--out')+1]);log=Path(item.get('log',str(receipt_path).replace('_queue.json','_train.log'))) + last=None + if log.exists(): + for line in log.read_text().splitlines(): + try: + record=json.loads(line) + if isinstance(record,dict) and ('step' in record or 'completed_step' in record):last=record + except json.JSONDecodeError:pass + queue_pid=item.get('launcher_pid',queue_pids.get(receipt_path.name)) + children_file=Path(f'/proc/{queue_pid}/task/{queue_pid}/children') if queue_pid else None + children=list(map(int,children_file.read_text().split())) if children_file and children_file.exists() else [] + checkpoints=list(run.glob('ema*.pt')) + s['external_jobs'][run.name]={'receipt':str(receipt_path),'status':item.get('status'), + 'queue_pid_at_snapshot':queue_pid,'child_pids_at_snapshot':children, + 'last_phase_record':last,'log':str(log), + 'latest_saved_ema':str(max(checkpoints)) if checkpoints else None, + 'complete_recovery_checkpoint':str(run/'recovery.pt') if (run/'recovery.pt').exists() else None, + 'command':command,'note':'PIDs are only a snapshot; check actual processes and serialized state before recovery.'} +s['compiler_environment']={'OPENBLAS_NUM_THREADS':'1','OMP_NUM_THREADS':'1','TORCHINDUCTOR_COMPILE_THREADS':'2','MAX_JOBS':'2','PYTHONPATH':str(R/'compiler_support'),'TRITON_CACHE_MANAGER':'sibling_cache:SiblingFileCacheManager','TRITON_CACHE_DIR':'/tmp/timeseries-triton-cache','TORCHINDUCTOR_CACHE_DIR':'/tmp/timeseries-inductor-cache'} +for job in s['external_jobs'].values(): + job['environment']=s['compiler_environment'] if '--compile-loss' in job['command'] else {'OPENBLAS_NUM_THREADS':'1','OMP_NUM_THREADS':'1'} +s['compiler_cache_backup']=str(R/'compiler_cache_backup') +for stale in ['pending','pending_actions','active_experiments','next_experiments','prepared_experiments']: + s.pop(stale,None) +tmp=p.with_suffix('.tmp');tmp.write_text(json.dumps(s,indent=2));os.replace(tmp,p) +print(s['snapshot_utc']) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/recovery/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/recovery/train.py new file mode 100644 index 0000000000000000000000000000000000000000..536677ab542342e8e9b56298e5ddb7cb2983a258 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/recovery/train.py @@ -0,0 +1,201 @@ +"""Resumable continuation of our existing permitted-corpus experiments.""" +import argparse,copy,fcntl,inspect,json,math,os,sys,time +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import numpy as np +import torch + +ap=argparse.ArgumentParser() +ap.add_argument('--code-dir',required=True);ap.add_argument('--packed',required=True) +ap.add_argument('--source-weights-from');ap.add_argument('--out',required=True) +ap.add_argument('--initialize-from',required=True);ap.add_argument('--initialize-ema') +ap.add_argument('--start-step',type=int,default=0);ap.add_argument('--resume') +ap.add_argument('--steps',type=int,required=True);ap.add_argument('--batch',type=int,required=True) +ap.add_argument('--lr',type=float,required=True);ap.add_argument('--seed',type=int,required=True) +ap.add_argument('--context',type=int);ap.add_argument('--sample-context',type=int,default=4096) +ap.add_argument('--save-every',type=int,default=1000);ap.add_argument('--stop-file') +ap.add_argument('--recovery-every',type=int,default=250) +ap.add_argument('--halt-after',type=int) +ap.add_argument('--loss-mode',choices=['individual','paired']) +ap.add_argument('--compile-loss',action='store_true') +ap.add_argument('--reset-at',type=int,default=-1);ap.add_argument('--reset-seed',type=int,default=179) +ap.add_argument('--anneal-from-step',type=int);ap.add_argument('--anneal-from-lr',type=float) +ap.add_argument('--anneal-final-lr',type=float) +ap.add_argument('--teacher-package');ap.add_argument('--teacher-coefficient',type=float) +a=ap.parse_args() +# Hold a process-lifetime lock before loading a model or touching GPU state. +_run_out=Path(a.out);_run_out.mkdir(parents=True,exist_ok=True) +_run_lock=open(_run_out/'.training.lock','a') +try:fcntl.flock(_run_lock,fcntl.LOCK_EX|fcntl.LOCK_NB) +except BlockingIOError:raise SystemExit('Another trainer already owns this output directory: '+str(_run_out)) +if not a.resume: + _saved=list(_run_out.glob('ema*.pt'))+list(_run_out.glob('step*.pt')) + if (_run_out/'recovery.pt').exists():_saved.append(_run_out/'recovery.pt') + if _saved: + raise SystemExit('Refusing fresh training into an output with saved checkpoints; use a new directory or explicit --resume: '+str(_run_out)) +sys.path.insert(0,a.code_dir) +from model import DirectForecaster,loss_fn +from data import Sampler +from schedules import learning_rate +torch.set_num_threads(2);torch.manual_seed(a.seed);torch.backends.cuda.matmul.allow_tf32=True +out=Path(a.out);out.mkdir(parents=True,exist_ok=True);a.trainable_scope='all' +if Path(a.code_dir).name in ('long_memory_synth','paired_long_memory','multiscale_ar','random_capacity','patch8_long_memory','distill_ensemble'):a.synthetic_ar_time_constants=[1,10000] +if Path(a.code_dir).name in ('full_paired','patch8','temporal_mixup','postloss','paired_long_memory','multiscale_ar','random_capacity','overflow_control','coarse_aggregate','patch8_long_memory','patch4','metric_scale','robust_normalization','split_patch','weekly_synth','distill_ensemble'):a.requested_horizon_seed=a.seed+300003 +if Path(a.code_dir).name=='multiscale_ar': + a.synthetic_ar_components=4;a.multiscale_ar_seed=a.seed+700003 +if Path(a.code_dir).name=='volatility_synth':a.stochastic_volatility_seed=a.seed+500003 +if Path(a.code_dir).name=='coarse_aggregate': + a.coarse_aggregation_seed=a.seed+900003;a.coarse_aggregation_probability=.2;a.coarse_aggregation_frequencies=['D','W'] +if Path(a.code_dir).name=='temporal_mixup':a.temporal_mixup_seed=a.seed+600003 +if Path(a.code_dir).name=='postloss': + a.fixed_postprocessing_loss=True;a.normalization_overflow_fallback=True +if Path(a.code_dir).name in ('overflow_control','metric_scale','random_capacity','weekly_synth','distill_ensemble'):a.normalization_overflow_fallback=True +if Path(a.code_dir).name=='weekly_synth': + a.weekly_synthetic_seed=a.seed+1000003;a.weekly_replacement_probability=1/11 +if Path(a.code_dir).name=='spectral_synth': + a.spectral_synthetic_seed=a.seed+1100003;a.spectral_replacement_probability=.5 + a.spectral_length_scale=[1,10000];a.spectral_families=['Matern0.5','Matern1.5','Matern2.5','RBF'] + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True +if Path(a.code_dir).name in ('long_seasonal','phase_joint'): + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True +if Path(a.code_dir).name=='lowfreq_windows': + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True + a.lowfreq_window_seed=a.seed+1200003;a.lowfreq_window_probability=.5 + a.lowfreq_window_rule='period2=1,period1<=52;finite-target endpoint;log-uniform horizon4..min(H,max(8,2p),span-8) with available-length fallback;context cap min(C,max(64,32p));at least4finite history' +if Path(a.code_dir).name=='metric_scale':a.loss_seasonality='lag1 for exact daily[7,365] and weekly[52,1] period pairs; unchanged otherwise' +if Path(a.code_dir).name=='robust_normalization':a.normalization_kind='finite median plus/minus6 mean absolute deviations winsorized mean/RMS, float64; original normalized history clipped30' +if Path(a.code_dir).name=='wide_graft_frozen':a.trainable_scope='new feature stream and cross-stream blocks; inherited parameter blocks frozen' +ck=torch.load(a.resume or a.initialize_from,map_location='cpu',weights_only=False) +# Keep immutable branch ancestry across a later restart from this run's own recovery. +lineage_parents=list(ck.get('parent_checkpoints',[])) +if a.initialize_ema:lineage_parents.append(a.initialize_ema) +if a.resume and Path(a.resume).parent.resolve()!=out.resolve():lineage_parents.append(a.resume) +previous_args=ck.get('args',{}) +previous_resume=previous_args.get('resume') +if previous_resume and Path(previous_resume).parent.resolve()!=Path(previous_args.get('out',a.out)).resolve(): + lineage_parents.append(previous_resume) +lineage_parents=list(dict.fromkeys(lineage_parents)) +config=dict(ck['config']) +if a.context:config['max_context']=a.context +model=DirectForecaster(**config).cuda();model.load_state_dict(ck['model']) +teacher=None +if Path(a.code_dir).name=='distill_ensemble': + assert a.teacher_package and a.teacher_coefficient is not None +if a.teacher_package: + assert Path(a.code_dir).name=='distill_ensemble' + from teacher import OwnEnsembleTeacher + with torch.random.fork_rng(devices=[torch.cuda.current_device()]): + teacher=OwnEnsembleTeacher(a.teacher_package) + if ck.get('args',{}).get('teacher_descriptor_sha256'): + assert ck['args']['teacher_descriptor_sha256']==teacher.descriptor_sha256 + assert ck['args']['teacher_coefficient']==a.teacher_coefficient + a.teacher_descriptor_sha256=teacher.descriptor_sha256 + a.teacher_checkpoint_sha256=teacher.member_hashes + a.teacher_target_kind='equal average of own frozen E96 raw normalized sign-paired neural quantiles, before postprocessing' + +protector=None +if Path(a.code_dir).name=='wide_graft_frozen': + from frozen import FreezeInherited + protector=FreezeInherited(model) + a.protected_parameters=protector.inherited_numel +if a.compile_loss: + torch._dynamo.config.recompile_limit=64 + objective=torch.compile(loss_fn,fullgraph=True,dynamic=False) +else:objective=loss_fn +multipliers=ck.get('lr_multipliers',{}) +def optimizer(): + groups=[] + for mult in sorted(set(multipliers.values())|{1.}): + params=[p for n,p in model.named_parameters() if multipliers.get(n,1.)==mult] + if params:groups.append({'params':params,'lr':a.lr*mult,'lr_multiplier':mult,'weight_decay':.05/mult}) + return torch.optim.AdamW(groups,betas=(.9,.95),fused=True) +opt=optimizer() +if a.resume: + start_step=ck['step'];opt.load_state_dict(ck['optimizer']) + ema={k:v.cuda() for k,v in ck['ema_state'].items()} +else: + start_step=a.start_step + ema_ck=torch.load(a.initialize_ema,map_location='cpu',weights_only=False) if a.initialize_ema else ck + ema={k:v.cuda().clone() for k,v in ema_ck['model'].items()} +del ck +def make_sampler(seed): + kwargs={'seed':seed} + if 'source_weights_from' in inspect.signature(Sampler).parameters:kwargs['source_weights_from']=a.source_weights_from + return Sampler(a.packed,**kwargs),np.random.default_rng(seed) +stream_seed=a.reset_seed if a.reset_at>=0 and start_step>=a.reset_at else a.seed +sampler,rng=make_sampler(stream_seed) +def next_batch(): + c=int(rng.choice([512,1024,2048,a.sample_context],p=[.1,.15,.35,.4])) + h=int(rng.choice([32,128,512,1024],p=[.1,.2,.2,.5])) + x,y,p=sampler.sample(a.batch,c,h) + return x[:,-model.max_context:].copy(),y,p +pool=ThreadPoolExecutor(1) +if a.resume: + recovery=torch.load(a.resume,map_location='cpu',weights_only=False) + rng.bit_generator.state=recovery['batch_rng_state'];sampler.rng.bit_generator.state=recovery['sampler_rng_state'] + for name,state in recovery.get('sampler_rng_states',{}).items():getattr(sampler,name).bit_generator.state=state + torch.set_rng_state(recovery['torch_rng_state']);torch.cuda.set_rng_state_all(recovery['cuda_rng_state']) + pending=recovery['prefetched_batch'];del recovery + future=pool.submit(lambda:pending) +else:future=pool.submit(next_batch) +parameters=sum(p.numel() for p in model.parameters()) +(out/'config.json').write_text(json.dumps({**vars(a),'model':model.config,'parameters':parameters},indent=2)) +print(json.dumps({'parameters':parameters,'starting_step':start_step,'stream_seed':stream_seed,'restored_complete_training_state':bool(a.resume)}),flush=True) +started=time.monotonic();losses=[] +def atomic_save(obj,path): + torch.save(obj,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) +def save(step,include_selection_weights=True): + global future + pending_batch=future.result() + common={'config':model.config,'step':step,'args':vars(a),'lr_multipliers':multipliers, + 'parent_checkpoints':list(dict.fromkeys(lineage_parents+(teacher.checkpoints if teacher else [])))} + if include_selection_weights: + for prefix,state in [('step',model.state_dict()),('ema',ema)]: + atomic_save({**common,'model':state,'ema':prefix=='ema'},out/f'{prefix}{step:06d}.pt') + atomic_save({**common,'model':model.state_dict(),'optimizer':opt.state_dict(),'ema_state':ema, + 'prefetched_batch':pending_batch,'batch_rng_state':copy.deepcopy(rng.bit_generator.state), + 'sampler_rng_state':copy.deepcopy(sampler.rng.bit_generator.state), + 'sampler_rng_states':{name:copy.deepcopy(value.bit_generator.state) for name,value in vars(sampler).items() if isinstance(value,np.random.Generator)}, + 'torch_rng_state':torch.get_rng_state(),'cuda_rng_state':torch.cuda.get_rng_state_all()},out/'recovery.pt') + future=pool.submit(lambda:pending_batch) +for step in range(start_step+1,a.steps+1): + if a.reset_at>=0 and step==a.reset_at+1 and start_step=a.halt_after) + selection_checkpoint=step%a.save_every==0 or step==a.steps or stop + # Persist a complete state before a fresh/resumed job warms its remaining compiled shapes. + if selection_checkpoint or step%a.recovery_every==0 or step==start_step+1: + save(step,include_selection_weights=selection_checkpoint) + if stop:break +pool.shutdown() +print(json.dumps({'completed_step':step,'training_process_loop_seconds':time.monotonic()-started}),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/spectral_synth/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/spectral_synth/check.py new file mode 100644 index 0000000000000000000000000000000000000000..18b155db82902843efdf6df4164d5ed87f249a47 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/spectral_synth/check.py @@ -0,0 +1,79 @@ +"""Check spectral covariance and unchanged control streams without validation data.""" +import copy +import hashlib +import importlib.util +import json +import sys +import time +from pathlib import Path + +import numpy as np + +R = Path('/workspace/research') +sys.path.insert(0, str(R / 'spectral_synth')) +from data import Sampler +from spectral import gaussian_residual, spectral_density + +spec = importlib.util.spec_from_file_location('spectral_control_data', R / 'overflow_control/data.py') +control_code = importlib.util.module_from_spec(spec) +spec.loader.exec_module(control_code) +started = time.monotonic() +seed = 499 +candidate = Sampler(R / 'packed_sample', seed=seed, source_weights_from=R / 'packed_sample') +control = control_code.Sampler(R / 'packed_sample', seed=seed, source_weights_from=R / 'packed_sample') +rng = np.random.default_rng(seed) +rows = synthetic_rows = replaced_rows = 0 +for _ in range(120): + c = int(rng.choice([512, 1024, 2048, 4096])) + h = int(rng.choice([32, 128, 512, 1024])) + expected = control.sample(64, c, h) + actual = candidate.sample(64, c, h) + replacements = np.array(candidate.last_spectral_rows, dtype=int) + unchanged = np.ones(64, dtype=bool) + unchanged[replacements] = False + for x, y in zip(expected, actual): + assert np.array_equal(x[unchanged], y[unchanged], equal_nan=True) + assert set(replacements) <= set(candidate.last_synthetic_rows) + assert np.array_equal(expected[2], actual[2]) + for x, y in zip(expected[:2], actual[:2]): + assert np.array_equal(np.isfinite(x), np.isfinite(y)) + assert candidate.rng.bit_generator.state == control.rng.bit_generator.state + assert candidate.horizon_rng.bit_generator.state == control.horizon_rng.bit_generator.state + rows += 64 + synthetic_rows += len(candidate.last_synthetic_rows) + replaced_rows += len(replacements) +sampler_seconds = time.monotonic() - started +states = {n: copy.deepcopy(v.bit_generator.state) for n, v in vars(candidate).items() + if isinstance(v, np.random.Generator)} +next_batch = candidate.sample(64, 4096, 1024) +for name, state in states.items(): + getattr(candidate, name).bit_generator.state = state +replayed = candidate.sample(64, 4096, 1024) +assert all(np.array_equal(x, y, equal_nan=True) for x, y in zip(next_batch, replayed)) + +covariances = [] +for family in range(4): + values = np.stack([gaussian_residual(512, rng, length_scale=8, family=family) + for _ in range(1024)]) + expected = np.fft.irfft(spectral_density(2048, 8, family), n=2048) + observed = [float(np.mean(values * values))] + observed += [float(np.mean(values[:, lag:] * values[:, :-lag])) for lag in [1, 8, 32]] + wanted = expected[[0, 1, 8, 32]] + assert np.max(np.abs(np.array(observed) - wanted)) < .045 + covariances.append(dict(family=family, observed=observed, theoretical=wanted.tolist())) +for family in range(4): + for n in [8, 40, 5120]: + for scale in [1., 1e4]: + assert np.isfinite(gaussian_residual(n, rng, scale, family)).all() +model_hash = hashlib.sha256((R / 'spectral_synth/model.py').read_bytes()).hexdigest() +assert model_hash == hashlib.sha256((R / 'overflow_control/model.py').read_bytes()).hexdigest() +result = dict(seed=seed, rows=rows, original_synthetic_rows=synthetic_rows, + replaced_spectral_rows=replaced_rows, probability=.5, + original_and_horizon_rng_bitwise_preserved=True, + unmodified_rows_bitwise_preserved=True, periods_and_finite_masks_unchanged=True, + all_numpy_rng_recovery_exact=True, model_sha256=model_hash, + model_bitwise_unchanged=True, covariance_checks=covariances, + sampler_comparison_seconds=sampler_seconds, seconds=time.monotonic()-started, + optimizer_updates=0, validation_data_read=False) +(R / 'spectral_synth_checks.json').write_text(json.dumps(result, indent=2)) +print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/spectral_synth/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/spectral_synth/data.py new file mode 100644 index 0000000000000000000000000000000000000000..bf91f33740715be702c2772f3cca89b656cea4dc --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/spectral_synth/data.py @@ -0,0 +1,102 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq +from spectral import gaussian_residual + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + if self.spectral_rng.random()8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + self.spectral_rng=np.random.default_rng(seed+1100003) + self.spectral_probability=.5 + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/spectral_synth/launch.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/spectral_synth/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..0134693b620294a3fb18eed15e107d649a0cc487 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/spectral_synth/launch.py @@ -0,0 +1,29 @@ +"""Queue spectral synthetic residuals after postloss completion finishes.""" +def main(): + import json + import os + import subprocess + from pathlib import Path + R=Path('/workspace/research') + checks=json.loads((R/'spectral_synth_checks.json').read_text()) + assert checks['original_and_horizon_rng_bitwise_preserved'] and checks['unmodified_rows_bitwise_preserved'] + assert checks['all_numpy_rng_recovery_exact'] and checks['model_bitwise_unchanged'] + env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1') + command=['python3',str(R/'recovery/train.py'),'--code-dir',str(R/'spectral_synth'), + '--packed',str(R/'packed_sample'),'--source-weights-from',str(R/'packed_sample'), + '--out',str(R/'runs/spectral_synth'),'--initialize-from',str(R/'horizon_delta12k.pt'), + '--steps','12000','--batch','64','--lr','.00002','--seed','197','--loss-mode','paired', + '--stop-file',str(R/'spectral_synth.stop')] + with (R/'spectral_synth_queue.log').open('w') as qlog,(R/'spectral_synth_watch.log').open('w') as wlog: + queued=subprocess.Popen(['python3',str(R/'queued_train.py'),'--label','E106 spectral synthetic residuals seed197', + '--log',str(R/'spectral_synth_train.log'),'--receipt',str(R/'spectral_synth_queue.json'), + '--wait-pid','10664','--require-checkpoint',str(R/'runs/postloss_completion/recovery.pt'), + '--',*command],stdout=qlog,stderr=subprocess.STDOUT,env=env) + watch=subprocess.Popen(['python3',str(R/'watch_evaluate.py'),'--run',str(R/'runs/spectral_synth'), + '--evaluator',str(R/'postloss_inference/evaluate.py'),'--name','spectral_synth', + '--expected-packed',str(R/'packed_sample'),'--steps','1000,3000,6000,12000'],stdout=wlog,stderr=subprocess.STDOUT,env=env) + print({'queue_pid':queued.pid,'watch_pid':watch.pid},flush=True) + result=queued.wait() + if result:watch.terminate() + watch.wait();raise SystemExit(result) +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/spectral_synth/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/spectral_synth/model.py new file mode 100644 index 0000000000000000000000000000000000000000..3532e5063bd8b5013f6b6e35703707ffef66e00b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/spectral_synth/model.py @@ -0,0 +1,213 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/spectral_synth/spectral.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/spectral_synth/spectral.py new file mode 100644 index 0000000000000000000000000000000000000000..f7358c3ec944849ea619ef2e73697775b48d408c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/spectral_synth/spectral.py @@ -0,0 +1,27 @@ +"""Locally generated finite stationary Gaussian fields with varied smoothness.""" +import numpy as np + + +def spectral_density(size, length_scale, family): + omega = 2 * np.pi * np.fft.rfftfreq(size) + if family == 3: + density = np.exp(-.5 * (length_scale * omega) ** 2) + else: + nu = [.5, 1.5, 2.5][family] + density = (1 + (length_scale * omega) ** 2 / (2 * nu)) ** (-nu - .5) + # Real FFT has one DC and one Nyquist coefficient, two of each interior bin. + variance = (density[0] + density[-1] + 2 * density[1:-1].sum()) / size + return density / variance + + +def gaussian_residual(n, rng, length_scale=None, family=None): + """The covariance is the discrete inverse Fourier transform of the declared PSD.""" + if length_scale is None: + length_scale = 10 ** rng.uniform(0, 4) + if family is None: + family = int(rng.integers(4)) + size = 1 << (max(16, 4 * n) - 1).bit_length() + density = spectral_density(size, length_scale, family) + white = rng.normal(size=size) + field = np.fft.irfft(np.fft.rfft(white) * np.sqrt(density), n=size) + return field[:n].astype(np.float32) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/spectral_transfer/run.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/spectral_transfer/run.py new file mode 100644 index 0000000000000000000000000000000000000000..b12c03e56acc3688932c441fd31aa259136f1bc1 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/spectral_transfer/run.py @@ -0,0 +1,55 @@ +"""E114: two predeclared coefficient-one spectral-prior transfers; selection only.""" +import hashlib +import json +import os +import subprocess +import time +from pathlib import Path + +R = Path('/workspace/research') +env = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1') +started = time.monotonic() +receipt = {'experiment': 'E114', 'status': 'running', 'steps': []} +receipt_path = R / 'spectral_transfer_receipt.json' + +def run(label, command): + receipt['current_step'] = label + receipt_path.write_text(json.dumps(receipt, indent=2)) + print(json.dumps({'starting': label}), flush=True) + t0 = time.monotonic() + result = subprocess.run(command, env=env, check=False) + receipt['steps'].append({'name': label, 'seconds': time.monotonic()-t0, + 'returncode': result.returncode}) + if result.returncode: + receipt.update(status='failed', seconds=time.monotonic()-started) + receipt_path.write_text(json.dumps(receipt, indent=2)) + raise SystemExit(result.returncode) + +add = R/'spectral_add_delta6k.pt' +replace = R/'spectral_replace_delta6k.pt' +assert not add.exists() and not replace.exists(), 'Refuse to overwrite fixed candidates' +run('add_spectral_delta', ['python3', str(R/'partial_delta/merge.py'), + '--base', str(R/'weekly_slow_ar_delta6k.pt'), + '--candidate', str(R/'runs/spectral_synth/ema006000.pt'), + '--control', str(R/'runs/overflow_control/ema006000.pt'), '--out', str(add)]) +run('remove_old_slow_ar_delta', ['python3', str(R/'partial_delta/merge.py'), + '--base', str(add), '--candidate', str(R/'runs/partial_targets/ema006000.pt'), + '--control', str(R/'runs/long_memory_synth_recovery/ema006000.pt'), '--out', str(replace)]) +receipt['candidate_hashes'] = {p.stem: hashlib.sha256(p.read_bytes()).hexdigest() for p in [add, replace]} +for weights in [add, replace]: + run(weights.stem+'_four_cutoffs', ['python3', str(R/'evaluate_cutoffs.py'), + '--name', weights.stem, '--weights', str(weights), + '--evaluator', str(R/'postloss_inference/evaluate.py')]) + for cutoff, folder in [('valid_screen','evals'), ('valid_backcast','backcast_evals'), + ('valid_backcast2','backcast2_evals'), ('valid_backcast3','backcast3_evals')]: + run(weights.stem+'_'+cutoff+'_record', ['python3', str(R/'direct_v1/record.py'), + str(R/folder/weights.stem/'report.json'), '--label', 'E114 '+weights.stem+' '+cutoff, + '--outcome', 'Fixed coefficient-one spectral transfer; additive and old-slow-AR replacement are the two predeclared ablations. No optimization. Ensemble selection recorded separately.']) + command = ['python3', str(R/'equal_ensemble_probe.py'), '--valid', str(R/cutoff), + '--out', str(R/(weights.stem+'_ensemble_'+cutoff+'.json'))] + for name in [weights.stem, 'patch8_ema6000', 'split_patch_ema12000']: + command += ['--pred', str(R/folder/name)] + run(weights.stem+'_'+cutoff+'_ensemble', command) +receipt.update(status='complete', seconds=time.monotonic()-started) +receipt_path.write_text(json.dumps(receipt, indent=2)) +print(json.dumps(receipt), flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/weekly_synth/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/weekly_synth/check.py new file mode 100644 index 0000000000000000000000000000000000000000..1797c7ca37791de3ac143f64843434ad7beda0ba --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/weekly_synth/check.py @@ -0,0 +1,45 @@ +"""Verify the weekly-only data change without using validation or optimizer steps.""" +import copy +import hashlib +import importlib.util +import json +import sys +import time +from pathlib import Path +import numpy as np + +R=Path('/workspace/research') +sys.path.insert(0,str(R/'weekly_synth')) +from data import Sampler +spec=importlib.util.spec_from_file_location('weekly_control_data',R/'overflow_control/data.py') +control_code=importlib.util.module_from_spec(spec);spec.loader.exec_module(control_code) +started=time.monotonic();seed=467 +candidate=Sampler(R/'packed_sample',seed=seed,source_weights_from=R/'packed_sample') +control=control_code.Sampler(R/'packed_sample',seed=seed,source_weights_from=R/'packed_sample') +rng=np.random.default_rng(seed);rows=synthetic_rows=weekly_rows=0 +for _ in range(120): + c=int(rng.choice([512,1024,2048,4096]));h=int(rng.choice([32,128,512,1024])) + expected=control.sample(64,c,h);actual=candidate.sample(64,c,h) + replacements=np.array(candidate.last_weekly_rows,dtype=int) + unchanged=np.ones(64,dtype=bool);unchanged[replacements]=False + for x,y in zip(expected,actual): + assert np.array_equal(x[unchanged],y[unchanged],equal_nan=True) + assert set(candidate.last_weekly_rows)<=set(candidate.last_synthetic_rows) + assert np.all(actual[2][replacements]==np.array([52,1])) + for x,y in zip(expected[:2],actual[:2]): + assert np.array_equal(np.isfinite(x),np.isfinite(y)) + assert candidate.rng.bit_generator.state==control.rng.bit_generator.state + assert candidate.horizon_rng.bit_generator.state==control.horizon_rng.bit_generator.state + rows+=64;synthetic_rows+=len(candidate.last_synthetic_rows);weekly_rows+=len(replacements) +states={n:copy.deepcopy(v.bit_generator.state) for n,v in vars(candidate).items() if isinstance(v,np.random.Generator)} +next_batch=candidate.sample(64,4096,1024) +for name,state in states.items():getattr(candidate,name).bit_generator.state=state +replayed=candidate.sample(64,4096,1024) +assert all(np.array_equal(x,y,equal_nan=True) for x,y in zip(next_batch,replayed)) +model_hash=hashlib.sha256((R/'weekly_synth/model.py').read_bytes()).hexdigest() +assert model_hash==hashlib.sha256((R/'overflow_control/model.py').read_bytes()).hexdigest() +result=dict(seed=seed,rows=rows,original_synthetic_rows=synthetic_rows,replaced_weekly_rows=weekly_rows, + probability=1/11,original_and_horizon_rng_bitwise_preserved=True,unmodified_rows_bitwise_preserved=True, + finite_masks_unchanged=True,all_numpy_rng_recovery_exact=True,model_sha256=model_hash, + model_bitwise_unchanged=True,seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False) +(R/'weekly_synth_checks.json').write_text(json.dumps(result,indent=2));print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/weekly_synth/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/weekly_synth/data.py new file mode 100644 index 0000000000000000000000000000000000000000..81f0f018cb212a6e2125543e0d4efa2f31b9d8fb --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/weekly_synth/data.py @@ -0,0 +1,113 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + self.weekly_rng=np.random.default_rng(seed+1000003) + self.weekly_probability=1/11 + def synthetic(self,n,p): + # Always consume the control generator first, preserving its complete RNG stream. + original=super().synthetic(n,p) + if self.weekly_rng.random()>=self.weekly_probability: + return original + original_rng=self.rng + try: + self.rng=self.weekly_rng + result=super().synthetic(n,[52,1]) + finally: + self.rng=original_rng + p[:]=[52,1] + self.last_weekly_rows.append(self._synthetic_row) + return result + + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/weekly_synth/launch.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/weekly_synth/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..ef36b1e3de2ad1cc424019100da141536161d07a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/weekly_synth/launch.py @@ -0,0 +1,29 @@ +"""Queue weekly synthetic coverage after robust-normalization training finishes.""" +def main(): + import json + import os + import subprocess + from pathlib import Path + R=Path('/workspace/research') + checks=json.loads((R/'weekly_synth_checks.json').read_text()) + assert checks['original_and_horizon_rng_bitwise_preserved'] and checks['unmodified_rows_bitwise_preserved'] + assert checks['all_numpy_rng_recovery_exact'] and checks['model_bitwise_unchanged'] + env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1') + command=['python3',str(R/'recovery/train.py'),'--code-dir',str(R/'weekly_synth'), + '--packed',str(R/'packed_sample'),'--source-weights-from',str(R/'packed_sample'), + '--out',str(R/'runs/weekly_synth'),'--initialize-from',str(R/'horizon_delta12k.pt'), + '--steps','12000','--batch','64','--lr','.00002','--seed','197','--loss-mode','paired', + '--stop-file',str(R/'weekly_synth.stop')] + with (R/'weekly_synth_queue.log').open('w') as qlog,(R/'weekly_synth_watch.log').open('w') as wlog: + queued=subprocess.Popen(['python3',str(R/'queued_train.py'),'--label','E97 weekly synthetic coverage seed197', + '--log',str(R/'weekly_synth_train.log'),'--receipt',str(R/'weekly_synth_queue.json'), + '--wait-pid','9354','--require-checkpoint',str(R/'runs/robust_normalization/recovery.pt'), + '--',*command],stdout=qlog,stderr=subprocess.STDOUT,env=env) + watch=subprocess.Popen(['python3',str(R/'watch_evaluate.py'),'--run',str(R/'runs/weekly_synth'), + '--evaluator',str(R/'postloss_inference/evaluate.py'),'--name','weekly_synth', + '--steps','1000,3000,6000,12000'],stdout=wlog,stderr=subprocess.STDOUT,env=env) + print({'queue_pid':queued.pid,'watch_pid':watch.pid},flush=True) + result=queued.wait() + if result:watch.terminate() + watch.wait();raise SystemExit(result) +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/weekly_synth/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/weekly_synth/model.py new file mode 100644 index 0000000000000000000000000000000000000000..3532e5063bd8b5013f6b6e35703707ffef66e00b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member0/training/weekly_synth/model.py @@ -0,0 +1,213 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/model_manifest.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/model_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..ed7d82d53ee418c27f3691dc143ede37891db0ef --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/model_manifest.json @@ -0,0 +1,660 @@ +{ + "name": "direct-seasonal-foundation", + "contract": "timeseries-forecast/v1", + "parameters": 36665488, + "pretrained_assets": [], + "sources_used": [ + "gifteval_pretrain/BEIJING_SUBWAY_30MIN", + "gifteval_pretrain/HZMETRO", + "gifteval_pretrain/LOS_LOOP", + "gifteval_pretrain/PEMS03", + "gifteval_pretrain/PEMS04", + "gifteval_pretrain/PEMS07", + "gifteval_pretrain/PEMS08", + "gifteval_pretrain/PEMS_BAY", + "gifteval_pretrain/Q-TRAFFIC", + "gifteval_pretrain/SHMETRO", + "gifteval_pretrain/alibaba_cluster_trace_2018", + "gifteval_pretrain/australian_electricity_demand", + "gifteval_pretrain/azure_vm_traces_2017", + "gifteval_pretrain/bdg-2_bear", + "gifteval_pretrain/bdg-2_fox", + "gifteval_pretrain/bdg-2_panther", + "gifteval_pretrain/bdg-2_rat", + "gifteval_pretrain/bitcoin_with_missing", + "gifteval_pretrain/borealis", + "gifteval_pretrain/borg_cluster_data_2011", + "gifteval_pretrain/buildings_900k", + "gifteval_pretrain/bull", + "gifteval_pretrain/cdc_fluview_ilinet", + "gifteval_pretrain/cdc_fluview_who_nrevss", + "gifteval_pretrain/china_air_quality", + "gifteval_pretrain/cif_2016_12", + "gifteval_pretrain/cif_2016_6", + "gifteval_pretrain/cmip6_2000", + "gifteval_pretrain/cmip6_2005", + "gifteval_pretrain/cmip6_2010", + "gifteval_pretrain/cockatoo", + "gifteval_pretrain/covid19_energy", + "gifteval_pretrain/covid_mobility", + "gifteval_pretrain/elecdemand", + "gifteval_pretrain/elf", + "gifteval_pretrain/era5_2010", + "gifteval_pretrain/era5_2011", + "gifteval_pretrain/era5_2012", + "gifteval_pretrain/era5_2013", + "gifteval_pretrain/era5_2014", + "gifteval_pretrain/era5_2015", + "gifteval_pretrain/era5_2016", + "gifteval_pretrain/era5_2017", + "gifteval_pretrain/era5_2018", + "gifteval_pretrain/extended_web_traffic_with_missing", + "gifteval_pretrain/favorita_sales", + "gifteval_pretrain/favorita_transactions", + "gifteval_pretrain/gfc12_load", + "gifteval_pretrain/gfc14_load", + "gifteval_pretrain/gfc17_load", + "gifteval_pretrain/godaddy", + "gifteval_pretrain/hog", + "gifteval_pretrain/ideal", + "gifteval_pretrain/kaggle_web_traffic_weekly", + "gifteval_pretrain/kdd2022", + "gifteval_pretrain/largest_2017", + "gifteval_pretrain/largest_2018", + "gifteval_pretrain/largest_2019", + "gifteval_pretrain/largest_2020", + "gifteval_pretrain/largest_2021", + "gifteval_pretrain/lcl", + "gifteval_pretrain/london_smart_meters_with_missing", + "gifteval_pretrain/m1_monthly", + "gifteval_pretrain/m1_quarterly", + "gifteval_pretrain/m1_yearly", + "gifteval_pretrain/m5", + "gifteval_pretrain/monash_m3_monthly", + "gifteval_pretrain/monash_m3_other", + "gifteval_pretrain/monash_m3_quarterly", + "gifteval_pretrain/nn5_daily_with_missing", + "gifteval_pretrain/nn5_weekly", + "gifteval_pretrain/oikolab_weather", + "gifteval_pretrain/pdb", + "gifteval_pretrain/project_tycho", + "gifteval_pretrain/residential_load_power", + "gifteval_pretrain/residential_pv_power", + "gifteval_pretrain/rideshare_with_missing", + "gifteval_pretrain/sceaux", + "gifteval_pretrain/smart", + "gifteval_pretrain/solar_power", + "gifteval_pretrain/spain", + "gifteval_pretrain/subseasonal", + "gifteval_pretrain/subseasonal_precip", + "gifteval_pretrain/sunspot_with_missing", + "gifteval_pretrain/taxi_30min", + "gifteval_pretrain/tourism_quarterly", + "gifteval_pretrain/tourism_yearly", + "gifteval_pretrain/traffic_hourly", + "gifteval_pretrain/traffic_weekly", + "gifteval_pretrain/uber_tlc_daily", + "gifteval_pretrain/uber_tlc_hourly", + "gifteval_pretrain/vehicle_trips_with_missing", + "gifteval_pretrain/wiki-rolling_nips", + "gifteval_pretrain/wind_farms_with_missing", + "gifteval_pretrain/wind_power", + "synthetic:both original and sign-reflected orientations of each sampled allowed or locally generated window; paired quantile loss, seed 197", + "synthetic:both original and sign-reflected orientations of each sampled window, seed 197", + "synthetic:independent sign reflection of sampled allowed-corpus and locally generated windows; seeds 43,47,59,79,89,197", + "synthetic:own direct_v1 Fourier seasons, damped trends, AR noise, changepoints and intermittent demand; seeds 23,43,47,59,79,89,197", + "synthetic:own random requested-horizon prefixes, half of rows retain the full horizon and half use a patch-rounded prefix between one-quarter and the full horizon; independent seed 300200" + ], + "weights_sha256": "308389b7217c080af9eb185559d4ee3cafa0f3e0f8c4dd8f5526b68198c89988", + "config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "training_lineage": [ + { + "checkpoint": "runs/patch8/ema006000.pt", + "sha256": "308389b7217c080af9eb185559d4ee3cafa0f3e0f8c4dd8f5526b68198c89988", + "step": 6000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "patch8_initial.pt" + ] + }, + { + "checkpoint": "patch8_initial.pt", + "sha256": "e7da4d47a9cc984a9423296679d7c9127ef2d679be950b9e8d3758e6fca074cc", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "from_checkpoint": "/run-state/workspace/research/horizon_delta12k.pt", + "from_sha256": "22c08571978be31ba57368eb983089a40a44d56d4ae5e17da41afd2a761a258c", + "method": "fold input/query/recency halves by summation; retain first8 output rows; preserve physical position units", + "exact_function_preservation": false + }, + "parents": [ + "horizon_delta12k.pt", + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "horizon_delta12k.pt", + "sha256": "22c08571978be31ba57368eb983089a40a44d56d4ae5e17da41afd2a761a258c", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/runs/confidence_query/ema006000.pt": "0bad97e8994aac49ea173443db0a4fa8d72d33f9eb9e2660f06de75f7f1403eb", + "/workspace/research/runs/horizon_jitter/ema012000.pt": "830179d763916a1065fc615d2c5e22f4a3b5b19390dde707ab0f057e13cadff6", + "/workspace/research/runs/large_corpus_control/ema012000.pt": "7f9ba5e01ac59c51a3b63d3067b442e23e15d0abc51ddbcccdd04d6083ae4add" + }, + "seconds": 1.2663014469435439 + }, + "parents": [ + "runs/confidence_query/ema006000.pt", + "runs/horizon_jitter/ema012000.pt", + "runs/large_corpus_control/ema012000.pt" + ] + }, + { + "checkpoint": "runs/confidence_query/ema006000.pt", + "sha256": "0bad97e8994aac49ea173443db0a4fa8d72d33f9eb9e2660f06de75f7f1403eb", + "step": 6000, + "seed": 89, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 0.0002, + "steps": 6000 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true + }, + "parents": [ + "runs/recency_features/ema024000.pt" + ] + }, + { + "checkpoint": "runs/horizon_jitter/ema012000.pt", + "sha256": "830179d763916a1065fc615d2c5e22f4a3b5b19390dde707ab0f057e13cadff6", + "step": 12000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "partial_target_lengths": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/large_corpus_control/ema012000.pt", + "sha256": "7f9ba5e01ac59c51a3b63d3067b442e23e15d0abc51ddbcccdd04d6083ae4add", + "step": 12000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/recency_features/ema024000.pt", + "sha256": "1530fbb577a87ca4eb39da83d6fee9b8ee5bc924202e021e3a7b56493112f564", + "step": 24000, + "seed": 59, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/patch16_trial/ema006000.pt" + ] + }, + { + "checkpoint": "runs/recency_features/ema012000.pt", + "sha256": "8ccb6870a025e1097331a3a288b1183741a413f3460fbf3352d0c589c6a4394c", + "step": 12000, + "seed": 59, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/patch16_trial/ema006000.pt" + ] + }, + { + "checkpoint": "runs/patch16_trial/ema006000.pt", + "sha256": "0ff54447074e0271d2e331c7d3e6e9e0fdd73353e4d8cef0175ff627385f71c3", + "step": 6000, + "seed": 47, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024 + }, + "parents": [ + "patch16_init.pt" + ] + }, + { + "checkpoint": "patch16_init.pt", + "sha256": "d69531bfde5bf801e7f36c515bf15fd0cae0bd84f7d1479d35f4a7b67f26b508", + "step": 6000, + "seed": 43, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024 + }, + "conversion": { + "from_checkpoint": "/run-state/workspace/research/runs/large_sign/ema006000.pt", + "from_sha256": "96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547", + "method": "fold input/query halves by summation; retain first 16 output rows; preserve physical positional units" + }, + "parents": [ + "runs/large_sign/ema006000.pt" + ] + }, + { + "checkpoint": "runs/large_sign/ema006000.pt", + "sha256": "96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547", + "step": 6000, + "seed": 43, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 32, + "max_context": 4096, + "max_horizon": 1024 + }, + "parents": [ + "runs/direct_large/step024000.pt" + ] + }, + { + "checkpoint": "runs/direct_large/step024000.pt", + "sha256": "b7e4f38aebcd2cf38ce484edaad8d19851317fb3b8df485e2faa0d0423cbcb48", + "step": 24000, + "seed": 23, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 128, + "lr": 0.0002, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 32, + "max_context": 4096, + "max_horizon": 1024 + }, + "initialization": "random initialization in this workspace" + } + ], + "symmetric_averaging": true, + "seasonal_gate": { + "variance_ratio_threshold": 0.25, + "maximum_weight": 0.98, + "cycles_averaged": 4, + "template_mode": "aligned", + "amplitude_ratio_clip": [ + 0.5, + 2.0 + ], + "latest_cycle_minimum_coverage": 0.75, + "variance_noise_correction": "mean squared seasonal differences / 2" + }, + "continuity": { + "decay_steps": 24, + "variance_ratio_threshold": 0.5, + "maximum_weight": 0.95, + "lookback": 512, + "slope_median_differences": 8 + }, + "notes": "All training lineage originates from random initialization here, using only the declared corpus and locally generated series. Validation was used only for selection and diagnostics. Context transformations are fixed formulas; there is no inference-time fitting or parameter adaptation.", + "runtime_code_sha256": { + "model.py": "c27748fa4b1186b513f76eca26052753b8dcd1794994e5989addaf371ca70f2e", + "infer.sh": "5fe66b4fe9a4787285d830cfd96975701e97286a75ba7c3687bd8891475edf68", + "continuity.py": "dbb08d2229ad80ad00f638b0b9f2f6ca13c663e0fd6730058e5fee8ff54545d5", + "ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "zero_mass.py": "f079d509009bcda409b80eb64467c869b838cfbab11b2bd4c660c2875b6642fe", + "seasonal.py": "b946e63048196ab5ea8b249137d48c80d8510943caccd0f180e4fb86d9b24b37", + "predict.py": "9bde896945a2cd8f892e7eeb6328ed2dfda09293532f3a4a64d929c9943614ef" + }, + "final_training_stage": { + "trainable_scope": "all parameters", + "sign_loss": "paired", + "learning_rate_multipliers": {} + }, + "trend_summary": { + "fixed_averaging_width": 128, + "matches_all_pretraining_context_widths": true, + "independent_of_batch_padding": true + }, + "zero_mass_projection": { + "threshold_in_context_standard_deviations": 0.4, + "nonnegative_context_required": true, + "minimum_exact_zeros": 4, + "minimum_zero_fraction": 0.1, + "context_cap": 4096 + }, + "recency_features": { + "query_projection_parameters": 16384, + "latest_vs_four_cycle_level": true, + "amplitude_ratio_clip": [ + 0.5, + 2.0 + ], + "minimum_observed_cycles": 3 + }, + "confidence_features": { + "query_projection_parameters": 3072, + "backbone_frozen_during_projection_training": true, + "training_objective": "weighted quantile and median loss after averaging both sign orientations", + "statistics": [ + "mean absolute difference", + "root mean square difference" + ], + "lags": "one and the two frequency-derived periods", + "lookback": "512 for lag one; eight cycles for seasonal lags", + "minimum_valid_pairs": 8, + "insufficient_pair_defaults": [ + 1, + 1.4142135623730951 + ], + "statistic_clip": 10, + "transform": "log1p", + "stage_scope": "Frozen-backbone details refer to projection introduction; subsequent updates are recorded in training_lineage.training_settings." + }, + "partial_target_training": { + "available_horizon": "last finite training-label position rounded up to the patch boundary", + "decoder_future_key_mask": true, + "per_row_horizon_metadata": true, + "inference_uses_requested_horizon_only": true + }, + "training_provenance_code_sha256": { + "confidence_query/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "confidence_query/model.py": "b4f11ba2018e2b50879cdc33acf0138301548971508b58035a7c96a29aaa6f2d", + "confidence_query/train.py": "fc8a7555a5a6b0a6f91e80ac8cc9cbbfddaa2b26468c57f49dfb17671b22ce93", + "direct_large/data.py": "6e6db217936f8dd79380d2ceff3eaa8598a44f1b60b17acae7bfde2363116847", + "direct_large/evaluate.py": "eaea99e8cd44c9f7c70a45fa9abf51354ae5449dbad273fcb55e48ad02652223", + "direct_large/model.py": "146d93a3f95b13bda8b1b437bc36621b91356cf946e94f62999f89e7fb348071", + "direct_large/pack.py": "3bcc4ce9eb3361ad741ceebd7efce7a2fb86fb49543f52c72aabd0e3e8cd17ce", + "direct_large/predict.py": "930a9f18f9f5da47c03859698c9d2f5567d1e1c73fd61edac1ed20b3a6f9bb50", + "direct_large/publish.py": "3c167f33e8571731c26f1cb70168eda54ef9cb4c76423dfd374240b75ca5f106", + "direct_large/record.py": "b3b00b0ed14bc3af00c7b1ad97195238ecb8f06e96bc41f0c07913bc3f6ed949", + "direct_large/train.py": "b9ad6b2adddeaf12961b529d6535dd33f6d044a31979b5c9e49dceafbadd3ac0", + "direct_large/ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "direct_large/validation_subset.py": "8d3eb9d3f3aa124368761ef402ff066935c0be31a62b25b8551a45dcb922e28d", + "full_paired/check.py": "90ac1c78846439d51ab8acd62a19bd536c7c394bd02e94f6d5ff17c0af8bd116", + "full_paired/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "full_paired/model.py": "c27748fa4b1186b513f76eca26052753b8dcd1794994e5989addaf371ca70f2e", + "horizon_jitter/data.py": "5044cf648323420095ed6058d29f837c07ff5559b606df8b00cc8d1e95c8b58e", + "horizon_jitter/model.py": "186bb282236f23cc665a012194d26e58f51004c680393352ec053f5308f1240f", + "horizon_jitter/train.py": "4e9cbca1293f18f7eea2c72dba127815c0934a13c86e8f6cc881a749676d41a6", + "large_corpus/data.py": "27c078cb0ed085717a364f556b5ff976fd803d5af37612cf3a03a0a3ca12a678", + "large_corpus/model.py": "e3a1bc01e89a0d6d750ede2cc969272ad01e1ca580b174af7dee00db029f1cf7", + "large_corpus/train.py": "3baca16c3945e6ef241ccbc9c13644539e3c265f71095cbbaa61a3d338e4fafe", + "large_sign/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "large_sign/evaluate.py": "eaea99e8cd44c9f7c70a45fa9abf51354ae5449dbad273fcb55e48ad02652223", + "large_sign/model.py": "3fff6445a1982a1b3c92f06a9b5f1bb627dda6a291b0b2364bcfb1a6457830d7", + "large_sign/pack.py": "3bcc4ce9eb3361ad741ceebd7efce7a2fb86fb49543f52c72aabd0e3e8cd17ce", + "large_sign/predict.py": "930a9f18f9f5da47c03859698c9d2f5567d1e1c73fd61edac1ed20b3a6f9bb50", + "large_sign/publish.py": "3c167f33e8571731c26f1cb70168eda54ef9cb4c76423dfd374240b75ca5f106", + "large_sign/record.py": "b3b00b0ed14bc3af00c7b1ad97195238ecb8f06e96bc41f0c07913bc3f6ed949", + "large_sign/train.py": "a597f40ab87cce04e96dc654d12e56cdf40ffd87f00034d8bc4d56dff4eb7c68", + "large_sign/ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "large_sign/validation_subset.py": "8d3eb9d3f3aa124368761ef402ff066935c0be31a62b25b8551a45dcb922e28d", + "partial_delta/merge.py": "63984a0f46f7d48817037f5bf5a1c9319e45a9b1924cde62c667ac49ce47532e", + "partial_targets/data.py": "27c078cb0ed085717a364f556b5ff976fd803d5af37612cf3a03a0a3ca12a678", + "partial_targets/model.py": "186bb282236f23cc665a012194d26e58f51004c680393352ec053f5308f1240f", + "partial_targets/train.py": "3baca16c3945e6ef241ccbc9c13644539e3c265f71095cbbaa61a3d338e4fafe", + "patch16/convert.py": "11e1d30100ab25311020ac1f4ab8227ec66156836df5de613300867977091c45", + "patch16/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "patch16/evaluate.py": "eaea99e8cd44c9f7c70a45fa9abf51354ae5449dbad273fcb55e48ad02652223", + "patch16/model.py": "8031c597b354eb2cf464140bee40c3ec8dff86c775b5c55c5ce910302b443582", + "patch16/pack.py": "3bcc4ce9eb3361ad741ceebd7efce7a2fb86fb49543f52c72aabd0e3e8cd17ce", + "patch16/predict.py": "930a9f18f9f5da47c03859698c9d2f5567d1e1c73fd61edac1ed20b3a6f9bb50", + "patch16/publish.py": "3c167f33e8571731c26f1cb70168eda54ef9cb4c76423dfd374240b75ca5f106", + "patch16/record.py": "b3b00b0ed14bc3af00c7b1ad97195238ecb8f06e96bc41f0c07913bc3f6ed949", + "patch16/train.py": "3156710f76111a31447cbe638ee27fe2811d060917aa083aab0b5134d98accf8", + "patch16/ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "patch16/validation_subset.py": "8d3eb9d3f3aa124368761ef402ff066935c0be31a62b25b8551a45dcb922e28d", + "patch8/convert.py": "9edaa0c8349310b7419d649fb4f21dd3ddb9067ebe984d5df3701a234be73780", + "patch8/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "patch8/memory_check.py": "78e8e5cca960bf1225ec0104980363c82f4c3c13c2d77ed154cea37a5b6f3fd1", + "patch8/model.py": "c27748fa4b1186b513f76eca26052753b8dcd1794994e5989addaf371ca70f2e", + "recency_features/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "recency_features/model.py": "e3a1bc01e89a0d6d750ede2cc969272ad01e1ca580b174af7dee00db029f1cf7", + "recency_features/train.py": "a654b9a27b6c27141e1d4e517ab28fcae3f2c23d061742fa2f6c01e3d23c8a00", + "recovery/capacity_curves.py": "2bdc6635705b70a868e115cd13eb529563acacf6f47c71f250a50dce8e943be4", + "recovery/exposure_audit.py": "54c194a626b8876ece84686b39b22360155c9fada7248a393ca9b7d6ee38002b", + "recovery/relaunch_20261022b.py": "f90ddd77928a793c8e151ba74cfa9cc84c8aefad0c0d943a833c74bc07b79313", + "recovery/relaunch_20261023.py": "a4c40c5674b0d05cfe9bb1fffe907f02dec16c53cbddb8b86efbba1b96649097", + "recovery/schedules.py": "7748fd6b2bbbe64037472faf7e6583d03cf339138d2f3c07b1bac9e65bf2d4f5", + "recovery/snapshot.py": "0f241a7e139e47ffff7efea40572205fd84c12efe6fb3c2dccd87c50d678a6c3", + "recovery/train.py": "63bee736565af670877b4cd7c75015fab06a18c66bbe132b0bb3faff5ebd80c7" + } +} diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/confidence_query/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/confidence_query/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/confidence_query/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/confidence_query/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/confidence_query/model.py new file mode 100644 index 0000000000000000000000000000000000000000..b881039b3752b3396e06415a8d01d24956fa29a7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/confidence_query/model.py @@ -0,0 +1,190 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + if self.recency is not None: + pos=torch.arange(c,device=z.device)[None,:];extras=[] + for j in range(2): + period=periods[:,j:j+1] + recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + n=ctx.shape[0] + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1]) + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/confidence_query/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/confidence_query/train.py new file mode 100644 index 0000000000000000000000000000000000000000..fd9d2a3a0502cee1a67c41c832266c7f87cc5a80 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/confidence_query/train.py @@ -0,0 +1,54 @@ +"""Train only confidence-query features on a frozen model, using paired-sign forecast loss.""" +import argparse,json,math,time,os +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) +ap.add_argument('--initialize-from',required=True);ap.add_argument('--steps',type=int,default=6000) +ap.add_argument('--batch',type=int,default=128);ap.add_argument('--lr',type=float,default=2e-4) +ap.add_argument('--seed',type=int,default=89);ap.add_argument('--save-every',type=int,default=1000);a=ap.parse_args() +torch.set_num_threads(1);torch.manual_seed(a.seed);torch.backends.cuda.matmul.allow_tf32=True +out=Path(a.out);out.mkdir(parents=True,exist_ok=True) +ck=torch.load(a.initialize_from,map_location='cpu',weights_only=False) +config={**ck['config'],'confidence_features':True};model=DirectForecaster(**config).cuda() +missing,unexpected=model.load_state_dict(ck['model'],strict=False) +assert not unexpected and all(k.startswith('confidence.') for k in missing) +for name,param in model.named_parameters():param.requires_grad_(name.startswith('confidence.')) +params=[p for p in model.parameters() if p.requires_grad] +opt=torch.optim.AdamW(params,lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) +ema={k:v.detach().clone() for k,v in model.state_dict().items()};sampler=Sampler(a.packed,seed=a.seed) +(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)) +rng=np.random.default_rng(a.seed) +def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) +def save(step): + for prefix,weights in [('step',model.state_dict()),('ema',ema)]: + state={'model':weights,'config':model.config,'step':step,'args':vars(a),'ema':prefix=='ema'} + path=out/f'{prefix}{step:06d}.pt';torch.save(state,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) +save(0);pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] +for step in range(1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch);x,y,p=[torch.from_numpy(x).cuda() for x in arrays] + lr=a.lr*min(1,step/200)*(.2+.8*.5*(1+math.cos(math.pi*step/a.steps))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(params,1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items(): + if k.startswith('confidence.'):ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + if step%a.save_every==0 or step==a.steps:save(step) +pool.shutdown() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/direct_large/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/direct_large/data.py new file mode 100644 index 0000000000000000000000000000000000000000..2378e33d7352ba5ad97d566148782e63e64b367c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/direct_large/data.py @@ -0,0 +1,71 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + return ctx,tgt,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/direct_large/evaluate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/direct_large/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..05f086d4d84def4a48165f9e65d2948877675e56 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/direct_large/evaluate.py @@ -0,0 +1,16 @@ +import sys,json,argparse,time,hashlib +from pathlib import Path +import torch +from predict import load_model,run +sys.path.insert(0,'/workspace/evaluation') +from score import score,json_safe + +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);ap.add_argument('--valid',default='/workspace/research/valid_screen');ap.add_argument('--baseline',default='/workspace/research/valid_screen/baseline.json');a=ap.parse_args() +torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cuda.matmul.allow_tf32=False +t0=time.time();out=Path(a.out);v=Path(a.valid) +run(load_model(a.weights),v/'input',out) +base=json.loads(Path(a.baseline).read_text())['configs'] +rep=score(v/'truth',out,base) +rep['checkpoint_sha256']=hashlib.sha256(Path(a.weights).read_bytes()).hexdigest();rep['eval_seconds']=time.time()-t0 +(out/'report.json').write_text(json.dumps(json_safe(rep),indent=1)) +print(json.dumps({k:rep[k] for k in ('skill_score','rel_mase_gmean','rel_wql_gmean','n_failed','groups','eval_seconds')},indent=1)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/direct_large/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/direct_large/model.py new file mode 100644 index 0000000000000000000000000000000000000000..7a224cc12a159446a1e427b2052b53d1d1f7e83e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/direct_large/model.py @@ -0,0 +1,142 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional(torch.arange(-nt,0,device=z.device),self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + q=self.query(base.reshape(b,h//p,p*9))+positional(torch.arange(h//p,device=z.device),self.d)[None]+emb + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + pin=torch.maximum(levels*err,(levels-1)*err).mean(-1) + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + return per.mean() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/direct_large/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/direct_large/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/direct_large/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/direct_large/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/direct_large/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..e20c6630475d6b4fa6906eb4ed9454b7b5aeec2c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/direct_large/predict.py @@ -0,0 +1,43 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):q=model.predict(x,p,h).float().cpu().numpy() + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/direct_large/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/direct_large/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf95c9aec5936076b881c340edb960786f2d40d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/direct_large/publish.py @@ -0,0 +1,31 @@ +"""Assemble a relocatable package, then atomically exchange complete directories.""" +import json,os,shutil,ctypes,hashlib,argparse +from pathlib import Path +import torch +HERE=Path(__file__).resolve().parent + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',default='/workspace/submission');ap.add_argument('--report',required=True);ap.add_argument('--experiments',default=str(HERE/'EXPERIMENTS.md'));a=ap.parse_args() + final=Path(a.out);staging=final.parent/f'.{final.name}-staging-{os.getpid()}' + shutil.rmtree(staging,ignore_errors=True);staging.mkdir(parents=True) + for file in ('model.py','predict.py','infer.sh','ts_io.py'): + shutil.copy(HERE/file,staging/file) + shutil.copy(a.weights,staging/'weights.pt');shutil.copy('/opt/runtime/requirements.txt',staging/'requirements.txt') + ck=torch.load(a.weights,map_location='cpu',weights_only=False);digest=hashlib.sha256((staging/'weights.pt').read_bytes()).hexdigest() + sources=json.loads(Path('/workspace/research/packed_sample/meta.json').read_text())['dirs'] + manifest={'name':'direct-seasonal-quantile-v1','contract':'timeseries-forecast/v1','parameters':sum(x.numel() for x in ck['model'].values()),'pretrained_assets':[],'sources_used':[f'gifteval_pretrain/{d}' for d in sources]+['synthetic:direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; data.py generator seed 17'],'weights_sha256':digest,'training_step':ck['step'],'config':ck['config'],'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.'} + (staging/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') + (staging/'config.json').write_text(json.dumps(ck['config'],indent=2)+'\n') + shutil.copy(a.experiments,staging/'EXPERIMENTS.md');shutil.copy(a.report,staging/'validation_report.json') + # Include generator/sampler provenance, which is not imported by inference. + (staging/'provenance').mkdir() + for file in ('pack.py','data.py','train.py'):shutil.copy(HERE/file,staging/'provenance'/file) + (staging/'README.md').write_text('# Direct seasonal quantile foundation forecaster\n\nRun `bash infer.sh INPUT_DIR OUTPUT_DIR`. This package contains all inference assets and uses only its supplied input directory. The 6.76M 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.\n\nThe 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.\n') + if final.exists(): + libc=ctypes.CDLL(None,use_errno=True) + if libc.renameat2(-100,os.fsencode(staging),-100,os.fsencode(final),2):raise OSError(ctypes.get_errno(),os.strerror(ctypes.get_errno())) + shutil.rmtree(staging) + else:os.replace(staging,final) + print(json.dumps(manifest,indent=1)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/direct_large/record.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/direct_large/record.py new file mode 100644 index 0000000000000000000000000000000000000000..1850a33f46fa3ee4d78cac4a5d6152404801a131 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/direct_large/record.py @@ -0,0 +1,9 @@ +import argparse,json,math +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('report');ap.add_argument('--label',required=True);ap.add_argument('--outcome',default='Screened for model selection.');a=ap.parse_args() +r=json.loads(Path(a.report).read_text());p=Path(__file__).with_name('EXPERIMENTS.md') +lines=[f'\n## {a.label}',f'- Checkpoint SHA-256: `{r.get("checkpoint_sha256","see model_manifest.json")}`.',f'- Evaluation: {r["n_configs"]} configurations, {r["n_instances"]} instances, {r["n_failed"]} failed configurations; {r.get("eval_seconds","not separately timed")} seconds.',f'- Overall skill {r["skill_score"]:.6f}; relative MASE {r["rel_mase_gmean"]:.6f}; relative WQL {r["rel_wql_gmean"]:.6f}.'] +for group,entries in r['groups'].items(): + lines.append(f'- {group} skill: '+', '.join(f'{k}={1-math.sqrt(v["rel_mase_gmean"]*v["rel_wql_gmean"]):.4f}' for k,v in entries.items())+'.') +lines.append('- Outcome: '+a.outcome) +with p.open('a') as f:f.write('\n'.join(lines)+'\n') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/direct_large/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/direct_large/train.py new file mode 100644 index 0000000000000000000000000000000000000000..a2ccc736bfef804259199a2dd315347d9854b680 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/direct_large/train.py @@ -0,0 +1,67 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(6);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/direct_large/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/direct_large/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/direct_large/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/direct_large/validation_subset.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/direct_large/validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..4df83e69c4f9a3365955e5d17ffcfc0af71372b7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/direct_large/validation_subset.py @@ -0,0 +1,18 @@ +"""Model-selection-only subset spanning all 97 configurations, seed 2026.""" +import sys,json,copy +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +import ts_io + +root=Path('/workspace/data/valid');out=Path('/workspace/research/valid_screen') +idx=json.loads((root/'input/index.json').read_text());new=copy.deepcopy(idx);rng=np.random.default_rng(2026) +for cfg in new['configs']: + cid=cfg['config_id'];case=ts_io.CaseFile(root/'input/cases'/f'{cid}.h5') + ids=np.sort(rng.choice(case.n,min(case.n,192),replace=False)) + ts_io.write_case_subset(case,ids,out/'input/cases'/f'{cid}.h5') + lab,se,meta=ts_io.read_truth_file(root/'truth/cases'/f'{cid}.h5') + ts_io.write_truth_file(out/'truth/cases'/f'{cid}.h5',lab[ids],se[ids],meta) + cfg['n_instances']=len(ids);case.close() +for kind in ('input','truth'):(out/kind/'index.json').write_text(json.dumps(new,indent=1)) +print('screen instances',sum(c['n_instances'] for c in new['configs'])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/full_paired/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/full_paired/check.py new file mode 100644 index 0000000000000000000000000000000000000000..fda928e16338305fd9912f7bc08cacff58bd8aa4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/full_paired/check.py @@ -0,0 +1,34 @@ +import importlib.util,json,time +from pathlib import Path +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +r=Path('/workspace/research');torch.set_num_threads(1);torch.manual_seed(197);start=time.monotonic() +ck=torch.load(r/'horizon_delta12k.pt',map_location='cpu',weights_only=False) +spec=importlib.util.spec_from_file_location('parent_model',r/'confidence_inference/model.py') +old=importlib.util.module_from_spec(spec);spec.loader.exec_module(old) +parent=old.DirectForecaster(**ck['config']);parent.load_state_dict(ck['model']) +m=DirectForecaster(**ck['config']);m.load_state_dict(ck['model']) +x=torch.randn(4,512);x[0,:50]=float('nan');p=torch.tensor([[24,168]]*4);y=torch.randn(4,128);y[0,32:]=float('nan') +with torch.inference_mode(): + assert all(torch.equal(a,b) for a,b in zip(m(x,p,48),parent(x,p,48))) + short=m(x,p,32)[0];long=m(x,p,128,forecast_lengths=torch.full((4,),32))[0][:,:32] + assert torch.allclose(short,long,atol=3e-6,rtol=1e-6),(short-long).abs().max() + paired=float(loss_fn(m,x,y,p,paired=True));reverse=float(loss_fn(m,-x,-y,p,paired=True)) + assert abs(paired-reverse)<1e-7,(paired,reverse) +a=Sampler(r/'packed_sample',197);b=Sampler(r/'packed_sample',197) +for c,h in [(512,32),(4096,1024)]: + assert all(np.array_equal(v,w,equal_nan=True) for v,w in zip(a.sample(16,c,h),b.sample(16,c,h))) +assert a.rng.bit_generator.state==b.rng.bit_generator.state and a.horizon_rng.bit_generator.state==b.horizon_rng.bit_generator.state +cpu=time.monotonic()-start;del parent,ck,a,b +m=m.cuda();ema={k:v.detach().clone() for k,v in m.state_dict().items()} +moments=[torch.zeros_like(v) for v in m.parameters() for _ in range(2)] +torch.backends.cuda.matmul.allow_tf32=True;torch.cuda.reset_peak_memory_stats();start=time.monotonic() +x=torch.randn(64,4096,device='cuda');y=torch.randn(64,1024,device='cuda');p=torch.tensor([[24,168]]*64,device='cuda') +with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(m,x,y,p,paired=True) +loss.backward();torch.cuda.synchronize() +assert torch.isfinite(loss) and all(v.grad is not None and torch.isfinite(v.grad).all() for v in m.parameters()) +z={'cpu_seconds':cpu,'initial_forecast_bitwise_parent':True,'unused_future_tokens_do_not_change_requested_prefix':True,'paired_loss_sign_symmetric':True,'matched_sampler_main_and_horizon_rng':True,'gpu_fixture_seconds':time.monotonic()-start,'allocated_mib':torch.cuda.max_memory_allocated()/2**20,'reserved_mib':torch.cuda.max_memory_reserved()/2**20,'optimizer_updates':0} +(r/'full_paired_checks.json').write_text(json.dumps(z,indent=2));print(json.dumps(z),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/full_paired/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/full_paired/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/full_paired/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/full_paired/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/full_paired/model.py new file mode 100644 index 0000000000000000000000000000000000000000..dedcdff4698028a8ba655865f8425d0dc3ef0dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/full_paired/model.py @@ -0,0 +1,204 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/horizon_jitter/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/horizon_jitter/data.py new file mode 100644 index 0000000000000000000000000000000000000000..3d632af7e96a71f30b7964a2b3fd73bc1c3f3f3e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/horizon_jitter/data.py @@ -0,0 +1,86 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/horizon_jitter/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/horizon_jitter/model.py new file mode 100644 index 0000000000000000000000000000000000000000..4ffe50d9aadf21d73949e2052ceb7f3642bf65d3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/horizon_jitter/model.py @@ -0,0 +1,180 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(ctx,periods,target.shape[-1],forecast_lengths=lengths) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/horizon_jitter/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/horizon_jitter/train.py new file mode 100644 index 0000000000000000000000000000000000000000..768d33da4421b24bd760d7d9680d0c2cd9bd84e4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/horizon_jitter/train.py @@ -0,0 +1,74 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler,truncate_targets + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + horizon_rng=np.random.default_rng(a.seed+startstep+300003) + def nextbatch(): + 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])) + return truncate_targets(sampler.sample(a.batch,c,h),horizon_rng,a.patch) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_corpus/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_corpus/data.py new file mode 100644 index 0000000000000000000000000000000000000000..a51e912d3c4b63a3ec0cd85133bf0e7aa3429569 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_corpus/data.py @@ -0,0 +1,73 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_corpus/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_corpus/model.py new file mode 100644 index 0000000000000000000000000000000000000000..f8271c5b0bf9a5edb961e1c7839761fe50a2e40b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_corpus/model.py @@ -0,0 +1,171 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024,recency_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + if self.recency is not None: + pos=torch.arange(c,device=z.device)[None,:];extras=[] + for j in range(2): + period=periods[:,j:j+1] + recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_corpus/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_corpus/train.py new file mode 100644 index 0000000000000000000000000000000000000000..2e77612e443d78dd80bcb6a0cc6d01169f61a3a4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_corpus/train.py @@ -0,0 +1,73 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_sign/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_sign/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_sign/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_sign/evaluate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_sign/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..05f086d4d84def4a48165f9e65d2948877675e56 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_sign/evaluate.py @@ -0,0 +1,16 @@ +import sys,json,argparse,time,hashlib +from pathlib import Path +import torch +from predict import load_model,run +sys.path.insert(0,'/workspace/evaluation') +from score import score,json_safe + +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);ap.add_argument('--valid',default='/workspace/research/valid_screen');ap.add_argument('--baseline',default='/workspace/research/valid_screen/baseline.json');a=ap.parse_args() +torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cuda.matmul.allow_tf32=False +t0=time.time();out=Path(a.out);v=Path(a.valid) +run(load_model(a.weights),v/'input',out) +base=json.loads(Path(a.baseline).read_text())['configs'] +rep=score(v/'truth',out,base) +rep['checkpoint_sha256']=hashlib.sha256(Path(a.weights).read_bytes()).hexdigest();rep['eval_seconds']=time.time()-t0 +(out/'report.json').write_text(json.dumps(json_safe(rep),indent=1)) +print(json.dumps({k:rep[k] for k in ('skill_score','rel_mase_gmean','rel_wql_gmean','n_failed','groups','eval_seconds')},indent=1)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_sign/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_sign/model.py new file mode 100644 index 0000000000000000000000000000000000000000..60aeb14b5f4fa298521ddce8a3276d076c1bb631 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_sign/model.py @@ -0,0 +1,154 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional(torch.arange(-nt,0,device=z.device),self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + q=self.query(base.reshape(b,h//p,p*9))+positional(torch.arange(h//p,device=z.device),self.d)[None]+emb + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_sign/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_sign/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_sign/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_sign/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_sign/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..e20c6630475d6b4fa6906eb4ed9454b7b5aeec2c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_sign/predict.py @@ -0,0 +1,43 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):q=model.predict(x,p,h).float().cpu().numpy() + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_sign/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_sign/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf95c9aec5936076b881c340edb960786f2d40d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_sign/publish.py @@ -0,0 +1,31 @@ +"""Assemble a relocatable package, then atomically exchange complete directories.""" +import json,os,shutil,ctypes,hashlib,argparse +from pathlib import Path +import torch +HERE=Path(__file__).resolve().parent + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',default='/workspace/submission');ap.add_argument('--report',required=True);ap.add_argument('--experiments',default=str(HERE/'EXPERIMENTS.md'));a=ap.parse_args() + final=Path(a.out);staging=final.parent/f'.{final.name}-staging-{os.getpid()}' + shutil.rmtree(staging,ignore_errors=True);staging.mkdir(parents=True) + for file in ('model.py','predict.py','infer.sh','ts_io.py'): + shutil.copy(HERE/file,staging/file) + shutil.copy(a.weights,staging/'weights.pt');shutil.copy('/opt/runtime/requirements.txt',staging/'requirements.txt') + ck=torch.load(a.weights,map_location='cpu',weights_only=False);digest=hashlib.sha256((staging/'weights.pt').read_bytes()).hexdigest() + sources=json.loads(Path('/workspace/research/packed_sample/meta.json').read_text())['dirs'] + manifest={'name':'direct-seasonal-quantile-v1','contract':'timeseries-forecast/v1','parameters':sum(x.numel() for x in ck['model'].values()),'pretrained_assets':[],'sources_used':[f'gifteval_pretrain/{d}' for d in sources]+['synthetic:direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; data.py generator seed 17'],'weights_sha256':digest,'training_step':ck['step'],'config':ck['config'],'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.'} + (staging/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') + (staging/'config.json').write_text(json.dumps(ck['config'],indent=2)+'\n') + shutil.copy(a.experiments,staging/'EXPERIMENTS.md');shutil.copy(a.report,staging/'validation_report.json') + # Include generator/sampler provenance, which is not imported by inference. + (staging/'provenance').mkdir() + for file in ('pack.py','data.py','train.py'):shutil.copy(HERE/file,staging/'provenance'/file) + (staging/'README.md').write_text('# Direct seasonal quantile foundation forecaster\n\nRun `bash infer.sh INPUT_DIR OUTPUT_DIR`. This package contains all inference assets and uses only its supplied input directory. The 6.76M 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.\n\nThe 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.\n') + if final.exists(): + libc=ctypes.CDLL(None,use_errno=True) + if libc.renameat2(-100,os.fsencode(staging),-100,os.fsencode(final),2):raise OSError(ctypes.get_errno(),os.strerror(ctypes.get_errno())) + shutil.rmtree(staging) + else:os.replace(staging,final) + print(json.dumps(manifest,indent=1)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_sign/record.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_sign/record.py new file mode 100644 index 0000000000000000000000000000000000000000..1850a33f46fa3ee4d78cac4a5d6152404801a131 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_sign/record.py @@ -0,0 +1,9 @@ +import argparse,json,math +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('report');ap.add_argument('--label',required=True);ap.add_argument('--outcome',default='Screened for model selection.');a=ap.parse_args() +r=json.loads(Path(a.report).read_text());p=Path(__file__).with_name('EXPERIMENTS.md') +lines=[f'\n## {a.label}',f'- Checkpoint SHA-256: `{r.get("checkpoint_sha256","see model_manifest.json")}`.',f'- Evaluation: {r["n_configs"]} configurations, {r["n_instances"]} instances, {r["n_failed"]} failed configurations; {r.get("eval_seconds","not separately timed")} seconds.',f'- Overall skill {r["skill_score"]:.6f}; relative MASE {r["rel_mase_gmean"]:.6f}; relative WQL {r["rel_wql_gmean"]:.6f}.'] +for group,entries in r['groups'].items(): + lines.append(f'- {group} skill: '+', '.join(f'{k}={1-math.sqrt(v["rel_mase_gmean"]*v["rel_wql_gmean"]):.4f}' for k,v in entries.items())+'.') +lines.append('- Outcome: '+a.outcome) +with p.open('a') as f:f.write('\n'.join(lines)+'\n') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_sign/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_sign/train.py new file mode 100644 index 0000000000000000000000000000000000000000..d089166fb1612ddf4955fcd2f096cb0b33624dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_sign/train.py @@ -0,0 +1,70 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(3);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_sign/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_sign/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_sign/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_sign/validation_subset.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_sign/validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..4df83e69c4f9a3365955e5d17ffcfc0af71372b7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/large_sign/validation_subset.py @@ -0,0 +1,18 @@ +"""Model-selection-only subset spanning all 97 configurations, seed 2026.""" +import sys,json,copy +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +import ts_io + +root=Path('/workspace/data/valid');out=Path('/workspace/research/valid_screen') +idx=json.loads((root/'input/index.json').read_text());new=copy.deepcopy(idx);rng=np.random.default_rng(2026) +for cfg in new['configs']: + cid=cfg['config_id'];case=ts_io.CaseFile(root/'input/cases'/f'{cid}.h5') + ids=np.sort(rng.choice(case.n,min(case.n,192),replace=False)) + ts_io.write_case_subset(case,ids,out/'input/cases'/f'{cid}.h5') + lab,se,meta=ts_io.read_truth_file(root/'truth/cases'/f'{cid}.h5') + ts_io.write_truth_file(out/'truth/cases'/f'{cid}.h5',lab[ids],se[ids],meta) + cfg['n_instances']=len(ids);case.close() +for kind in ('input','truth'):(out/kind/'index.json').write_text(json.dumps(new,indent=1)) +print('screen instances',sum(c['n_instances'] for c in new['configs'])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/partial_delta/merge.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/partial_delta/merge.py new file mode 100644 index 0000000000000000000000000000000000000000..3dde47d52d25ed2b013942b3887f1bf686e42ed8 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/partial_delta/merge.py @@ -0,0 +1,16 @@ +"""Apply the difference of two matched, locally trained checkpoints to our selected model.""" +import argparse,torch,hashlib,json,time +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('--base',required=True);ap.add_argument('--candidate',required=True);ap.add_argument('--control',required=True);ap.add_argument('--out',required=True);a=ap.parse_args() +torch.set_num_threads(1);start=time.monotonic() +base=torch.load(a.base,map_location='cpu',weights_only=False);candidate=torch.load(a.candidate,map_location='cpu',weights_only=False);control=torch.load(a.control,map_location='cpu',weights_only=False) +assert set(candidate['model'])==set(control['model']) +weights={k:v.clone() for k,v in base['model'].items()} +for k in candidate['model']: + assert k in weights and weights[k].shape==candidate['model'][k].shape==control['model'][k].shape + weights[k].add_(candidate['model'][k]-control['model'][k]) +assert all(torch.isfinite(v).all() for v in weights.values()) +parents=[a.base,a.candidate,a.control] +conversion={'method':'matched training delta','formula':'base + candidate - control','coefficient':1.0,'parent_hashes':{p:hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in parents},'seconds':time.monotonic()-start} +ck={'model':weights,'config':base['config'],'step':0,'args':{'packed':base['args']['packed']},'parent_checkpoints':parents,'conversion':conversion} +torch.save(ck,a.out);print(json.dumps(conversion)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/partial_targets/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/partial_targets/data.py new file mode 100644 index 0000000000000000000000000000000000000000..a51e912d3c4b63a3ec0cd85133bf0e7aa3429569 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/partial_targets/data.py @@ -0,0 +1,73 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/partial_targets/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/partial_targets/model.py new file mode 100644 index 0000000000000000000000000000000000000000..4ffe50d9aadf21d73949e2052ceb7f3642bf65d3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/partial_targets/model.py @@ -0,0 +1,180 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(ctx,periods,target.shape[-1],forecast_lengths=lengths) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/partial_targets/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/partial_targets/train.py new file mode 100644 index 0000000000000000000000000000000000000000..2e77612e443d78dd80bcb6a0cc6d01169f61a3a4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/partial_targets/train.py @@ -0,0 +1,73 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/convert.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/convert.py new file mode 100644 index 0000000000000000000000000000000000000000..b2cbc8fc919be6a77eca9ab19c4faa06060a2e0d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/convert.py @@ -0,0 +1,18 @@ +"""Convert only our own trained checkpoint from 32- to 16-point patches. + +Context/query projections fold the two halves by summation, preserving the +embedding of constant features. The output projection keeps the first half. +Attention/MLP weights are inherited unchanged; position units remain 32 points. +""" +import argparse,torch,hashlib +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('--input',required=True);ap.add_argument('--output',required=True);a=ap.parse_args() +ck=torch.load(a.input,map_location='cpu',weights_only=False);state=ck['model'];d=ck['config']['d'];assert ck['config']['patch']==32 +old=state['embed.0.weight'].reshape(d,2,32);state['embed.0.weight']=(old[:,:,:16]+old[:,:,16:]).reshape(d,32) +old=state['query.0.weight'].reshape(d,32,9);state['query.0.weight']=(old[:,:16]+old[:,16:]).reshape(d,16*9) +state['head.weight']=state['head.weight'].reshape(32,18,d)[:16].reshape(16*18,d).clone() +state['head.bias']=state['head.bias'].reshape(32,18)[:16].reshape(16*18).clone() +ck['config']['patch']=16 +ck['conversion']={'from_checkpoint':str(Path(a.input).resolve()),'from_sha256':hashlib.sha256(Path(a.input).read_bytes()).hexdigest(),'method':'fold input/query halves by summation; retain first 16 output rows; preserve physical positional units'} +ck['args']={**ck['args'],'initialize_from':str(Path(a.input).resolve()),'converted':True} +torch.save(ck,a.output) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/evaluate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..05f086d4d84def4a48165f9e65d2948877675e56 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/evaluate.py @@ -0,0 +1,16 @@ +import sys,json,argparse,time,hashlib +from pathlib import Path +import torch +from predict import load_model,run +sys.path.insert(0,'/workspace/evaluation') +from score import score,json_safe + +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);ap.add_argument('--valid',default='/workspace/research/valid_screen');ap.add_argument('--baseline',default='/workspace/research/valid_screen/baseline.json');a=ap.parse_args() +torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cuda.matmul.allow_tf32=False +t0=time.time();out=Path(a.out);v=Path(a.valid) +run(load_model(a.weights),v/'input',out) +base=json.loads(Path(a.baseline).read_text())['configs'] +rep=score(v/'truth',out,base) +rep['checkpoint_sha256']=hashlib.sha256(Path(a.weights).read_bytes()).hexdigest();rep['eval_seconds']=time.time()-t0 +(out/'report.json').write_text(json.dumps(json_safe(rep),indent=1)) +print(json.dumps({k:rep[k] for k in ('skill_score','rel_mase_gmean','rel_wql_gmean','n_failed','groups','eval_seconds')},indent=1)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/model.py new file mode 100644 index 0000000000000000000000000000000000000000..06cce56e2ce671b6683f0246900abfcac06bb3c0 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/model.py @@ -0,0 +1,154 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..e20c6630475d6b4fa6906eb4ed9454b7b5aeec2c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/predict.py @@ -0,0 +1,43 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):q=model.predict(x,p,h).float().cpu().numpy() + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf95c9aec5936076b881c340edb960786f2d40d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/publish.py @@ -0,0 +1,31 @@ +"""Assemble a relocatable package, then atomically exchange complete directories.""" +import json,os,shutil,ctypes,hashlib,argparse +from pathlib import Path +import torch +HERE=Path(__file__).resolve().parent + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',default='/workspace/submission');ap.add_argument('--report',required=True);ap.add_argument('--experiments',default=str(HERE/'EXPERIMENTS.md'));a=ap.parse_args() + final=Path(a.out);staging=final.parent/f'.{final.name}-staging-{os.getpid()}' + shutil.rmtree(staging,ignore_errors=True);staging.mkdir(parents=True) + for file in ('model.py','predict.py','infer.sh','ts_io.py'): + shutil.copy(HERE/file,staging/file) + shutil.copy(a.weights,staging/'weights.pt');shutil.copy('/opt/runtime/requirements.txt',staging/'requirements.txt') + ck=torch.load(a.weights,map_location='cpu',weights_only=False);digest=hashlib.sha256((staging/'weights.pt').read_bytes()).hexdigest() + sources=json.loads(Path('/workspace/research/packed_sample/meta.json').read_text())['dirs'] + manifest={'name':'direct-seasonal-quantile-v1','contract':'timeseries-forecast/v1','parameters':sum(x.numel() for x in ck['model'].values()),'pretrained_assets':[],'sources_used':[f'gifteval_pretrain/{d}' for d in sources]+['synthetic:direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; data.py generator seed 17'],'weights_sha256':digest,'training_step':ck['step'],'config':ck['config'],'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.'} + (staging/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') + (staging/'config.json').write_text(json.dumps(ck['config'],indent=2)+'\n') + shutil.copy(a.experiments,staging/'EXPERIMENTS.md');shutil.copy(a.report,staging/'validation_report.json') + # Include generator/sampler provenance, which is not imported by inference. + (staging/'provenance').mkdir() + for file in ('pack.py','data.py','train.py'):shutil.copy(HERE/file,staging/'provenance'/file) + (staging/'README.md').write_text('# Direct seasonal quantile foundation forecaster\n\nRun `bash infer.sh INPUT_DIR OUTPUT_DIR`. This package contains all inference assets and uses only its supplied input directory. The 6.76M 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.\n\nThe 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.\n') + if final.exists(): + libc=ctypes.CDLL(None,use_errno=True) + if libc.renameat2(-100,os.fsencode(staging),-100,os.fsencode(final),2):raise OSError(ctypes.get_errno(),os.strerror(ctypes.get_errno())) + shutil.rmtree(staging) + else:os.replace(staging,final) + print(json.dumps(manifest,indent=1)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/record.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/record.py new file mode 100644 index 0000000000000000000000000000000000000000..1850a33f46fa3ee4d78cac4a5d6152404801a131 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/record.py @@ -0,0 +1,9 @@ +import argparse,json,math +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('report');ap.add_argument('--label',required=True);ap.add_argument('--outcome',default='Screened for model selection.');a=ap.parse_args() +r=json.loads(Path(a.report).read_text());p=Path(__file__).with_name('EXPERIMENTS.md') +lines=[f'\n## {a.label}',f'- Checkpoint SHA-256: `{r.get("checkpoint_sha256","see model_manifest.json")}`.',f'- Evaluation: {r["n_configs"]} configurations, {r["n_instances"]} instances, {r["n_failed"]} failed configurations; {r.get("eval_seconds","not separately timed")} seconds.',f'- Overall skill {r["skill_score"]:.6f}; relative MASE {r["rel_mase_gmean"]:.6f}; relative WQL {r["rel_wql_gmean"]:.6f}.'] +for group,entries in r['groups'].items(): + lines.append(f'- {group} skill: '+', '.join(f'{k}={1-math.sqrt(v["rel_mase_gmean"]*v["rel_wql_gmean"]):.4f}' for k,v in entries.items())+'.') +lines.append('- Outcome: '+a.outcome) +with p.open('a') as f:f.write('\n'.join(lines)+'\n') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/train.py new file mode 100644 index 0000000000000000000000000000000000000000..3cdc106980371c99d81c71d6746943c47206be83 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/train.py @@ -0,0 +1,71 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(3);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/validation_subset.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..4df83e69c4f9a3365955e5d17ffcfc0af71372b7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch16/validation_subset.py @@ -0,0 +1,18 @@ +"""Model-selection-only subset spanning all 97 configurations, seed 2026.""" +import sys,json,copy +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +import ts_io + +root=Path('/workspace/data/valid');out=Path('/workspace/research/valid_screen') +idx=json.loads((root/'input/index.json').read_text());new=copy.deepcopy(idx);rng=np.random.default_rng(2026) +for cfg in new['configs']: + cid=cfg['config_id'];case=ts_io.CaseFile(root/'input/cases'/f'{cid}.h5') + ids=np.sort(rng.choice(case.n,min(case.n,192),replace=False)) + ts_io.write_case_subset(case,ids,out/'input/cases'/f'{cid}.h5') + lab,se,meta=ts_io.read_truth_file(root/'truth/cases'/f'{cid}.h5') + ts_io.write_truth_file(out/'truth/cases'/f'{cid}.h5',lab[ids],se[ids],meta) + cfg['n_instances']=len(ids);case.close() +for kind in ('input','truth'):(out/kind/'index.json').write_text(json.dumps(new,indent=1)) +print('screen instances',sum(c['n_instances'] for c in new['configs'])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch8/convert.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch8/convert.py new file mode 100644 index 0000000000000000000000000000000000000000..f758dcbc0d48b531889b71dc758a7d2fb9a3afb7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch8/convert.py @@ -0,0 +1,44 @@ +"""Convert our own 16-point model to 8-point patches, without external assets.""" +import argparse +import hashlib +import json +import time +from pathlib import Path + +import torch + +ap=argparse.ArgumentParser() +ap.add_argument('--input',required=True) +ap.add_argument('--output',required=True) +a=ap.parse_args() +torch.set_num_threads(2) +started=time.monotonic() +ck=torch.load(a.input,map_location='cpu',weights_only=False) +state=ck['model']; d=ck['config']['d'] +assert ck['config']['patch']==16 +old=state['embed.0.weight'].reshape(d,2,16) +state['embed.0.weight']=(old[:,:,:8]+old[:,:,8:]).reshape(d,16) +old=state['query.0.weight'].reshape(d,16,9) +state['query.0.weight']=(old[:,:8]+old[:,8:]).reshape(d,8*9) +if 'recency.weight' in state: + old=state['recency.weight'].reshape(d,16,4) + state['recency.weight']=(old[:,:8]+old[:,8:]).reshape(d,8*4) +state['head.weight']=state['head.weight'].reshape(16,18,d)[:8].reshape(8*18,d).clone() +state['head.bias']=state['head.bias'].reshape(16,18)[:8].reshape(8*18).clone() +ck['config']['patch']=8 +ck['config']['partial_target_lengths']=True +ck['conversion']={ + 'from_checkpoint':str(Path(a.input).resolve()), + 'from_sha256':hashlib.sha256(Path(a.input).read_bytes()).hexdigest(), + 'method':'fold input/query/recency halves by summation; retain first8 output rows; preserve physical position units', + 'exact_function_preservation':False} +ck['args']={**ck['args'],'initialize_from':str(Path(a.input).resolve()),'converted':True} +ck['parent_checkpoints']=[str(Path(a.input).resolve())] +torch.save(ck,a.output) +receipt=dict(input_sha256=ck['conversion']['from_sha256'], + checkpoint_sha256=hashlib.sha256(Path(a.output).read_bytes()).hexdigest(), + parameters=sum(v.numel() for v in state.values()), + cpu_seconds=time.monotonic()-started, + optimizer_updates=0,conversion=ck['conversion']) +Path(a.output).with_suffix('.json').write_text(json.dumps(receipt,indent=2)) +print(json.dumps(receipt)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch8/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch8/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch8/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch8/memory_check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch8/memory_check.py new file mode 100644 index 0000000000000000000000000000000000000000..d55bebeab8c6ff393f89b7ad031763f49531f56b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch8/memory_check.py @@ -0,0 +1,23 @@ +"""Maximum training-shape memory fixture, serialized with validation jobs.""" +import fcntl,json,sys,time +from pathlib import Path +import torch + +r=Path('/workspace/research');sys.path.insert(0,str(r/'patch8')) +from model import DirectForecaster,loss_fn +from data import Sampler +with open(r/'.evaluation.lock','a') as lock: + fcntl.flock(lock,fcntl.LOCK_EX) + torch.set_num_threads(1);torch.manual_seed(277);torch.backends.cuda.matmul.allow_tf32=True + started=time.monotonic() + ck=torch.load(r/'patch8_initial.pt',map_location='cpu',weights_only=False) + m=DirectForecaster(**ck['config']).cuda();m.load_state_dict(ck['model']) + x,y,p=[torch.from_numpy(a).cuda() for a in Sampler(r/'packed_sample',277).sample(64,4096,1024)] + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(m,x,y,p,paired=True) + loss.backward();torch.cuda.synchronize() + assert all(v.grad is not None and torch.isfinite(v.grad).all() for v in m.parameters()) + result={'seed':277,'batch':64,'signed_rows':128,'context':4096,'horizon':1024, + 'optimizer_updates':0,'loss':float(loss.detach()),'seconds':time.monotonic()-started, + 'peak_allocated_mib':torch.cuda.max_memory_allocated()/2**20, + 'peak_reserved_mib':torch.cuda.max_memory_reserved()/2**20} + (r/'patch8_memory_check.json').write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch8/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch8/model.py new file mode 100644 index 0000000000000000000000000000000000000000..dedcdff4698028a8ba655865f8425d0dc3ef0dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/patch8/model.py @@ -0,0 +1,204 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/recency_features/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/recency_features/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/recency_features/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/recency_features/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/recency_features/model.py new file mode 100644 index 0000000000000000000000000000000000000000..f8271c5b0bf9a5edb961e1c7839761fe50a2e40b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/recency_features/model.py @@ -0,0 +1,171 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024,recency_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + if self.recency is not None: + pos=torch.arange(c,device=z.device)[None,:];extras=[] + for j in range(2): + period=periods[:,j:j+1] + recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/recency_features/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/recency_features/train.py new file mode 100644 index 0000000000000000000000000000000000000000..3bfb8b90f1a6656881b7598f864becaa737a76f4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/recency_features/train.py @@ -0,0 +1,73 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(3);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/recovery/capacity_curves.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/recovery/capacity_curves.py new file mode 100644 index 0000000000000000000000000000000000000000..c89a28a84243dc16ae52a1215c182a00f15dbc4e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/recovery/capacity_curves.py @@ -0,0 +1,50 @@ +"""Summarize completed validation checkpoints and measured shared-GPU training time.""" +import csv +import json +import time +from pathlib import Path + +R = Path('/workspace/research') +started = time.monotonic() +names = ['random_capacity_512', 'random_capacity_1024', 'random_capacity_1024_halflr', + 'random_capacity_full', 'distill_ensemble', 'random_capacity_512_anneal'] +rows = [] +for name in names: + log = R/(name+'_train.log') + records = {} + if log.exists(): + for line in log.read_text().splitlines(): + try: + item = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(item,dict) and 'step' in item and 'seconds' in item: + records[item['step']] = item + config_path = R/'runs'/name/'config.json' + config = json.loads(config_path.read_text()) if config_path.exists() else {} + for report in sorted((R/'evals').glob(name+'_ema*/report.json')): + result = json.loads(report.read_text()) + step = int(report.parent.name.rsplit('ema',1)[1]) + if result['n_failed']: + continue + record = records.get(step,{}) + rows.append(dict(run=name,step=step,parameters=config.get('parameters'), + seed=config.get('seed'),batch=config.get('batch'),learning_rate=config.get('lr'), + packed=config.get('packed'),skill=result['skill_score'], + rel_mase=result['rel_mase_gmean'],rel_wql=result['rel_wql_gmean'], + checkpoint_sha256=result['checkpoint_sha256'], + training_phase_loop_seconds=record.get('seconds'), + evaluation_seconds=result.get('eval_seconds'),report=str(report))) +rows.sort(key=lambda item:(names.index(item['run']),item['step'])) +output = dict(generated_utc=time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()), + note='Validation selection only. Time is logged process wall on the shared single H100, not isolated GPU time. The cooldown arm starts from the same saved24000state; its phase clock resets. No missing log time is inferred.', + rows=rows,analysis_seconds=time.monotonic()-started,no_training_or_new_inference=True) +(R/'capacity_learning_curves.json').write_text(json.dumps(output,indent=2)) +with (R/'capacity_learning_curves.csv').open('w',newline='') as handle: + writer = csv.DictWriter(handle,fieldnames=list(rows[0]) if rows else ['run']) + writer.writeheader() + writer.writerows(rows) +for name in names: + selected = [r for r in rows if r['run']==name] + if selected: + print(json.dumps(selected[-1])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/recovery/exposure_audit.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/recovery/exposure_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..fb67738bc9ed77f87173feda2430365e66c75966 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/recovery/exposure_audit.py @@ -0,0 +1,46 @@ +"""Describe sampled observation exposure and training invested in selected ancestry.""" +import json +import sys +import time +from pathlib import Path +import numpy as np + +R=Path('/workspace/research') +sys.path.insert(0,str(R/'random_capacity')) +from data import Sampler + +started=time.monotonic() +seed=521 +sampler=Sampler(R/'packed_sample',seed=seed,source_weights_from=R/'packed_sample') +rng=np.random.default_rng(seed) +rows=context_points=target_points=0 +for _ in range(320): + 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])) + x,y,p=sampler.sample(64,c,h) + rows+=len(x) + context_points+=int(np.isfinite(x).sum()) + target_points+=int(np.isfinite(y).sum()) +manifest=json.loads(Path('/workspace/submission/model_manifest.json').read_text()) +runs={} +for item in manifest['training_lineage']: + path=Path(item['checkpoint']) + batch=item.get('training_settings',{}).get('batch') + if path.parts[0]!='runs' or not batch: + continue + run=path.parts[1] + step=item.get('step',0) + if step>runs.get(run,{}).get('step',0): + runs[run]=dict(step=step,batch=batch,rows=step*batch,checkpoint=item['checkpoint']) +ancestral_rows=sum(v['rows'] for v in runs.values()) +mean_points=(context_points+target_points)/rows +result=dict(seed=seed,seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False, + sampled_rows=rows,mean_finite_context_points=context_points/rows, + mean_finite_target_points=target_points/rows,mean_finite_points=mean_points, + selected_descriptor=manifest['checkpoint_sha256'],ancestral_runs=runs, + selected_ancestral_rows_before_sign_pairing=ancestral_rows, + fresh96000_batch48_rows=96000*48, + fresh96000_batch48_gross_observation_presentations_estimate=96000*48*mean_points, + note='Gross sampled presentations include overlapping/resampled windows and synthetic values, not unique observations. Ancestral run maxima count compute invested in different branches, including subtracted controls; they are not an equivalent single-model training trajectory. Sign pairing duplicates compute but not distinct sampled rows. No future training recipe is inferred from this audit alone.') +(R/'training_exposure_audit.json').write_text(json.dumps(result,indent=2)) +print(json.dumps({k:v for k,v in result.items() if k!='ancestral_runs'})) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/recovery/relaunch_20261022b.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/recovery/relaunch_20261022b.py new file mode 100644 index 0000000000000000000000000000000000000000..d16fc19cbbb86dba2ff53b445e368b8bbd2ca218 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/recovery/relaunch_20261022b.py @@ -0,0 +1,105 @@ +"""Resume interrupted research jobs and preserve phase-specific recovery receipts.""" +import datetime +import json +import os +from pathlib import Path +import shutil +import subprocess +import time + +R = Path('/workspace/research') +TAG = 'recovery2' +env = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1') +receipt = {'recovery_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(), + 'remaining_research_seconds_at_operator_recovery': 152594, + 'jobs': {}, 'queues': {}} +children = {} + +def launch(name, command, phase=TAG): + log = R / f'{name}_{phase}.log' + assert not log.exists(), log + with log.open('w') as f: + child = subprocess.Popen(command, stdout=f, stderr=subprocess.STDOUT, env=env) + children[name] = child + return {'pid': child.pid, 'command': command, 'log': str(log), 'started_monotonic': time.monotonic()} + +def persist(): + path = R / f'{TAG}_launch_receipt.json' + tmp = path.with_suffix('.tmp') + tmp.write_text(json.dumps(receipt, indent=2)); os.replace(tmp, path) + +for name in ['wide_capacity_146m_recovery', 'wide_capacity_control_recovery', + 'long_memory_synth_recovery', 'recent_normalization_recovery', 'wide_graft', 'patch8']: + run = R / 'runs' / name + cfg = json.loads((run / 'config.json').read_text()) + shutil.copy2(run / 'config.json', run / f'config_before_{TAG}.json') + command = ['python3', str(R / 'recovery/train.py')] + for key in ['code_dir', 'packed', 'source_weights_from', 'out', 'initialize_from', + 'initialize_ema', 'start_step', 'steps', 'batch', 'lr', 'seed', 'context', + 'sample_context', 'save_every', 'stop_file', 'reset_at', 'reset_seed', 'loss_mode']: + if cfg.get(key) is not None: + command += ['--' + key.replace('_', '-'), str(cfg[key])] + if (run / 'recovery.pt').exists(): + command += ['--resume', str(run / 'recovery.pt')] + mode = 'complete optimizer/EMA/RNG/prefetched-batch resume' + else: + mode = 'restart saved own initialization; no complete checkpoint existed' + if cfg.get('compile_loss'): + command += ['--compile-loss'] + command = ['env', 'TORCHINDUCTOR_COMPILE_THREADS=2', 'MAX_JOBS=2', + 'PYTHONPATH=/workspace/research/compiler_support', + 'TRITON_CACHE_MANAGER=sibling_cache:SiblingFileCacheManager', + 'TRITON_CACHE_DIR=/tmp/timeseries-triton-cache', + 'TORCHINDUCTOR_CACHE_DIR=/tmp/timeseries-inductor-cache'] + command + assert not Path(cfg['stop_file']).exists(), cfg['stop_file'] + receipt['jobs'][name] = dict(launch(name, command), mode=mode) + persist() + +watch_specs = { + 'wide_capacity_146m_recovery': ('wide_capacity_inference', '24000,32000'), + 'wide_capacity_control_recovery': ('wide_capacity_inference', '24000,32000'), + 'long_memory_synth_recovery': ('partial_targets_inference', '12000'), + 'recent_normalization_recovery': ('recent_normalization_inference', '12000'), + 'wide_graft': ('wide_graft_inference', '4000,8000,12000,16000,24000,32000'), + 'patch8': ('full_paired_inference', '1000,3000,6000,12000'), + 'volatility_synth': ('partial_targets_inference', '3000,6000,12000'), + 'postloss': ('full_paired_inference', '1000,3000,6000,12000'), + 'paired_long_memory': ('full_paired_inference', '1000,3000,6000,12000'), +} +for name, (runtime, steps) in watch_specs.items(): + command = ['python3', str(R / 'watch_evaluate.py'), '--run', str(R / 'runs' / name), + '--evaluator', str(R / runtime / 'evaluate.py'), '--name', name, '--steps', steps] + launch(name + '_watch', command) + +queue_specs = {'volatility_synth': 'long_memory_synth_recovery', + 'postloss': 'recent_normalization_recovery', + 'paired_long_memory': 'wide_capacity_control_recovery'} +for name, dependency in queue_specs.items(): + old = json.loads((R / (name + '_queue.json')).read_text()) + shutil.copy2(R / (name + '_queue.json'), R / (name + '_queue_before_' + TAG + '.json')) + receipt['queues'][name] = dict(old, dependency=dependency, status='waiting', + wait_pids=[children[dependency].pid]) +persist() + +while True: + for name, job in receipt['jobs'].items(): + if 'returncode' not in job and children[name].poll() is not None: + job.update(returncode=children[name].returncode, + phase_seconds=time.monotonic() - job['started_monotonic']) + persist() + for name, queue in receipt['queues'].items(): + if queue['status'] == 'waiting' and children[queue['dependency']].poll() is not None: + if children[queue['dependency']].returncode != 0 or not all(Path(p).exists() for p in queue['required_checkpoints']): + queue['status'] = 'blocked_by_incomplete_dependency' + else: + receipt['jobs'][name] = launch(name, queue['command']) + queue.update(status='running', pid=children[name].pid, + started_utc=datetime.datetime.now(datetime.timezone.utc).isoformat()) + with (R / 'direct_v1/EXPERIMENTS.md').open('a') as f: + f.write(f'\n{name} started {queue["started_utc"]} after {queue["dependency"]} completed. Original predeclared settings and seed retained.\n') + (R / (name + '_queue.json')).write_text(json.dumps(queue, indent=2)) + persist() + if all(p.poll() is not None for n,p in children.items() if not n.endswith('_watch')) and all(q['status'] != 'waiting' for q in receipt['queues'].values()): + break + time.sleep(5) +persist() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/recovery/relaunch_20261023.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/recovery/relaunch_20261023.py new file mode 100644 index 0000000000000000000000000000000000000000..5f35a9cfcbe7ea66c8837b6d4ada8b84be36b934 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/recovery/relaunch_20261023.py @@ -0,0 +1,104 @@ +"""Resume interrupted research jobs and preserve phase-specific recovery receipts.""" +import datetime +import json +import os +from pathlib import Path +import shutil +import subprocess +import time + +R = Path('/workspace/research') +TAG = 'recovery3' +env = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1') +receipt = {'recovery_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(), + 'remaining_research_seconds_at_operator_recovery': 151596, + 'jobs': {}, 'queues': {}} +children = {} + +def launch(name, command, phase=TAG): + log = R / f'{name}_{phase}.log' + assert not log.exists(), log + with log.open('w') as f: + child = subprocess.Popen(command, stdout=f, stderr=subprocess.STDOUT, env=env) + children[name] = child + return {'pid': child.pid, 'command': command, 'log': str(log), 'started_monotonic': time.monotonic()} + +def persist(): + path = R / f'{TAG}_launch_receipt.json' + tmp = path.with_suffix('.tmp') + tmp.write_text(json.dumps(receipt, indent=2)); os.replace(tmp, path) + +for name in ['wide_capacity_146m_recovery', 'wide_capacity_control_recovery', + 'long_memory_synth_recovery', 'wide_graft', 'patch8']: + run = R / 'runs' / name + cfg = json.loads((run / 'config.json').read_text()) + shutil.copy2(run / 'config.json', run / f'config_before_{TAG}.json') + command = ['python3', str(R / 'recovery/train.py')] + for key in ['code_dir', 'packed', 'source_weights_from', 'out', 'initialize_from', + 'initialize_ema', 'start_step', 'steps', 'batch', 'lr', 'seed', 'context', + 'sample_context', 'save_every', 'stop_file', 'reset_at', 'reset_seed', 'loss_mode']: + if cfg.get(key) is not None: + command += ['--' + key.replace('_', '-'), str(cfg[key])] + if (run / 'recovery.pt').exists(): + command += ['--resume', str(run / 'recovery.pt')] + mode = 'complete optimizer/EMA/RNG/prefetched-batch resume' + else: + mode = 'restart saved own initialization; no complete checkpoint existed' + if cfg.get('compile_loss'): + command += ['--compile-loss'] + command = ['env', 'TORCHINDUCTOR_COMPILE_THREADS=2', 'MAX_JOBS=2', + 'PYTHONPATH=/workspace/research/compiler_support', + 'TRITON_CACHE_MANAGER=sibling_cache:SiblingFileCacheManager', + 'TRITON_CACHE_DIR=/tmp/timeseries-triton-cache', + 'TORCHINDUCTOR_CACHE_DIR=/tmp/timeseries-inductor-cache'] + command + assert not Path(cfg['stop_file']).exists(), cfg['stop_file'] + receipt['jobs'][name] = dict(launch(name, command), mode=mode) + persist() + +watch_specs = { + 'wide_capacity_146m_recovery': ('wide_capacity_inference', '24000,32000'), + 'wide_capacity_control_recovery': ('wide_capacity_inference', '24000,32000'), + 'long_memory_synth_recovery': ('partial_targets_inference', '12000'), + 'recent_normalization_recovery': ('recent_normalization_inference', '12000'), + 'wide_graft': ('wide_graft_inference', '4000,8000,12000,16000,24000,32000'), + 'patch8': ('full_paired_inference', '1000,3000,6000,12000'), + 'volatility_synth': ('partial_targets_inference', '3000,6000,12000'), + 'postloss': ('full_paired_inference', '1000,3000,6000,12000'), + 'paired_long_memory': ('full_paired_inference', '1000,3000,6000,12000'), +} +for name, (runtime, steps) in watch_specs.items(): + command = ['python3', str(R / 'watch_evaluate.py'), '--run', str(R / 'runs' / name), + '--evaluator', str(R / runtime / 'evaluate.py'), '--name', name, '--steps', steps] + launch(name + '_watch', command) + +queue_specs = {'volatility_synth': 'long_memory_synth_recovery', + 'paired_long_memory': 'wide_capacity_control_recovery'} +for name, dependency in queue_specs.items(): + old = json.loads((R / (name + '_queue.json')).read_text()) + shutil.copy2(R / (name + '_queue.json'), R / (name + '_queue_before_' + TAG + '.json')) + receipt['queues'][name] = dict(old, dependency=dependency, status='waiting', + wait_pids=[children[dependency].pid]) +persist() + +while True: + for name, job in receipt['jobs'].items(): + if 'returncode' not in job and children[name].poll() is not None: + job.update(returncode=children[name].returncode, + phase_seconds=time.monotonic() - job['started_monotonic']) + persist() + for name, queue in receipt['queues'].items(): + if queue['status'] == 'waiting' and children[queue['dependency']].poll() is not None: + if children[queue['dependency']].returncode != 0 or not all(Path(p).exists() for p in queue['required_checkpoints']): + queue['status'] = 'blocked_by_incomplete_dependency' + else: + receipt['jobs'][name] = launch(name, queue['command']) + queue.update(status='running', pid=children[name].pid, + started_utc=datetime.datetime.now(datetime.timezone.utc).isoformat()) + with (R / 'direct_v1/EXPERIMENTS.md').open('a') as f: + f.write(f'\n{name} started {queue["started_utc"]} after {queue["dependency"]} completed. Original predeclared settings and seed retained.\n') + (R / (name + '_queue.json')).write_text(json.dumps(queue, indent=2)) + persist() + if all(p.poll() is not None for n,p in children.items() if not n.endswith('_watch')) and all(q['status'] != 'waiting' for q in receipt['queues'].values()): + break + time.sleep(5) +persist() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/recovery/schedules.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/recovery/schedules.py new file mode 100644 index 0000000000000000000000000000000000000000..4c8378f374144b802d2cd5a98afd71efc1ba0a4c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/recovery/schedules.py @@ -0,0 +1,13 @@ +"""Explicit training-only learning-rate schedules; default arithmetic unchanged.""" +import math + + +def learning_rate(step, steps, peak, reset_at=-1, anneal_from_step=None, + anneal_from_lr=None, anneal_final_lr=None): + if anneal_from_step is not None: + assert steps > anneal_from_step + assert 0 < anneal_final_lr <= anneal_from_lr + progress=max(0.,min(1.,(step-anneal_from_step)/(steps-anneal_from_step))) + return anneal_final_lr+.5*(anneal_from_lr-anneal_final_lr)*(1+math.cos(math.pi*progress)) + warm_step=step-reset_at if reset_at>=0 and step>reset_at else step + return peak*min(1,warm_step/400)*(.2+.4*(1+math.cos(math.pi*step/steps))) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/recovery/snapshot.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/recovery/snapshot.py new file mode 100644 index 0000000000000000000000000000000000000000..11ce27e43477f9c685cefeaa5f36e53c59634505 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/recovery/snapshot.py @@ -0,0 +1,99 @@ +"""Write a compact authoritative research recovery index without touching training state.""" +import datetime +import json +import os +from pathlib import Path + +R=Path('/workspace/research');p=R/'CURRENT_RESEARCH_STATE.json' +s=json.loads(p.read_text()) +s['snapshot_utc']=datetime.datetime.now(datetime.timezone.utc).isoformat() +receipt=json.loads((R/'recovery3_launch_receipt.json').read_text()) +s['runs']={} +for name,job in receipt['jobs'].items(): + run=R/'runs'/name + log=Path(job['log']) + records=[] + for line in log.read_text().splitlines(): + try: + record=json.loads(line) + if 'step' in record or 'completed_step' in record:records.append(record) + except json.JSONDecodeError:pass + s['runs'][name]={'config':json.loads((run/'config.json').read_text()) if (run/'config.json').exists() else None, + 'last_phase_record':records[-1] if records else None, + 'phase_log':str(log),'supervisor_receipt':str(R/'recovery3_launch_receipt.json'), + 'latest_saved_ema':str(max(run.glob('ema*.pt'))) if list(run.glob('ema*.pt')) else None, + 'complete_recovery_checkpoint':str(run/'recovery.pt') if (run/'recovery.pt').exists() else None, + 'pid_at_snapshot':job['pid'],'returncode':job.get('returncode'), + 'note':'Check actual live process and checkpoint state before resuming; this is only a snapshot.'} +s['queues']={name:{'status':q['status'],'dependency':q['dependency'],'command':q['command'], + 'required_checkpoints':q['required_checkpoints']} + for name,q in receipt['queues'].items()} +s.pop('prepared_not_launched',None) +s['deferred_unqueued']={'E72':'temporal_mixup, prepared and checked but not queued','ideas':'RESEARCH_IDEAS.md, no jobs attached'} +s['completed_since_previous_recovery']={ + 'E67_control12000':{'skill':.37724286394256845,'training_loop_seconds':2794.8358458959847}, + 'E67_paired12000':{'skill':.377427077277383,'training_loop_seconds':2794.867385860998}, + 'E63_expanded146M':'Stopped8501, complete recovery retained; allocation moved to E73; inconclusive data scaling', + 'E61_slowAR':'Complete12000; E76 used6000 correction, final transfer rejected', + 'E65_recent_normalization':'Complete12000; E81 equal ensemble rejected', + 'E58_small_control':'Complete32000', + 'E58_wide146M':'Complete32000; no gain over37Mcontrol; do not resume', + 'E71_patch8':'Complete12000; selected6000 used in E87/E96/E102 ensembles', + 'E69_volatility':'Complete12000; final below matched control; no transfer', + 'E89_patch8_control':'Complete12000; final0.380847096,loop2729.052105s; selected starting E71parent remains stronger', + 'E89_fullpatch4':'Complete12000,main0.381640078; E96 used6000, E103final cached alternative mixed; loop5066.016522s', + 'E93_split_patch':'Complete12000,main0.381711986; selected final is E102 published thirdmember; loop3153.565149s', + 'E92_robust_normalization':'Complete12000,final0.377099312 belowcontrol; rejected;E97started', + 'E90_metric_scale':'Complete12000; final0.377373344 ties/slightly trailsE80; no selection; loop2702.166704s', + 'E84_coarse':'Complete12000; daily gain but weekly regression; not selected', + 'E88_late_patch8_slowAR':'Complete12000; small9k gain lost atfinal; rejected', + 'E80_overflow':'Complete12000; finaltiesoriginal; selected3k compositeE91rejected', + 'E78_multiscaleAR':'Complete12000; no gain over single slowAR', + 'E86_protected_graft':'Complete8000; below own initialization; no publication', + 'E75_postloss':'Stopped3653 deliberately; immutable snapshot retained; E98 separately declared completion active in another output, original stopfile remains', + 'E73_independent_graft':'Stopped8683 after negative8000; replaced by E86; stopfile remains', + 'E95_stratified_corpus':'Complete12000,final0.377983250,earliermixed; E105collision destroyed only1000weights and optimizer recovery;2k..12k preserved; do not resume', + 'E97_weekly_synth':'Complete12000,final0.380439539; E112final weekly correction now published; loop2600.472750s', + 'E105_stratified_volume':'Complete12000,final0.377529200,earlier0.336713522/0.359535697/0.390349158 mixed; corrected continuationloop2013.982814s plus original incident phase', + 'E106_spectral_synth':'Complete12000,final0.377641399,earlier0.337647555/0.361626447/0.385497870, average matched gap negligible; loop2206.272278s; E114fixed6000transfers in selection', + 'E98_postloss_completion':'Complete12000,final0.376034254 below3000 andcontrol; rejected,loop1995.386513s', + 'E99_early_cooldown':'Complete36000,final0.363306598 trails original36k0.364859034; rejected,loop1603.635706s', + 'E77_pairedslowAR':'Complete12000;6000 strongest main/earlier comparison'} +s['external_receipts']=[str(R/'postloss_recovery3_receipt.json'),str(R/'random_capacity_512_queue.json'),str(R/'random_capacity_1024_queue.json'),str(R/'multiscale_ar_queue.json'),str(R/'overflow_control_queue.json'),str(R/'coarse_aggregate_queue.json'),str(R/'patch8_long_memory_queue.json'),str(R/'wide_graft_frozen_queue.json'),str(R/'patch4_candidate_queue.json'),str(R/'patch4_control_queue.json'),str(R/'metric_scale_queue.json'),str(R/'robust_normalization_queue.json'),str(R/'split_patch_queue.json'),str(R/'random_capacity_1024_halflr_queue.json'),str(R/'stratified_corpus_queue.json'),str(R/'weekly_synth_queue.json'),str(R/'postloss_completion_queue.json'),str(R/'random_capacity_512_anneal_queue.json'),str(R/'distill_ensemble_queue.json'),str(R/'stratified_volume_queue.json'),str(R/'spectral_synth_queue.json'),str(R/'long_seasonal_queue.json'),str(R/'random_capacity_full_queue.json'),str(R/'weekly_replication_control_queue.json'),str(R/'weekly_replication_candidate_queue.json'),str(R/'lowfreq_windows_queue.json'),str(R/'phase_joint_queue.json')] +queue_pids={'random_capacity_512_queue.json':965,'random_capacity_1024_queue.json':967, + 'multiscale_ar_queue.json':1678,'overflow_control_queue.json':1676, + 'coarse_aggregate_queue.json':3086,'patch8_long_memory_queue.json':3739, + 'wide_graft_frozen_queue.json':3931,'patch4_candidate_queue.json':4078, + 'patch4_control_queue.json':4080} +s['external_jobs']={} +for receipt_name in s['external_receipts']: + receipt_path=Path(receipt_name) + if not receipt_path.exists():continue + item=json.loads(receipt_path.read_text());command=item.get('command',[]) + if '--out' not in command:continue + run=Path(command[command.index('--out')+1]);log=Path(item.get('log',str(receipt_path).replace('_queue.json','_train.log'))) + last=None + if log.exists(): + for line in log.read_text().splitlines(): + try: + record=json.loads(line) + if isinstance(record,dict) and ('step' in record or 'completed_step' in record):last=record + except json.JSONDecodeError:pass + queue_pid=item.get('launcher_pid',queue_pids.get(receipt_path.name)) + children_file=Path(f'/proc/{queue_pid}/task/{queue_pid}/children') if queue_pid else None + children=list(map(int,children_file.read_text().split())) if children_file and children_file.exists() else [] + checkpoints=list(run.glob('ema*.pt')) + s['external_jobs'][run.name]={'receipt':str(receipt_path),'status':item.get('status'), + 'queue_pid_at_snapshot':queue_pid,'child_pids_at_snapshot':children, + 'last_phase_record':last,'log':str(log), + 'latest_saved_ema':str(max(checkpoints)) if checkpoints else None, + 'complete_recovery_checkpoint':str(run/'recovery.pt') if (run/'recovery.pt').exists() else None, + 'command':command,'note':'PIDs are only a snapshot; check actual processes and serialized state before recovery.'} +s['compiler_environment']={'OPENBLAS_NUM_THREADS':'1','OMP_NUM_THREADS':'1','TORCHINDUCTOR_COMPILE_THREADS':'2','MAX_JOBS':'2','PYTHONPATH':str(R/'compiler_support'),'TRITON_CACHE_MANAGER':'sibling_cache:SiblingFileCacheManager','TRITON_CACHE_DIR':'/tmp/timeseries-triton-cache','TORCHINDUCTOR_CACHE_DIR':'/tmp/timeseries-inductor-cache'} +for job in s['external_jobs'].values(): + job['environment']=s['compiler_environment'] if '--compile-loss' in job['command'] else {'OPENBLAS_NUM_THREADS':'1','OMP_NUM_THREADS':'1'} +s['compiler_cache_backup']=str(R/'compiler_cache_backup') +for stale in ['pending','pending_actions','active_experiments','next_experiments','prepared_experiments']: + s.pop(stale,None) +tmp=p.with_suffix('.tmp');tmp.write_text(json.dumps(s,indent=2));os.replace(tmp,p) +print(s['snapshot_utc']) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/recovery/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/recovery/train.py new file mode 100644 index 0000000000000000000000000000000000000000..536677ab542342e8e9b56298e5ddb7cb2983a258 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member1/training/recovery/train.py @@ -0,0 +1,201 @@ +"""Resumable continuation of our existing permitted-corpus experiments.""" +import argparse,copy,fcntl,inspect,json,math,os,sys,time +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import numpy as np +import torch + +ap=argparse.ArgumentParser() +ap.add_argument('--code-dir',required=True);ap.add_argument('--packed',required=True) +ap.add_argument('--source-weights-from');ap.add_argument('--out',required=True) +ap.add_argument('--initialize-from',required=True);ap.add_argument('--initialize-ema') +ap.add_argument('--start-step',type=int,default=0);ap.add_argument('--resume') +ap.add_argument('--steps',type=int,required=True);ap.add_argument('--batch',type=int,required=True) +ap.add_argument('--lr',type=float,required=True);ap.add_argument('--seed',type=int,required=True) +ap.add_argument('--context',type=int);ap.add_argument('--sample-context',type=int,default=4096) +ap.add_argument('--save-every',type=int,default=1000);ap.add_argument('--stop-file') +ap.add_argument('--recovery-every',type=int,default=250) +ap.add_argument('--halt-after',type=int) +ap.add_argument('--loss-mode',choices=['individual','paired']) +ap.add_argument('--compile-loss',action='store_true') +ap.add_argument('--reset-at',type=int,default=-1);ap.add_argument('--reset-seed',type=int,default=179) +ap.add_argument('--anneal-from-step',type=int);ap.add_argument('--anneal-from-lr',type=float) +ap.add_argument('--anneal-final-lr',type=float) +ap.add_argument('--teacher-package');ap.add_argument('--teacher-coefficient',type=float) +a=ap.parse_args() +# Hold a process-lifetime lock before loading a model or touching GPU state. +_run_out=Path(a.out);_run_out.mkdir(parents=True,exist_ok=True) +_run_lock=open(_run_out/'.training.lock','a') +try:fcntl.flock(_run_lock,fcntl.LOCK_EX|fcntl.LOCK_NB) +except BlockingIOError:raise SystemExit('Another trainer already owns this output directory: '+str(_run_out)) +if not a.resume: + _saved=list(_run_out.glob('ema*.pt'))+list(_run_out.glob('step*.pt')) + if (_run_out/'recovery.pt').exists():_saved.append(_run_out/'recovery.pt') + if _saved: + raise SystemExit('Refusing fresh training into an output with saved checkpoints; use a new directory or explicit --resume: '+str(_run_out)) +sys.path.insert(0,a.code_dir) +from model import DirectForecaster,loss_fn +from data import Sampler +from schedules import learning_rate +torch.set_num_threads(2);torch.manual_seed(a.seed);torch.backends.cuda.matmul.allow_tf32=True +out=Path(a.out);out.mkdir(parents=True,exist_ok=True);a.trainable_scope='all' +if Path(a.code_dir).name in ('long_memory_synth','paired_long_memory','multiscale_ar','random_capacity','patch8_long_memory','distill_ensemble'):a.synthetic_ar_time_constants=[1,10000] +if Path(a.code_dir).name in ('full_paired','patch8','temporal_mixup','postloss','paired_long_memory','multiscale_ar','random_capacity','overflow_control','coarse_aggregate','patch8_long_memory','patch4','metric_scale','robust_normalization','split_patch','weekly_synth','distill_ensemble'):a.requested_horizon_seed=a.seed+300003 +if Path(a.code_dir).name=='multiscale_ar': + a.synthetic_ar_components=4;a.multiscale_ar_seed=a.seed+700003 +if Path(a.code_dir).name=='volatility_synth':a.stochastic_volatility_seed=a.seed+500003 +if Path(a.code_dir).name=='coarse_aggregate': + a.coarse_aggregation_seed=a.seed+900003;a.coarse_aggregation_probability=.2;a.coarse_aggregation_frequencies=['D','W'] +if Path(a.code_dir).name=='temporal_mixup':a.temporal_mixup_seed=a.seed+600003 +if Path(a.code_dir).name=='postloss': + a.fixed_postprocessing_loss=True;a.normalization_overflow_fallback=True +if Path(a.code_dir).name in ('overflow_control','metric_scale','random_capacity','weekly_synth','distill_ensemble'):a.normalization_overflow_fallback=True +if Path(a.code_dir).name=='weekly_synth': + a.weekly_synthetic_seed=a.seed+1000003;a.weekly_replacement_probability=1/11 +if Path(a.code_dir).name=='spectral_synth': + a.spectral_synthetic_seed=a.seed+1100003;a.spectral_replacement_probability=.5 + a.spectral_length_scale=[1,10000];a.spectral_families=['Matern0.5','Matern1.5','Matern2.5','RBF'] + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True +if Path(a.code_dir).name in ('long_seasonal','phase_joint'): + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True +if Path(a.code_dir).name=='lowfreq_windows': + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True + a.lowfreq_window_seed=a.seed+1200003;a.lowfreq_window_probability=.5 + a.lowfreq_window_rule='period2=1,period1<=52;finite-target endpoint;log-uniform horizon4..min(H,max(8,2p),span-8) with available-length fallback;context cap min(C,max(64,32p));at least4finite history' +if Path(a.code_dir).name=='metric_scale':a.loss_seasonality='lag1 for exact daily[7,365] and weekly[52,1] period pairs; unchanged otherwise' +if Path(a.code_dir).name=='robust_normalization':a.normalization_kind='finite median plus/minus6 mean absolute deviations winsorized mean/RMS, float64; original normalized history clipped30' +if Path(a.code_dir).name=='wide_graft_frozen':a.trainable_scope='new feature stream and cross-stream blocks; inherited parameter blocks frozen' +ck=torch.load(a.resume or a.initialize_from,map_location='cpu',weights_only=False) +# Keep immutable branch ancestry across a later restart from this run's own recovery. +lineage_parents=list(ck.get('parent_checkpoints',[])) +if a.initialize_ema:lineage_parents.append(a.initialize_ema) +if a.resume and Path(a.resume).parent.resolve()!=out.resolve():lineage_parents.append(a.resume) +previous_args=ck.get('args',{}) +previous_resume=previous_args.get('resume') +if previous_resume and Path(previous_resume).parent.resolve()!=Path(previous_args.get('out',a.out)).resolve(): + lineage_parents.append(previous_resume) +lineage_parents=list(dict.fromkeys(lineage_parents)) +config=dict(ck['config']) +if a.context:config['max_context']=a.context +model=DirectForecaster(**config).cuda();model.load_state_dict(ck['model']) +teacher=None +if Path(a.code_dir).name=='distill_ensemble': + assert a.teacher_package and a.teacher_coefficient is not None +if a.teacher_package: + assert Path(a.code_dir).name=='distill_ensemble' + from teacher import OwnEnsembleTeacher + with torch.random.fork_rng(devices=[torch.cuda.current_device()]): + teacher=OwnEnsembleTeacher(a.teacher_package) + if ck.get('args',{}).get('teacher_descriptor_sha256'): + assert ck['args']['teacher_descriptor_sha256']==teacher.descriptor_sha256 + assert ck['args']['teacher_coefficient']==a.teacher_coefficient + a.teacher_descriptor_sha256=teacher.descriptor_sha256 + a.teacher_checkpoint_sha256=teacher.member_hashes + a.teacher_target_kind='equal average of own frozen E96 raw normalized sign-paired neural quantiles, before postprocessing' + +protector=None +if Path(a.code_dir).name=='wide_graft_frozen': + from frozen import FreezeInherited + protector=FreezeInherited(model) + a.protected_parameters=protector.inherited_numel +if a.compile_loss: + torch._dynamo.config.recompile_limit=64 + objective=torch.compile(loss_fn,fullgraph=True,dynamic=False) +else:objective=loss_fn +multipliers=ck.get('lr_multipliers',{}) +def optimizer(): + groups=[] + for mult in sorted(set(multipliers.values())|{1.}): + params=[p for n,p in model.named_parameters() if multipliers.get(n,1.)==mult] + if params:groups.append({'params':params,'lr':a.lr*mult,'lr_multiplier':mult,'weight_decay':.05/mult}) + return torch.optim.AdamW(groups,betas=(.9,.95),fused=True) +opt=optimizer() +if a.resume: + start_step=ck['step'];opt.load_state_dict(ck['optimizer']) + ema={k:v.cuda() for k,v in ck['ema_state'].items()} +else: + start_step=a.start_step + ema_ck=torch.load(a.initialize_ema,map_location='cpu',weights_only=False) if a.initialize_ema else ck + ema={k:v.cuda().clone() for k,v in ema_ck['model'].items()} +del ck +def make_sampler(seed): + kwargs={'seed':seed} + if 'source_weights_from' in inspect.signature(Sampler).parameters:kwargs['source_weights_from']=a.source_weights_from + return Sampler(a.packed,**kwargs),np.random.default_rng(seed) +stream_seed=a.reset_seed if a.reset_at>=0 and start_step>=a.reset_at else a.seed +sampler,rng=make_sampler(stream_seed) +def next_batch(): + c=int(rng.choice([512,1024,2048,a.sample_context],p=[.1,.15,.35,.4])) + h=int(rng.choice([32,128,512,1024],p=[.1,.2,.2,.5])) + x,y,p=sampler.sample(a.batch,c,h) + return x[:,-model.max_context:].copy(),y,p +pool=ThreadPoolExecutor(1) +if a.resume: + recovery=torch.load(a.resume,map_location='cpu',weights_only=False) + rng.bit_generator.state=recovery['batch_rng_state'];sampler.rng.bit_generator.state=recovery['sampler_rng_state'] + for name,state in recovery.get('sampler_rng_states',{}).items():getattr(sampler,name).bit_generator.state=state + torch.set_rng_state(recovery['torch_rng_state']);torch.cuda.set_rng_state_all(recovery['cuda_rng_state']) + pending=recovery['prefetched_batch'];del recovery + future=pool.submit(lambda:pending) +else:future=pool.submit(next_batch) +parameters=sum(p.numel() for p in model.parameters()) +(out/'config.json').write_text(json.dumps({**vars(a),'model':model.config,'parameters':parameters},indent=2)) +print(json.dumps({'parameters':parameters,'starting_step':start_step,'stream_seed':stream_seed,'restored_complete_training_state':bool(a.resume)}),flush=True) +started=time.monotonic();losses=[] +def atomic_save(obj,path): + torch.save(obj,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) +def save(step,include_selection_weights=True): + global future + pending_batch=future.result() + common={'config':model.config,'step':step,'args':vars(a),'lr_multipliers':multipliers, + 'parent_checkpoints':list(dict.fromkeys(lineage_parents+(teacher.checkpoints if teacher else [])))} + if include_selection_weights: + for prefix,state in [('step',model.state_dict()),('ema',ema)]: + atomic_save({**common,'model':state,'ema':prefix=='ema'},out/f'{prefix}{step:06d}.pt') + atomic_save({**common,'model':model.state_dict(),'optimizer':opt.state_dict(),'ema_state':ema, + 'prefetched_batch':pending_batch,'batch_rng_state':copy.deepcopy(rng.bit_generator.state), + 'sampler_rng_state':copy.deepcopy(sampler.rng.bit_generator.state), + 'sampler_rng_states':{name:copy.deepcopy(value.bit_generator.state) for name,value in vars(sampler).items() if isinstance(value,np.random.Generator)}, + 'torch_rng_state':torch.get_rng_state(),'cuda_rng_state':torch.cuda.get_rng_state_all()},out/'recovery.pt') + future=pool.submit(lambda:pending_batch) +for step in range(start_step+1,a.steps+1): + if a.reset_at>=0 and step==a.reset_at+1 and start_step=a.halt_after) + selection_checkpoint=step%a.save_every==0 or step==a.steps or stop + # Persist a complete state before a fresh/resumed job warms its remaining compiled shapes. + if selection_checkpoint or step%a.recovery_every==0 or step==start_step+1: + save(step,include_selection_weights=selection_checkpoint) + if stop:break +pool.shutdown() +print(json.dumps({'completed_step':step,'training_process_loop_seconds':time.monotonic()-started}),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/direct_large/evaluate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/direct_large/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..05f086d4d84def4a48165f9e65d2948877675e56 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/direct_large/evaluate.py @@ -0,0 +1,16 @@ +import sys,json,argparse,time,hashlib +from pathlib import Path +import torch +from predict import load_model,run +sys.path.insert(0,'/workspace/evaluation') +from score import score,json_safe + +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);ap.add_argument('--valid',default='/workspace/research/valid_screen');ap.add_argument('--baseline',default='/workspace/research/valid_screen/baseline.json');a=ap.parse_args() +torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cuda.matmul.allow_tf32=False +t0=time.time();out=Path(a.out);v=Path(a.valid) +run(load_model(a.weights),v/'input',out) +base=json.loads(Path(a.baseline).read_text())['configs'] +rep=score(v/'truth',out,base) +rep['checkpoint_sha256']=hashlib.sha256(Path(a.weights).read_bytes()).hexdigest();rep['eval_seconds']=time.time()-t0 +(out/'report.json').write_text(json.dumps(json_safe(rep),indent=1)) +print(json.dumps({k:rep[k] for k in ('skill_score','rel_mase_gmean','rel_wql_gmean','n_failed','groups','eval_seconds')},indent=1)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/direct_large/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/direct_large/model.py new file mode 100644 index 0000000000000000000000000000000000000000..7a224cc12a159446a1e427b2052b53d1d1f7e83e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/direct_large/model.py @@ -0,0 +1,142 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional(torch.arange(-nt,0,device=z.device),self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + q=self.query(base.reshape(b,h//p,p*9))+positional(torch.arange(h//p,device=z.device),self.d)[None]+emb + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + pin=torch.maximum(levels*err,(levels-1)*err).mean(-1) + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + return per.mean() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/direct_large/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/direct_large/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..e20c6630475d6b4fa6906eb4ed9454b7b5aeec2c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/direct_large/predict.py @@ -0,0 +1,43 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):q=model.predict(x,p,h).float().cpu().numpy() + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/direct_large/record.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/direct_large/record.py new file mode 100644 index 0000000000000000000000000000000000000000..1850a33f46fa3ee4d78cac4a5d6152404801a131 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/direct_large/record.py @@ -0,0 +1,9 @@ +import argparse,json,math +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('report');ap.add_argument('--label',required=True);ap.add_argument('--outcome',default='Screened for model selection.');a=ap.parse_args() +r=json.loads(Path(a.report).read_text());p=Path(__file__).with_name('EXPERIMENTS.md') +lines=[f'\n## {a.label}',f'- Checkpoint SHA-256: `{r.get("checkpoint_sha256","see model_manifest.json")}`.',f'- Evaluation: {r["n_configs"]} configurations, {r["n_instances"]} instances, {r["n_failed"]} failed configurations; {r.get("eval_seconds","not separately timed")} seconds.',f'- Overall skill {r["skill_score"]:.6f}; relative MASE {r["rel_mase_gmean"]:.6f}; relative WQL {r["rel_wql_gmean"]:.6f}.'] +for group,entries in r['groups'].items(): + lines.append(f'- {group} skill: '+', '.join(f'{k}={1-math.sqrt(v["rel_mase_gmean"]*v["rel_wql_gmean"]):.4f}' for k,v in entries.items())+'.') +lines.append('- Outcome: '+a.outcome) +with p.open('a') as f:f.write('\n'.join(lines)+'\n') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/direct_large/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/direct_large/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/direct_large/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/horizon_jitter/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/horizon_jitter/train.py new file mode 100644 index 0000000000000000000000000000000000000000..768d33da4421b24bd760d7d9680d0c2cd9bd84e4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/horizon_jitter/train.py @@ -0,0 +1,74 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler,truncate_targets + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + horizon_rng=np.random.default_rng(a.seed+startstep+300003) + def nextbatch(): + 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])) + return truncate_targets(sampler.sample(a.batch,c,h),horizon_rng,a.patch) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/patch8/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/patch8/model.py new file mode 100644 index 0000000000000000000000000000000000000000..dedcdff4698028a8ba655865f8425d0dc3ef0dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/patch8/model.py @@ -0,0 +1,204 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/recovery/capacity_curves.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/recovery/capacity_curves.py new file mode 100644 index 0000000000000000000000000000000000000000..c89a28a84243dc16ae52a1215c182a00f15dbc4e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/recovery/capacity_curves.py @@ -0,0 +1,50 @@ +"""Summarize completed validation checkpoints and measured shared-GPU training time.""" +import csv +import json +import time +from pathlib import Path + +R = Path('/workspace/research') +started = time.monotonic() +names = ['random_capacity_512', 'random_capacity_1024', 'random_capacity_1024_halflr', + 'random_capacity_full', 'distill_ensemble', 'random_capacity_512_anneal'] +rows = [] +for name in names: + log = R/(name+'_train.log') + records = {} + if log.exists(): + for line in log.read_text().splitlines(): + try: + item = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(item,dict) and 'step' in item and 'seconds' in item: + records[item['step']] = item + config_path = R/'runs'/name/'config.json' + config = json.loads(config_path.read_text()) if config_path.exists() else {} + for report in sorted((R/'evals').glob(name+'_ema*/report.json')): + result = json.loads(report.read_text()) + step = int(report.parent.name.rsplit('ema',1)[1]) + if result['n_failed']: + continue + record = records.get(step,{}) + rows.append(dict(run=name,step=step,parameters=config.get('parameters'), + seed=config.get('seed'),batch=config.get('batch'),learning_rate=config.get('lr'), + packed=config.get('packed'),skill=result['skill_score'], + rel_mase=result['rel_mase_gmean'],rel_wql=result['rel_wql_gmean'], + checkpoint_sha256=result['checkpoint_sha256'], + training_phase_loop_seconds=record.get('seconds'), + evaluation_seconds=result.get('eval_seconds'),report=str(report))) +rows.sort(key=lambda item:(names.index(item['run']),item['step'])) +output = dict(generated_utc=time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()), + note='Validation selection only. Time is logged process wall on the shared single H100, not isolated GPU time. The cooldown arm starts from the same saved24000state; its phase clock resets. No missing log time is inferred.', + rows=rows,analysis_seconds=time.monotonic()-started,no_training_or_new_inference=True) +(R/'capacity_learning_curves.json').write_text(json.dumps(output,indent=2)) +with (R/'capacity_learning_curves.csv').open('w',newline='') as handle: + writer = csv.DictWriter(handle,fieldnames=list(rows[0]) if rows else ['run']) + writer.writeheader() + writer.writerows(rows) +for name in names: + selected = [r for r in rows if r['run']==name] + if selected: + print(json.dumps(selected[-1])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/recovery/relaunch_20261022b.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/recovery/relaunch_20261022b.py new file mode 100644 index 0000000000000000000000000000000000000000..d16fc19cbbb86dba2ff53b445e368b8bbd2ca218 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/recovery/relaunch_20261022b.py @@ -0,0 +1,105 @@ +"""Resume interrupted research jobs and preserve phase-specific recovery receipts.""" +import datetime +import json +import os +from pathlib import Path +import shutil +import subprocess +import time + +R = Path('/workspace/research') +TAG = 'recovery2' +env = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1') +receipt = {'recovery_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(), + 'remaining_research_seconds_at_operator_recovery': 152594, + 'jobs': {}, 'queues': {}} +children = {} + +def launch(name, command, phase=TAG): + log = R / f'{name}_{phase}.log' + assert not log.exists(), log + with log.open('w') as f: + child = subprocess.Popen(command, stdout=f, stderr=subprocess.STDOUT, env=env) + children[name] = child + return {'pid': child.pid, 'command': command, 'log': str(log), 'started_monotonic': time.monotonic()} + +def persist(): + path = R / f'{TAG}_launch_receipt.json' + tmp = path.with_suffix('.tmp') + tmp.write_text(json.dumps(receipt, indent=2)); os.replace(tmp, path) + +for name in ['wide_capacity_146m_recovery', 'wide_capacity_control_recovery', + 'long_memory_synth_recovery', 'recent_normalization_recovery', 'wide_graft', 'patch8']: + run = R / 'runs' / name + cfg = json.loads((run / 'config.json').read_text()) + shutil.copy2(run / 'config.json', run / f'config_before_{TAG}.json') + command = ['python3', str(R / 'recovery/train.py')] + for key in ['code_dir', 'packed', 'source_weights_from', 'out', 'initialize_from', + 'initialize_ema', 'start_step', 'steps', 'batch', 'lr', 'seed', 'context', + 'sample_context', 'save_every', 'stop_file', 'reset_at', 'reset_seed', 'loss_mode']: + if cfg.get(key) is not None: + command += ['--' + key.replace('_', '-'), str(cfg[key])] + if (run / 'recovery.pt').exists(): + command += ['--resume', str(run / 'recovery.pt')] + mode = 'complete optimizer/EMA/RNG/prefetched-batch resume' + else: + mode = 'restart saved own initialization; no complete checkpoint existed' + if cfg.get('compile_loss'): + command += ['--compile-loss'] + command = ['env', 'TORCHINDUCTOR_COMPILE_THREADS=2', 'MAX_JOBS=2', + 'PYTHONPATH=/workspace/research/compiler_support', + 'TRITON_CACHE_MANAGER=sibling_cache:SiblingFileCacheManager', + 'TRITON_CACHE_DIR=/tmp/timeseries-triton-cache', + 'TORCHINDUCTOR_CACHE_DIR=/tmp/timeseries-inductor-cache'] + command + assert not Path(cfg['stop_file']).exists(), cfg['stop_file'] + receipt['jobs'][name] = dict(launch(name, command), mode=mode) + persist() + +watch_specs = { + 'wide_capacity_146m_recovery': ('wide_capacity_inference', '24000,32000'), + 'wide_capacity_control_recovery': ('wide_capacity_inference', '24000,32000'), + 'long_memory_synth_recovery': ('partial_targets_inference', '12000'), + 'recent_normalization_recovery': ('recent_normalization_inference', '12000'), + 'wide_graft': ('wide_graft_inference', '4000,8000,12000,16000,24000,32000'), + 'patch8': ('full_paired_inference', '1000,3000,6000,12000'), + 'volatility_synth': ('partial_targets_inference', '3000,6000,12000'), + 'postloss': ('full_paired_inference', '1000,3000,6000,12000'), + 'paired_long_memory': ('full_paired_inference', '1000,3000,6000,12000'), +} +for name, (runtime, steps) in watch_specs.items(): + command = ['python3', str(R / 'watch_evaluate.py'), '--run', str(R / 'runs' / name), + '--evaluator', str(R / runtime / 'evaluate.py'), '--name', name, '--steps', steps] + launch(name + '_watch', command) + +queue_specs = {'volatility_synth': 'long_memory_synth_recovery', + 'postloss': 'recent_normalization_recovery', + 'paired_long_memory': 'wide_capacity_control_recovery'} +for name, dependency in queue_specs.items(): + old = json.loads((R / (name + '_queue.json')).read_text()) + shutil.copy2(R / (name + '_queue.json'), R / (name + '_queue_before_' + TAG + '.json')) + receipt['queues'][name] = dict(old, dependency=dependency, status='waiting', + wait_pids=[children[dependency].pid]) +persist() + +while True: + for name, job in receipt['jobs'].items(): + if 'returncode' not in job and children[name].poll() is not None: + job.update(returncode=children[name].returncode, + phase_seconds=time.monotonic() - job['started_monotonic']) + persist() + for name, queue in receipt['queues'].items(): + if queue['status'] == 'waiting' and children[queue['dependency']].poll() is not None: + if children[queue['dependency']].returncode != 0 or not all(Path(p).exists() for p in queue['required_checkpoints']): + queue['status'] = 'blocked_by_incomplete_dependency' + else: + receipt['jobs'][name] = launch(name, queue['command']) + queue.update(status='running', pid=children[name].pid, + started_utc=datetime.datetime.now(datetime.timezone.utc).isoformat()) + with (R / 'direct_v1/EXPERIMENTS.md').open('a') as f: + f.write(f'\n{name} started {queue["started_utc"]} after {queue["dependency"]} completed. Original predeclared settings and seed retained.\n') + (R / (name + '_queue.json')).write_text(json.dumps(queue, indent=2)) + persist() + if all(p.poll() is not None for n,p in children.items() if not n.endswith('_watch')) and all(q['status'] != 'waiting' for q in receipt['queues'].values()): + break + time.sleep(5) +persist() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/recovery/relaunch_20261023.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/recovery/relaunch_20261023.py new file mode 100644 index 0000000000000000000000000000000000000000..5f35a9cfcbe7ea66c8837b6d4ada8b84be36b934 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/recovery/relaunch_20261023.py @@ -0,0 +1,104 @@ +"""Resume interrupted research jobs and preserve phase-specific recovery receipts.""" +import datetime +import json +import os +from pathlib import Path +import shutil +import subprocess +import time + +R = Path('/workspace/research') +TAG = 'recovery3' +env = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1') +receipt = {'recovery_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(), + 'remaining_research_seconds_at_operator_recovery': 151596, + 'jobs': {}, 'queues': {}} +children = {} + +def launch(name, command, phase=TAG): + log = R / f'{name}_{phase}.log' + assert not log.exists(), log + with log.open('w') as f: + child = subprocess.Popen(command, stdout=f, stderr=subprocess.STDOUT, env=env) + children[name] = child + return {'pid': child.pid, 'command': command, 'log': str(log), 'started_monotonic': time.monotonic()} + +def persist(): + path = R / f'{TAG}_launch_receipt.json' + tmp = path.with_suffix('.tmp') + tmp.write_text(json.dumps(receipt, indent=2)); os.replace(tmp, path) + +for name in ['wide_capacity_146m_recovery', 'wide_capacity_control_recovery', + 'long_memory_synth_recovery', 'wide_graft', 'patch8']: + run = R / 'runs' / name + cfg = json.loads((run / 'config.json').read_text()) + shutil.copy2(run / 'config.json', run / f'config_before_{TAG}.json') + command = ['python3', str(R / 'recovery/train.py')] + for key in ['code_dir', 'packed', 'source_weights_from', 'out', 'initialize_from', + 'initialize_ema', 'start_step', 'steps', 'batch', 'lr', 'seed', 'context', + 'sample_context', 'save_every', 'stop_file', 'reset_at', 'reset_seed', 'loss_mode']: + if cfg.get(key) is not None: + command += ['--' + key.replace('_', '-'), str(cfg[key])] + if (run / 'recovery.pt').exists(): + command += ['--resume', str(run / 'recovery.pt')] + mode = 'complete optimizer/EMA/RNG/prefetched-batch resume' + else: + mode = 'restart saved own initialization; no complete checkpoint existed' + if cfg.get('compile_loss'): + command += ['--compile-loss'] + command = ['env', 'TORCHINDUCTOR_COMPILE_THREADS=2', 'MAX_JOBS=2', + 'PYTHONPATH=/workspace/research/compiler_support', + 'TRITON_CACHE_MANAGER=sibling_cache:SiblingFileCacheManager', + 'TRITON_CACHE_DIR=/tmp/timeseries-triton-cache', + 'TORCHINDUCTOR_CACHE_DIR=/tmp/timeseries-inductor-cache'] + command + assert not Path(cfg['stop_file']).exists(), cfg['stop_file'] + receipt['jobs'][name] = dict(launch(name, command), mode=mode) + persist() + +watch_specs = { + 'wide_capacity_146m_recovery': ('wide_capacity_inference', '24000,32000'), + 'wide_capacity_control_recovery': ('wide_capacity_inference', '24000,32000'), + 'long_memory_synth_recovery': ('partial_targets_inference', '12000'), + 'recent_normalization_recovery': ('recent_normalization_inference', '12000'), + 'wide_graft': ('wide_graft_inference', '4000,8000,12000,16000,24000,32000'), + 'patch8': ('full_paired_inference', '1000,3000,6000,12000'), + 'volatility_synth': ('partial_targets_inference', '3000,6000,12000'), + 'postloss': ('full_paired_inference', '1000,3000,6000,12000'), + 'paired_long_memory': ('full_paired_inference', '1000,3000,6000,12000'), +} +for name, (runtime, steps) in watch_specs.items(): + command = ['python3', str(R / 'watch_evaluate.py'), '--run', str(R / 'runs' / name), + '--evaluator', str(R / runtime / 'evaluate.py'), '--name', name, '--steps', steps] + launch(name + '_watch', command) + +queue_specs = {'volatility_synth': 'long_memory_synth_recovery', + 'paired_long_memory': 'wide_capacity_control_recovery'} +for name, dependency in queue_specs.items(): + old = json.loads((R / (name + '_queue.json')).read_text()) + shutil.copy2(R / (name + '_queue.json'), R / (name + '_queue_before_' + TAG + '.json')) + receipt['queues'][name] = dict(old, dependency=dependency, status='waiting', + wait_pids=[children[dependency].pid]) +persist() + +while True: + for name, job in receipt['jobs'].items(): + if 'returncode' not in job and children[name].poll() is not None: + job.update(returncode=children[name].returncode, + phase_seconds=time.monotonic() - job['started_monotonic']) + persist() + for name, queue in receipt['queues'].items(): + if queue['status'] == 'waiting' and children[queue['dependency']].poll() is not None: + if children[queue['dependency']].returncode != 0 or not all(Path(p).exists() for p in queue['required_checkpoints']): + queue['status'] = 'blocked_by_incomplete_dependency' + else: + receipt['jobs'][name] = launch(name, queue['command']) + queue.update(status='running', pid=children[name].pid, + started_utc=datetime.datetime.now(datetime.timezone.utc).isoformat()) + with (R / 'direct_v1/EXPERIMENTS.md').open('a') as f: + f.write(f'\n{name} started {queue["started_utc"]} after {queue["dependency"]} completed. Original predeclared settings and seed retained.\n') + (R / (name + '_queue.json')).write_text(json.dumps(queue, indent=2)) + persist() + if all(p.poll() is not None for n,p in children.items() if not n.endswith('_watch')) and all(q['status'] != 'waiting' for q in receipt['queues'].values()): + break + time.sleep(5) +persist() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/recovery/schedules.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/recovery/schedules.py new file mode 100644 index 0000000000000000000000000000000000000000..4c8378f374144b802d2cd5a98afd71efc1ba0a4c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/recovery/schedules.py @@ -0,0 +1,13 @@ +"""Explicit training-only learning-rate schedules; default arithmetic unchanged.""" +import math + + +def learning_rate(step, steps, peak, reset_at=-1, anneal_from_step=None, + anneal_from_lr=None, anneal_final_lr=None): + if anneal_from_step is not None: + assert steps > anneal_from_step + assert 0 < anneal_final_lr <= anneal_from_lr + progress=max(0.,min(1.,(step-anneal_from_step)/(steps-anneal_from_step))) + return anneal_final_lr+.5*(anneal_from_lr-anneal_final_lr)*(1+math.cos(math.pi*progress)) + warm_step=step-reset_at if reset_at>=0 and step>reset_at else step + return peak*min(1,warm_step/400)*(.2+.4*(1+math.cos(math.pi*step/steps))) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/recovery/snapshot.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/recovery/snapshot.py new file mode 100644 index 0000000000000000000000000000000000000000..11ce27e43477f9c685cefeaa5f36e53c59634505 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/recovery/snapshot.py @@ -0,0 +1,99 @@ +"""Write a compact authoritative research recovery index without touching training state.""" +import datetime +import json +import os +from pathlib import Path + +R=Path('/workspace/research');p=R/'CURRENT_RESEARCH_STATE.json' +s=json.loads(p.read_text()) +s['snapshot_utc']=datetime.datetime.now(datetime.timezone.utc).isoformat() +receipt=json.loads((R/'recovery3_launch_receipt.json').read_text()) +s['runs']={} +for name,job in receipt['jobs'].items(): + run=R/'runs'/name + log=Path(job['log']) + records=[] + for line in log.read_text().splitlines(): + try: + record=json.loads(line) + if 'step' in record or 'completed_step' in record:records.append(record) + except json.JSONDecodeError:pass + s['runs'][name]={'config':json.loads((run/'config.json').read_text()) if (run/'config.json').exists() else None, + 'last_phase_record':records[-1] if records else None, + 'phase_log':str(log),'supervisor_receipt':str(R/'recovery3_launch_receipt.json'), + 'latest_saved_ema':str(max(run.glob('ema*.pt'))) if list(run.glob('ema*.pt')) else None, + 'complete_recovery_checkpoint':str(run/'recovery.pt') if (run/'recovery.pt').exists() else None, + 'pid_at_snapshot':job['pid'],'returncode':job.get('returncode'), + 'note':'Check actual live process and checkpoint state before resuming; this is only a snapshot.'} +s['queues']={name:{'status':q['status'],'dependency':q['dependency'],'command':q['command'], + 'required_checkpoints':q['required_checkpoints']} + for name,q in receipt['queues'].items()} +s.pop('prepared_not_launched',None) +s['deferred_unqueued']={'E72':'temporal_mixup, prepared and checked but not queued','ideas':'RESEARCH_IDEAS.md, no jobs attached'} +s['completed_since_previous_recovery']={ + 'E67_control12000':{'skill':.37724286394256845,'training_loop_seconds':2794.8358458959847}, + 'E67_paired12000':{'skill':.377427077277383,'training_loop_seconds':2794.867385860998}, + 'E63_expanded146M':'Stopped8501, complete recovery retained; allocation moved to E73; inconclusive data scaling', + 'E61_slowAR':'Complete12000; E76 used6000 correction, final transfer rejected', + 'E65_recent_normalization':'Complete12000; E81 equal ensemble rejected', + 'E58_small_control':'Complete32000', + 'E58_wide146M':'Complete32000; no gain over37Mcontrol; do not resume', + 'E71_patch8':'Complete12000; selected6000 used in E87/E96/E102 ensembles', + 'E69_volatility':'Complete12000; final below matched control; no transfer', + 'E89_patch8_control':'Complete12000; final0.380847096,loop2729.052105s; selected starting E71parent remains stronger', + 'E89_fullpatch4':'Complete12000,main0.381640078; E96 used6000, E103final cached alternative mixed; loop5066.016522s', + 'E93_split_patch':'Complete12000,main0.381711986; selected final is E102 published thirdmember; loop3153.565149s', + 'E92_robust_normalization':'Complete12000,final0.377099312 belowcontrol; rejected;E97started', + 'E90_metric_scale':'Complete12000; final0.377373344 ties/slightly trailsE80; no selection; loop2702.166704s', + 'E84_coarse':'Complete12000; daily gain but weekly regression; not selected', + 'E88_late_patch8_slowAR':'Complete12000; small9k gain lost atfinal; rejected', + 'E80_overflow':'Complete12000; finaltiesoriginal; selected3k compositeE91rejected', + 'E78_multiscaleAR':'Complete12000; no gain over single slowAR', + 'E86_protected_graft':'Complete8000; below own initialization; no publication', + 'E75_postloss':'Stopped3653 deliberately; immutable snapshot retained; E98 separately declared completion active in another output, original stopfile remains', + 'E73_independent_graft':'Stopped8683 after negative8000; replaced by E86; stopfile remains', + 'E95_stratified_corpus':'Complete12000,final0.377983250,earliermixed; E105collision destroyed only1000weights and optimizer recovery;2k..12k preserved; do not resume', + 'E97_weekly_synth':'Complete12000,final0.380439539; E112final weekly correction now published; loop2600.472750s', + 'E105_stratified_volume':'Complete12000,final0.377529200,earlier0.336713522/0.359535697/0.390349158 mixed; corrected continuationloop2013.982814s plus original incident phase', + 'E106_spectral_synth':'Complete12000,final0.377641399,earlier0.337647555/0.361626447/0.385497870, average matched gap negligible; loop2206.272278s; E114fixed6000transfers in selection', + 'E98_postloss_completion':'Complete12000,final0.376034254 below3000 andcontrol; rejected,loop1995.386513s', + 'E99_early_cooldown':'Complete36000,final0.363306598 trails original36k0.364859034; rejected,loop1603.635706s', + 'E77_pairedslowAR':'Complete12000;6000 strongest main/earlier comparison'} +s['external_receipts']=[str(R/'postloss_recovery3_receipt.json'),str(R/'random_capacity_512_queue.json'),str(R/'random_capacity_1024_queue.json'),str(R/'multiscale_ar_queue.json'),str(R/'overflow_control_queue.json'),str(R/'coarse_aggregate_queue.json'),str(R/'patch8_long_memory_queue.json'),str(R/'wide_graft_frozen_queue.json'),str(R/'patch4_candidate_queue.json'),str(R/'patch4_control_queue.json'),str(R/'metric_scale_queue.json'),str(R/'robust_normalization_queue.json'),str(R/'split_patch_queue.json'),str(R/'random_capacity_1024_halflr_queue.json'),str(R/'stratified_corpus_queue.json'),str(R/'weekly_synth_queue.json'),str(R/'postloss_completion_queue.json'),str(R/'random_capacity_512_anneal_queue.json'),str(R/'distill_ensemble_queue.json'),str(R/'stratified_volume_queue.json'),str(R/'spectral_synth_queue.json'),str(R/'long_seasonal_queue.json'),str(R/'random_capacity_full_queue.json'),str(R/'weekly_replication_control_queue.json'),str(R/'weekly_replication_candidate_queue.json'),str(R/'lowfreq_windows_queue.json'),str(R/'phase_joint_queue.json')] +queue_pids={'random_capacity_512_queue.json':965,'random_capacity_1024_queue.json':967, + 'multiscale_ar_queue.json':1678,'overflow_control_queue.json':1676, + 'coarse_aggregate_queue.json':3086,'patch8_long_memory_queue.json':3739, + 'wide_graft_frozen_queue.json':3931,'patch4_candidate_queue.json':4078, + 'patch4_control_queue.json':4080} +s['external_jobs']={} +for receipt_name in s['external_receipts']: + receipt_path=Path(receipt_name) + if not receipt_path.exists():continue + item=json.loads(receipt_path.read_text());command=item.get('command',[]) + if '--out' not in command:continue + run=Path(command[command.index('--out')+1]);log=Path(item.get('log',str(receipt_path).replace('_queue.json','_train.log'))) + last=None + if log.exists(): + for line in log.read_text().splitlines(): + try: + record=json.loads(line) + if isinstance(record,dict) and ('step' in record or 'completed_step' in record):last=record + except json.JSONDecodeError:pass + queue_pid=item.get('launcher_pid',queue_pids.get(receipt_path.name)) + children_file=Path(f'/proc/{queue_pid}/task/{queue_pid}/children') if queue_pid else None + children=list(map(int,children_file.read_text().split())) if children_file and children_file.exists() else [] + checkpoints=list(run.glob('ema*.pt')) + s['external_jobs'][run.name]={'receipt':str(receipt_path),'status':item.get('status'), + 'queue_pid_at_snapshot':queue_pid,'child_pids_at_snapshot':children, + 'last_phase_record':last,'log':str(log), + 'latest_saved_ema':str(max(checkpoints)) if checkpoints else None, + 'complete_recovery_checkpoint':str(run/'recovery.pt') if (run/'recovery.pt').exists() else None, + 'command':command,'note':'PIDs are only a snapshot; check actual processes and serialized state before recovery.'} +s['compiler_environment']={'OPENBLAS_NUM_THREADS':'1','OMP_NUM_THREADS':'1','TORCHINDUCTOR_COMPILE_THREADS':'2','MAX_JOBS':'2','PYTHONPATH':str(R/'compiler_support'),'TRITON_CACHE_MANAGER':'sibling_cache:SiblingFileCacheManager','TRITON_CACHE_DIR':'/tmp/timeseries-triton-cache','TORCHINDUCTOR_CACHE_DIR':'/tmp/timeseries-inductor-cache'} +for job in s['external_jobs'].values(): + job['environment']=s['compiler_environment'] if '--compile-loss' in job['command'] else {'OPENBLAS_NUM_THREADS':'1','OMP_NUM_THREADS':'1'} +s['compiler_cache_backup']=str(R/'compiler_cache_backup') +for stale in ['pending','pending_actions','active_experiments','next_experiments','prepared_experiments']: + s.pop(stale,None) +tmp=p.with_suffix('.tmp');tmp.write_text(json.dumps(s,indent=2));os.replace(tmp,p) +print(s['snapshot_utc']) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/recovery/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/recovery/train.py new file mode 100644 index 0000000000000000000000000000000000000000..536677ab542342e8e9b56298e5ddb7cb2983a258 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S058/provenance/member2/training/recovery/train.py @@ -0,0 +1,201 @@ +"""Resumable continuation of our existing permitted-corpus experiments.""" +import argparse,copy,fcntl,inspect,json,math,os,sys,time +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import numpy as np +import torch + +ap=argparse.ArgumentParser() +ap.add_argument('--code-dir',required=True);ap.add_argument('--packed',required=True) +ap.add_argument('--source-weights-from');ap.add_argument('--out',required=True) +ap.add_argument('--initialize-from',required=True);ap.add_argument('--initialize-ema') +ap.add_argument('--start-step',type=int,default=0);ap.add_argument('--resume') +ap.add_argument('--steps',type=int,required=True);ap.add_argument('--batch',type=int,required=True) +ap.add_argument('--lr',type=float,required=True);ap.add_argument('--seed',type=int,required=True) +ap.add_argument('--context',type=int);ap.add_argument('--sample-context',type=int,default=4096) +ap.add_argument('--save-every',type=int,default=1000);ap.add_argument('--stop-file') +ap.add_argument('--recovery-every',type=int,default=250) +ap.add_argument('--halt-after',type=int) +ap.add_argument('--loss-mode',choices=['individual','paired']) +ap.add_argument('--compile-loss',action='store_true') +ap.add_argument('--reset-at',type=int,default=-1);ap.add_argument('--reset-seed',type=int,default=179) +ap.add_argument('--anneal-from-step',type=int);ap.add_argument('--anneal-from-lr',type=float) +ap.add_argument('--anneal-final-lr',type=float) +ap.add_argument('--teacher-package');ap.add_argument('--teacher-coefficient',type=float) +a=ap.parse_args() +# Hold a process-lifetime lock before loading a model or touching GPU state. +_run_out=Path(a.out);_run_out.mkdir(parents=True,exist_ok=True) +_run_lock=open(_run_out/'.training.lock','a') +try:fcntl.flock(_run_lock,fcntl.LOCK_EX|fcntl.LOCK_NB) +except BlockingIOError:raise SystemExit('Another trainer already owns this output directory: '+str(_run_out)) +if not a.resume: + _saved=list(_run_out.glob('ema*.pt'))+list(_run_out.glob('step*.pt')) + if (_run_out/'recovery.pt').exists():_saved.append(_run_out/'recovery.pt') + if _saved: + raise SystemExit('Refusing fresh training into an output with saved checkpoints; use a new directory or explicit --resume: '+str(_run_out)) +sys.path.insert(0,a.code_dir) +from model import DirectForecaster,loss_fn +from data import Sampler +from schedules import learning_rate +torch.set_num_threads(2);torch.manual_seed(a.seed);torch.backends.cuda.matmul.allow_tf32=True +out=Path(a.out);out.mkdir(parents=True,exist_ok=True);a.trainable_scope='all' +if Path(a.code_dir).name in ('long_memory_synth','paired_long_memory','multiscale_ar','random_capacity','patch8_long_memory','distill_ensemble'):a.synthetic_ar_time_constants=[1,10000] +if Path(a.code_dir).name in ('full_paired','patch8','temporal_mixup','postloss','paired_long_memory','multiscale_ar','random_capacity','overflow_control','coarse_aggregate','patch8_long_memory','patch4','metric_scale','robust_normalization','split_patch','weekly_synth','distill_ensemble'):a.requested_horizon_seed=a.seed+300003 +if Path(a.code_dir).name=='multiscale_ar': + a.synthetic_ar_components=4;a.multiscale_ar_seed=a.seed+700003 +if Path(a.code_dir).name=='volatility_synth':a.stochastic_volatility_seed=a.seed+500003 +if Path(a.code_dir).name=='coarse_aggregate': + a.coarse_aggregation_seed=a.seed+900003;a.coarse_aggregation_probability=.2;a.coarse_aggregation_frequencies=['D','W'] +if Path(a.code_dir).name=='temporal_mixup':a.temporal_mixup_seed=a.seed+600003 +if Path(a.code_dir).name=='postloss': + a.fixed_postprocessing_loss=True;a.normalization_overflow_fallback=True +if Path(a.code_dir).name in ('overflow_control','metric_scale','random_capacity','weekly_synth','distill_ensemble'):a.normalization_overflow_fallback=True +if Path(a.code_dir).name=='weekly_synth': + a.weekly_synthetic_seed=a.seed+1000003;a.weekly_replacement_probability=1/11 +if Path(a.code_dir).name=='spectral_synth': + a.spectral_synthetic_seed=a.seed+1100003;a.spectral_replacement_probability=.5 + a.spectral_length_scale=[1,10000];a.spectral_families=['Matern0.5','Matern1.5','Matern2.5','RBF'] + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True +if Path(a.code_dir).name in ('long_seasonal','phase_joint'): + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True +if Path(a.code_dir).name=='lowfreq_windows': + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True + a.lowfreq_window_seed=a.seed+1200003;a.lowfreq_window_probability=.5 + a.lowfreq_window_rule='period2=1,period1<=52;finite-target endpoint;log-uniform horizon4..min(H,max(8,2p),span-8) with available-length fallback;context cap min(C,max(64,32p));at least4finite history' +if Path(a.code_dir).name=='metric_scale':a.loss_seasonality='lag1 for exact daily[7,365] and weekly[52,1] period pairs; unchanged otherwise' +if Path(a.code_dir).name=='robust_normalization':a.normalization_kind='finite median plus/minus6 mean absolute deviations winsorized mean/RMS, float64; original normalized history clipped30' +if Path(a.code_dir).name=='wide_graft_frozen':a.trainable_scope='new feature stream and cross-stream blocks; inherited parameter blocks frozen' +ck=torch.load(a.resume or a.initialize_from,map_location='cpu',weights_only=False) +# Keep immutable branch ancestry across a later restart from this run's own recovery. +lineage_parents=list(ck.get('parent_checkpoints',[])) +if a.initialize_ema:lineage_parents.append(a.initialize_ema) +if a.resume and Path(a.resume).parent.resolve()!=out.resolve():lineage_parents.append(a.resume) +previous_args=ck.get('args',{}) +previous_resume=previous_args.get('resume') +if previous_resume and Path(previous_resume).parent.resolve()!=Path(previous_args.get('out',a.out)).resolve(): + lineage_parents.append(previous_resume) +lineage_parents=list(dict.fromkeys(lineage_parents)) +config=dict(ck['config']) +if a.context:config['max_context']=a.context +model=DirectForecaster(**config).cuda();model.load_state_dict(ck['model']) +teacher=None +if Path(a.code_dir).name=='distill_ensemble': + assert a.teacher_package and a.teacher_coefficient is not None +if a.teacher_package: + assert Path(a.code_dir).name=='distill_ensemble' + from teacher import OwnEnsembleTeacher + with torch.random.fork_rng(devices=[torch.cuda.current_device()]): + teacher=OwnEnsembleTeacher(a.teacher_package) + if ck.get('args',{}).get('teacher_descriptor_sha256'): + assert ck['args']['teacher_descriptor_sha256']==teacher.descriptor_sha256 + assert ck['args']['teacher_coefficient']==a.teacher_coefficient + a.teacher_descriptor_sha256=teacher.descriptor_sha256 + a.teacher_checkpoint_sha256=teacher.member_hashes + a.teacher_target_kind='equal average of own frozen E96 raw normalized sign-paired neural quantiles, before postprocessing' + +protector=None +if Path(a.code_dir).name=='wide_graft_frozen': + from frozen import FreezeInherited + protector=FreezeInherited(model) + a.protected_parameters=protector.inherited_numel +if a.compile_loss: + torch._dynamo.config.recompile_limit=64 + objective=torch.compile(loss_fn,fullgraph=True,dynamic=False) +else:objective=loss_fn +multipliers=ck.get('lr_multipliers',{}) +def optimizer(): + groups=[] + for mult in sorted(set(multipliers.values())|{1.}): + params=[p for n,p in model.named_parameters() if multipliers.get(n,1.)==mult] + if params:groups.append({'params':params,'lr':a.lr*mult,'lr_multiplier':mult,'weight_decay':.05/mult}) + return torch.optim.AdamW(groups,betas=(.9,.95),fused=True) +opt=optimizer() +if a.resume: + start_step=ck['step'];opt.load_state_dict(ck['optimizer']) + ema={k:v.cuda() for k,v in ck['ema_state'].items()} +else: + start_step=a.start_step + ema_ck=torch.load(a.initialize_ema,map_location='cpu',weights_only=False) if a.initialize_ema else ck + ema={k:v.cuda().clone() for k,v in ema_ck['model'].items()} +del ck +def make_sampler(seed): + kwargs={'seed':seed} + if 'source_weights_from' in inspect.signature(Sampler).parameters:kwargs['source_weights_from']=a.source_weights_from + return Sampler(a.packed,**kwargs),np.random.default_rng(seed) +stream_seed=a.reset_seed if a.reset_at>=0 and start_step>=a.reset_at else a.seed +sampler,rng=make_sampler(stream_seed) +def next_batch(): + c=int(rng.choice([512,1024,2048,a.sample_context],p=[.1,.15,.35,.4])) + h=int(rng.choice([32,128,512,1024],p=[.1,.2,.2,.5])) + x,y,p=sampler.sample(a.batch,c,h) + return x[:,-model.max_context:].copy(),y,p +pool=ThreadPoolExecutor(1) +if a.resume: + recovery=torch.load(a.resume,map_location='cpu',weights_only=False) + rng.bit_generator.state=recovery['batch_rng_state'];sampler.rng.bit_generator.state=recovery['sampler_rng_state'] + for name,state in recovery.get('sampler_rng_states',{}).items():getattr(sampler,name).bit_generator.state=state + torch.set_rng_state(recovery['torch_rng_state']);torch.cuda.set_rng_state_all(recovery['cuda_rng_state']) + pending=recovery['prefetched_batch'];del recovery + future=pool.submit(lambda:pending) +else:future=pool.submit(next_batch) +parameters=sum(p.numel() for p in model.parameters()) +(out/'config.json').write_text(json.dumps({**vars(a),'model':model.config,'parameters':parameters},indent=2)) +print(json.dumps({'parameters':parameters,'starting_step':start_step,'stream_seed':stream_seed,'restored_complete_training_state':bool(a.resume)}),flush=True) +started=time.monotonic();losses=[] +def atomic_save(obj,path): + torch.save(obj,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) +def save(step,include_selection_weights=True): + global future + pending_batch=future.result() + common={'config':model.config,'step':step,'args':vars(a),'lr_multipliers':multipliers, + 'parent_checkpoints':list(dict.fromkeys(lineage_parents+(teacher.checkpoints if teacher else [])))} + if include_selection_weights: + for prefix,state in [('step',model.state_dict()),('ema',ema)]: + atomic_save({**common,'model':state,'ema':prefix=='ema'},out/f'{prefix}{step:06d}.pt') + atomic_save({**common,'model':model.state_dict(),'optimizer':opt.state_dict(),'ema_state':ema, + 'prefetched_batch':pending_batch,'batch_rng_state':copy.deepcopy(rng.bit_generator.state), + 'sampler_rng_state':copy.deepcopy(sampler.rng.bit_generator.state), + 'sampler_rng_states':{name:copy.deepcopy(value.bit_generator.state) for name,value in vars(sampler).items() if isinstance(value,np.random.Generator)}, + 'torch_rng_state':torch.get_rng_state(),'cuda_rng_state':torch.cuda.get_rng_state_all()},out/'recovery.pt') + future=pool.submit(lambda:pending_batch) +for step in range(start_step+1,a.steps+1): + if a.reset_at>=0 and step==a.reset_at+1 and start_step=a.halt_after) + selection_checkpoint=step%a.save_every==0 or step==a.steps or stop + # Persist a complete state before a fresh/resumed job warms its remaining compiled shapes. + if selection_checkpoint or step%a.recovery_every==0 or step==start_step+1: + save(step,include_selection_weights=selection_checkpoint) + if stop:break +pool.shutdown() +print(json.dumps({'completed_step':step,'training_process_loop_seconds':time.monotonic()-started}),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/README.md b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/README.md new file mode 100644 index 0000000000000000000000000000000000000000..56de74cfd2a57068d183d508989729d35ed91683 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/README.md @@ -0,0 +1,9 @@ +# Three-member seasonal foundation forecaster + +Run `bash infer.sh INPUT_DIR OUTPUT_DIR`. All runtime assets are included, with versions pinned in requirements.txt. The package contains three locally trained models totaling 110,117,400 parameters. Every member forecasts every instance; their nine ordered quantiles are averaged with fixed equal weights of 1/3 each. + +Each member retains its declared context limits, listed in model_manifest.json under member_history_caps. A model with a separate encoder_context uses longer history only for learned seasonal summaries; its encoder, normalization and fixed forecast rules use the shorter declared limit. Their history/forecast patch sizes are 16/16, 8/8, 8/4, in member order. Each member retains its own original model implementation and normalization; the first has a float64 fallback for nonfinite float32 context statistics. Each member uses finite-history normalization and the same fixed sign averaging, positivity, seasonal, continuity and zero-mass rules. The seasonal template aligns four cycles to the latest cycle's mean and amplitude. The trend summary uses a fixed width of 128 observations. The zero projection threshold is 0.4 context standard deviations. No additional zero projection is applied after averaging. There is no inference-time training, fitting or parameter adaptation. + +model_manifest.json declares every source, member hash and training lineage. config.json contains relative member paths and their hashes. The original member manifests and all trainer/generator code are archived in provenance/. No pretrained assets were used. Normalization uses the supplied context and needs no external statistics. + +EXPERIMENTS.md records hypotheses, negative results, compute, group metrics and hashes. validation_report.json records the package evaluation. Validation and earlier-cutoff scores are not the held-out reward scale. diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/config.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/config.json new file mode 100644 index 0000000000000000000000000000000000000000..0816e88abdd209b6d0b86fb62cbe1380ef988f44 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/config.json @@ -0,0 +1,66 @@ +{ + "members": [ + { + "weights": "member0.pt", + "weights_sha256": "8a2b252b733cc79c31778ea27ba00fbe61206fef50454514b667c54a928d80a4", + "parameters": 36849984, + "config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true + }, + "model_code": "model0.py" + }, + { + "weights": "member1.pt", + "weights_sha256": "308389b7217c080af9eb185559d4ee3cafa0f3e0f8c4dd8f5526b68198c89988", + "parameters": 36665488, + "config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "model_code": "model1.py" + }, + { + "weights": "member2.pt", + "weights_sha256": "1a2fb20a9fb5cae6526f2e36ea47559626bece78fd9c284899836505030ae9fe", + "parameters": 36601928, + "config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 4, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "input_patch": 8 + }, + "model_code": "model2.py" + } + ], + "weights": [ + 0.3333333333333333, + 0.3333333333333333, + 0.3333333333333333 + ], + "composition": "mean after each member applies its fixed inference rules" +} diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/continuity.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/continuity.py new file mode 100644 index 0000000000000000000000000000000000000000..bebb06b9c20f322b9d5564650889e2236ae94494 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/continuity.py @@ -0,0 +1,18 @@ +"""Fixed continuity prior for histories whose adjacent samples change slowly.""" +import numpy as np + +def apply_continuity(ctx,quant,tau=24.): + b,_,h=quant.shape + bias=np.zeros(b,np.float32) + positive=((ctx>=0)|~np.isfinite(ctx)).all(-1) + for i in range(b): + x=ctx[i,-512:].astype(np.float64) + if len(x)<8 or not np.isfinite(x[-1]):continue + diff=np.diff(x) + if np.isfinite(diff).sum()<8 or not np.isfinite(diff[-8:]).any():continue + ratio=np.nanmean(diff*diff)/(np.nanvar(x)+1e-12) + weight=float(np.clip(1-ratio/.5,0,.95)) + bias[i]=weight*(x[-1]+np.nanmedian(diff[-8:])-quant[i,4,0]) + out=quant+bias[:,None,None]*np.exp(-np.arange(h)/tau)[None,None,:] + out=np.where(positive[:,None,None],np.maximum(0,out),out) + return out.astype(np.float32) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/infer.sh b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/infer.sh new file mode 100644 index 0000000000000000000000000000000000000000..cd8b850fa281f16a1fdf4147cb8e3ce1412f2702 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/infer.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -euo pipefail +export OMP_NUM_THREADS=4 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=4 +exec python3 "$(dirname "$(readlink -f "$0")")/predict.py" "$1" "$2" diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/model.py new file mode 100644 index 0000000000000000000000000000000000000000..dedcdff4698028a8ba655865f8425d0dc3ef0dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/model.py @@ -0,0 +1,204 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/model0.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/model0.py new file mode 100644 index 0000000000000000000000000000000000000000..298ee3b840cbc8b7da585ee5e47a3822d06717b0 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/model0.py @@ -0,0 +1,260 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + + +def centered_seasonal_difference(z, valid, periods, horizon): + b, c = z.shape + time = torch.arange(horizon, device=z.device)[None, :] + sums = F.pad((z * valid).cumsum(-1), (1, 0)) + counts = F.pad(valid.float().cumsum(-1), (1, 0)) + deltas, extras = [], [] + for j in range(2): + period = periods[:, j:j+1].clamp(min=1) + anchor = c - period + time % period + centered, masks = [], [] + for cycle in range(16): + end = (c - cycle * period).clamp(min=0, max=c) + start = (c - (cycle + 1) * period).clamp(min=0, max=c) + count = counts.gather(1, end) - counts.gather(1, start) + mean = (sums.gather(1, end) - sums.gather(1, start)) / count.clamp(min=1) + index = anchor - cycle * period + safe = index.clamp(min=0, max=c-1) + present = (index >= 0) & valid.gather(1, safe) + centered.append(z.gather(1, safe) - mean) + masks.append(present) + values = torch.stack(centered) + seen = torch.stack(masks) + n4 = seen[:4].sum(0) + n16 = seen.sum(0) + mean4 = (values[:4] * seen[:4]).sum(0) / n4.clamp(min=1) + mean16 = (values * seen).sum(0) / n16.clamp(min=1) + active = (period >= 2) & (n4 >= 2) & (n16 >= 8) + delta = torch.where(active, mean16 - mean4, 0.) + support = torch.where(active, n16.float() / 16, 0.) + deltas.append(delta) + extras.extend([delta, support]) + return torch.stack(deltas, -1), torch.stack(extras, -1) + + + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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,long_seasonal_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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,long_seasonal_features=long_seasonal_features) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + self.long_query=nn.Linear(patch*4,d,bias=False) if long_seasonal_features else None + self.long_head=nn.Linear(d,patch*2) if long_seasonal_features else None + if long_seasonal_features: + nn.init.zeros_(self.long_query.weight) + nn.init.zeros_(self.long_head.weight);nn.init.zeros_(self.long_head.bias) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + if self.long_query is not None:long_delta,long_extra=centered_seasonal_difference(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + hidden=self.norm(q) + out=self.head(hidden).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + if self.long_head is not None: + gates=self.long_head(hidden).view(b,h,2).float().tanh() + median=median+(gates*long_delta).sum(-1) + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/model1.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/model1.py new file mode 100644 index 0000000000000000000000000000000000000000..dedcdff4698028a8ba655865f8425d0dc3ef0dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/model1.py @@ -0,0 +1,204 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/model2.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/model2.py new file mode 100644 index 0000000000000000000000000000000000000000..af1af318784c94a1d9ee75ed377582745bd30136 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/model2.py @@ -0,0 +1,204 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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,input_patch=None): + super().__init__();self.patch=patch;self.input_patch=patch if input_patch is None else input_patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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,input_patch=self.input_patch) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(self.input_patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;ip=self.input_patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%ip,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//ip + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,ip),valid.view(b,nt,ip).float()),-1)) + pmask=valid.view(b,nt,ip).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/model_manifest.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/model_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..68bc9c021c029339a489fc78088b78eaf1c3656f --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/model_manifest.json @@ -0,0 +1,1231 @@ +{ + "name": "direct-seasonal-three-patch-foundation", + "contract": "timeseries-forecast/v1", + "parameters": 110117400, + "pretrained_assets": [], + "sources_used": [ + "gifteval_pretrain/BEIJING_SUBWAY_30MIN", + "gifteval_pretrain/HZMETRO", + "gifteval_pretrain/LOS_LOOP", + "gifteval_pretrain/PEMS03", + "gifteval_pretrain/PEMS04", + "gifteval_pretrain/PEMS07", + "gifteval_pretrain/PEMS08", + "gifteval_pretrain/PEMS_BAY", + "gifteval_pretrain/Q-TRAFFIC", + "gifteval_pretrain/SHMETRO", + "gifteval_pretrain/alibaba_cluster_trace_2018", + "gifteval_pretrain/australian_electricity_demand", + "gifteval_pretrain/azure_vm_traces_2017", + "gifteval_pretrain/bdg-2_bear", + "gifteval_pretrain/bdg-2_fox", + "gifteval_pretrain/bdg-2_panther", + "gifteval_pretrain/bdg-2_rat", + "gifteval_pretrain/bitcoin_with_missing", + "gifteval_pretrain/borealis", + "gifteval_pretrain/borg_cluster_data_2011", + "gifteval_pretrain/buildings_900k", + "gifteval_pretrain/bull", + "gifteval_pretrain/cdc_fluview_ilinet", + "gifteval_pretrain/cdc_fluview_who_nrevss", + "gifteval_pretrain/china_air_quality", + "gifteval_pretrain/cif_2016_12", + "gifteval_pretrain/cif_2016_6", + "gifteval_pretrain/cmip6_2000", + "gifteval_pretrain/cmip6_2005", + "gifteval_pretrain/cmip6_2010", + "gifteval_pretrain/cockatoo", + "gifteval_pretrain/covid19_energy", + "gifteval_pretrain/covid_mobility", + "gifteval_pretrain/elecdemand", + "gifteval_pretrain/elf", + "gifteval_pretrain/era5_2010", + "gifteval_pretrain/era5_2011", + "gifteval_pretrain/era5_2012", + "gifteval_pretrain/era5_2013", + "gifteval_pretrain/era5_2014", + "gifteval_pretrain/era5_2015", + "gifteval_pretrain/era5_2016", + "gifteval_pretrain/era5_2017", + "gifteval_pretrain/era5_2018", + "gifteval_pretrain/extended_web_traffic_with_missing", + "gifteval_pretrain/favorita_sales", + "gifteval_pretrain/favorita_transactions", + "gifteval_pretrain/gfc12_load", + "gifteval_pretrain/gfc14_load", + "gifteval_pretrain/gfc17_load", + "gifteval_pretrain/godaddy", + "gifteval_pretrain/hog", + "gifteval_pretrain/ideal", + "gifteval_pretrain/kaggle_web_traffic_weekly", + "gifteval_pretrain/kdd2022", + "gifteval_pretrain/largest_2017", + "gifteval_pretrain/largest_2018", + "gifteval_pretrain/largest_2019", + "gifteval_pretrain/largest_2020", + "gifteval_pretrain/largest_2021", + "gifteval_pretrain/lcl", + "gifteval_pretrain/london_smart_meters_with_missing", + "gifteval_pretrain/m1_monthly", + "gifteval_pretrain/m1_quarterly", + "gifteval_pretrain/m1_yearly", + "gifteval_pretrain/m5", + "gifteval_pretrain/monash_m3_monthly", + "gifteval_pretrain/monash_m3_other", + "gifteval_pretrain/monash_m3_quarterly", + "gifteval_pretrain/nn5_daily_with_missing", + "gifteval_pretrain/nn5_weekly", + "gifteval_pretrain/oikolab_weather", + "gifteval_pretrain/pdb", + "gifteval_pretrain/project_tycho", + "gifteval_pretrain/residential_load_power", + "gifteval_pretrain/residential_pv_power", + "gifteval_pretrain/rideshare_with_missing", + "gifteval_pretrain/sceaux", + "gifteval_pretrain/smart", + "gifteval_pretrain/solar_power", + "gifteval_pretrain/spain", + "gifteval_pretrain/subseasonal", + "gifteval_pretrain/subseasonal_precip", + "gifteval_pretrain/sunspot_with_missing", + "gifteval_pretrain/taxi_30min", + "gifteval_pretrain/tourism_quarterly", + "gifteval_pretrain/tourism_yearly", + "gifteval_pretrain/traffic_hourly", + "gifteval_pretrain/traffic_weekly", + "gifteval_pretrain/uber_tlc_daily", + "gifteval_pretrain/uber_tlc_hourly", + "gifteval_pretrain/vehicle_trips_with_missing", + "gifteval_pretrain/wiki-rolling_nips", + "gifteval_pretrain/wind_farms_with_missing", + "gifteval_pretrain/wind_power", + "synthetic:both original and sign-reflected orientations of each sampled allowed or locally generated window; paired quantile loss, seed 197", + "synthetic:both original and sign-reflected orientations of each sampled allowed or locally generated window; paired quantile loss, seed 401", + "synthetic:both original and sign-reflected orientations of each sampled window, seed 197", + "synthetic:independent sign reflection of sampled allowed-corpus and locally generated windows; seeds 43,47,59,79,89,197", + "synthetic:own Fourier/trend/AR/intermittent/changepoint generator at weekly periods52,1, replacing a Bernoulli1/11 share of the original synthetic rows with unchanged total synthetic fraction; independent seed 1000200", + "synthetic:own Fourier/trend/intermittent generator with AR time constant log-uniform from 1 to 10000 steps and zero initial state; seed 79", + "synthetic:own direct_v1 Fourier seasons, damped trends, AR noise, changepoints and intermittent demand; seeds 23,43,47,59,79,89,197", + "synthetic:own direct_v1 Fourier seasons, damped trends, AR noise, changepoints and intermittent demand; seeds 23,43,47,59,79,89,197,401", + "synthetic:own direct_v1 Fourier seasons, damped trends, AR noise, changepoints and intermittent demand; seeds 23,43,47,59,79,89,197,503", + "synthetic:own random requested-horizon prefixes, half of rows retain the full horizon and half use a patch-rounded prefix between one-quarter and the full horizon; independent seed 300200", + "synthetic:own random requested-horizon prefixes, half of rows retain the full horizon and half use a patch-rounded prefix between one-quarter and the full horizon; independent seed 300404", + "synthetic:own stationary Gaussian residuals generated by FFT, equal Matern0.5/1.5/2.5 and RBF spectral families, length scale log-uniform1to10000, theoretical unit marginal variance, FFT size next power of two at least4times window; replacing half of original synthetic residuals with all other generator components unchanged; independent seed 1100200" + ], + "members": [ + { + "weights": "member0.pt", + "weights_sha256": "8a2b252b733cc79c31778ea27ba00fbe61206fef50454514b667c54a928d80a4", + "parameters": 36849984, + "config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true + }, + "model_code": "model0.py" + }, + { + "weights": "member1.pt", + "weights_sha256": "308389b7217c080af9eb185559d4ee3cafa0f3e0f8c4dd8f5526b68198c89988", + "parameters": 36665488, + "config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "model_code": "model1.py" + }, + { + "weights": "member2.pt", + "weights_sha256": "1a2fb20a9fb5cae6526f2e36ea47559626bece78fd9c284899836505030ae9fe", + "parameters": 36601928, + "config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 4, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "input_patch": 8 + }, + "model_code": "model2.py" + } + ], + "checkpoint_sha256": "90199d09666c1653819ef17813f69fc4014fca075f99cc3766d24f457b50ca79", + "checkpoint_digest_method": "SHA-256 of config.json, including ordered member weight hashes", + "training_lineage": [ + { + "checkpoint": "long_seasonal_transfer12k.pt", + "sha256": "8a2b252b733cc79c31778ea27ba00fbe61206fef50454514b667c54a928d80a4", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true + }, + "conversion": { + "method": "matched training delta after zero extension of new seasonal query/head parameters", + "formula": "extend_zero(base) + candidate - extend_zero(control)", + "coefficient": 1.0, + "new_parameters_from_candidate": [ + "long_head.bias", + "long_head.weight", + "long_query.weight" + ], + "parent_hashes": { + "/workspace/research/spectral_add_delta6k.pt": "c3dfc433d51355228fc13d04913db1a7edf83030c33283b150bdcc50f5ae6ea2", + "/workspace/research/runs/long_seasonal/ema012000.pt": "d512cdac520239f0c10e021721424d87cee30086fa70f6cbc41f21e2e04988c3", + "/workspace/research/runs/overflow_control/ema012000.pt": "f11d056b95f1c5eeef174265ebc51742952600e0dae1fa52900860447d5be819" + }, + "base_extension_forward_bitwise_equal": true, + "check_seed": 571, + "seconds": 2.5279976530000567, + "optimizer_updates": 0, + "validation_data_read": false + }, + "parents": [ + "spectral_add_delta6k.pt", + "runs/long_seasonal/ema012000.pt", + "runs/overflow_control/ema012000.pt" + ] + }, + { + "checkpoint": "spectral_add_delta6k.pt", + "sha256": "c3dfc433d51355228fc13d04913db1a7edf83030c33283b150bdcc50f5ae6ea2", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/weekly_slow_ar_delta6k.pt": "c8adf9cadf97dac5e120d8d4d2c8c025bffa2e8b55d8664bf900cce55d00a70b", + "/workspace/research/runs/spectral_synth/ema006000.pt": "683f3824d3c1f605d17bb08d3eef127a54c67eca3867cfbcf1158710a55c4b24", + "/workspace/research/runs/overflow_control/ema006000.pt": "b19875c52ed5024383fb69ccc48cb07a5629ad8011abf134c7dcfcdc50fae2af" + }, + "seconds": 1.4204325219616294 + }, + "parents": [ + "weekly_slow_ar_delta6k.pt", + "runs/spectral_synth/ema006000.pt", + "runs/overflow_control/ema006000.pt" + ] + }, + { + "checkpoint": "runs/long_seasonal/ema012000.pt", + "sha256": "d512cdac520239f0c10e021721424d87cee30086fa70f6cbc41f21e2e04988c3", + "step": 12000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null, + "teacher_coefficient": null + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true + }, + "parents": [ + "long_seasonal_initial.pt", + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "runs/overflow_control/ema012000.pt", + "sha256": "f11d056b95f1c5eeef174265ebc51742952600e0dae1fa52900860447d5be819", + "step": 12000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "weekly_slow_ar_delta6k.pt", + "sha256": "c8adf9cadf97dac5e120d8d4d2c8c025bffa2e8b55d8664bf900cce55d00a70b", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/postloss_slow_ar_delta6k.pt": "0ae7875b49b99a44c295dc2b8243327aeacadc25b2354988abb2c37250359a49", + "/workspace/research/runs/weekly_synth/ema006000.pt": "de053e5baf9641e9245519990d6e5193fc91392cb76e72ceffee1ce63f578fca", + "/workspace/research/runs/overflow_control/ema006000.pt": "b19875c52ed5024383fb69ccc48cb07a5629ad8011abf134c7dcfcdc50fae2af" + }, + "seconds": 2.0751679679378867 + }, + "parents": [ + "postloss_slow_ar_delta6k.pt", + "runs/weekly_synth/ema006000.pt", + "runs/overflow_control/ema006000.pt" + ] + }, + { + "checkpoint": "runs/spectral_synth/ema006000.pt", + "sha256": "683f3824d3c1f605d17bb08d3eef127a54c67eca3867cfbcf1158710a55c4b24", + "step": 6000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null, + "teacher_coefficient": null, + "spectral_synthetic_seed": 1100200, + "spectral_replacement_probability": 0.5, + "spectral_length_scale": [ + 1, + 10000 + ], + "spectral_families": [ + "Matern0.5", + "Matern1.5", + "Matern2.5", + "RBF" + ] + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt", + "runs/confidence_query/ema006000.pt", + "runs/horizon_jitter/ema012000.pt", + "runs/large_corpus_control/ema012000.pt" + ] + }, + { + "checkpoint": "runs/overflow_control/ema006000.pt", + "sha256": "b19875c52ed5024383fb69ccc48cb07a5629ad8011abf134c7dcfcdc50fae2af", + "step": 6000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "long_seasonal_initial.pt", + "sha256": "470ef98d69d00b17defbf41c70a92b22574154cdb6e0317993bccf113e4af93b", + "step": 0, + "seed": 503, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "long_seasonal_features": true + }, + "conversion": { + "method": "zero-initialized sixteen-cycle centered seasonal query/head additions", + "parent_sha256": "22c08571978be31ba57368eb983089a40a44d56d4ae5e17da41afd2a761a258c", + "initial_function_bitwise_equal": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "horizon_delta12k.pt", + "sha256": "22c08571978be31ba57368eb983089a40a44d56d4ae5e17da41afd2a761a258c", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/runs/confidence_query/ema006000.pt": "0bad97e8994aac49ea173443db0a4fa8d72d33f9eb9e2660f06de75f7f1403eb", + "/workspace/research/runs/horizon_jitter/ema012000.pt": "830179d763916a1065fc615d2c5e22f4a3b5b19390dde707ab0f057e13cadff6", + "/workspace/research/runs/large_corpus_control/ema012000.pt": "7f9ba5e01ac59c51a3b63d3067b442e23e15d0abc51ddbcccdd04d6083ae4add" + }, + "seconds": 1.2663014469435439 + }, + "parents": [ + "runs/confidence_query/ema006000.pt", + "runs/horizon_jitter/ema012000.pt", + "runs/large_corpus_control/ema012000.pt" + ] + }, + { + "checkpoint": "postloss_slow_ar_delta6k.pt", + "sha256": "0ae7875b49b99a44c295dc2b8243327aeacadc25b2354988abb2c37250359a49", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/runs/postloss/ema003000.pt": "82c785d40998e155a20290c9965c346c26cd397fa0f3cf36278377ad2aed5c7d", + "/workspace/research/runs/long_memory_synth_recovery/ema006000.pt": "fea5b5290a3a9be5618eaeaf67e918e4f677d5be908d562040ce4bdfeb549bd9", + "/workspace/research/runs/partial_targets/ema006000.pt": "67562486b099a350da53c3caa5ff0932fe7fecdfe72c1879b064b2a9bb173dfb" + }, + "seconds": 1.0092943429481238 + }, + "parents": [ + "runs/postloss/ema003000.pt", + "runs/long_memory_synth_recovery/ema006000.pt", + "runs/partial_targets/ema006000.pt" + ] + }, + { + "checkpoint": "runs/weekly_synth/ema006000.pt", + "sha256": "de053e5baf9641e9245519990d6e5193fc91392cb76e72ceffee1ce63f578fca", + "step": 6000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true, + "weekly_synthetic_seed": 1000200, + "weekly_replacement_probability": 0.09090909090909091, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "runs/confidence_query/ema006000.pt", + "sha256": "0bad97e8994aac49ea173443db0a4fa8d72d33f9eb9e2660f06de75f7f1403eb", + "step": 6000, + "seed": 89, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 0.0002, + "steps": 6000 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true + }, + "parents": [ + "runs/recency_features/ema024000.pt" + ] + }, + { + "checkpoint": "runs/horizon_jitter/ema012000.pt", + "sha256": "830179d763916a1065fc615d2c5e22f4a3b5b19390dde707ab0f057e13cadff6", + "step": 12000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "partial_target_lengths": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/large_corpus_control/ema012000.pt", + "sha256": "7f9ba5e01ac59c51a3b63d3067b442e23e15d0abc51ddbcccdd04d6083ae4add", + "step": 12000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/postloss/ema003000.pt", + "sha256": "82c785d40998e155a20290c9965c346c26cd397fa0f3cf36278377ad2aed5c7d", + "step": 3000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "fixed_postprocessing_loss": true, + "normalization_overflow_fallback": true + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "runs/long_memory_synth_recovery/ema006000.pt", + "sha256": "fea5b5290a3a9be5618eaeaf67e918e4f677d5be908d562040ce4bdfeb549bd9", + "step": 6000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "context": null, + "sample_context": 4096, + "synthetic_ar_time_constants": [ + 1, + 10000 + ] + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "partial_target_lengths": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/partial_targets/ema006000.pt", + "sha256": "67562486b099a350da53c3caa5ff0932fe7fecdfe72c1879b064b2a9bb173dfb", + "step": 6000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "partial_target_lengths": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/recency_features/ema024000.pt", + "sha256": "1530fbb577a87ca4eb39da83d6fee9b8ee5bc924202e021e3a7b56493112f564", + "step": 24000, + "seed": 59, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/patch16_trial/ema006000.pt" + ] + }, + { + "checkpoint": "runs/recency_features/ema012000.pt", + "sha256": "8ccb6870a025e1097331a3a288b1183741a413f3460fbf3352d0c589c6a4394c", + "step": 12000, + "seed": 59, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/patch16_trial/ema006000.pt" + ] + }, + { + "checkpoint": "runs/patch16_trial/ema006000.pt", + "sha256": "0ff54447074e0271d2e331c7d3e6e9e0fdd73353e4d8cef0175ff627385f71c3", + "step": 6000, + "seed": 47, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024 + }, + "parents": [ + "patch16_init.pt" + ] + }, + { + "checkpoint": "patch16_init.pt", + "sha256": "d69531bfde5bf801e7f36c515bf15fd0cae0bd84f7d1479d35f4a7b67f26b508", + "step": 6000, + "seed": 43, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024 + }, + "conversion": { + "from_checkpoint": "/run-state/workspace/research/runs/large_sign/ema006000.pt", + "from_sha256": "96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547", + "method": "fold input/query halves by summation; retain first 16 output rows; preserve physical positional units" + }, + "parents": [ + "runs/large_sign/ema006000.pt" + ] + }, + { + "checkpoint": "runs/large_sign/ema006000.pt", + "sha256": "96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547", + "step": 6000, + "seed": 43, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 32, + "max_context": 4096, + "max_horizon": 1024 + }, + "parents": [ + "runs/direct_large/step024000.pt" + ] + }, + { + "checkpoint": "runs/direct_large/step024000.pt", + "sha256": "b7e4f38aebcd2cf38ce484edaad8d19851317fb3b8df485e2faa0d0423cbcb48", + "step": 24000, + "seed": 23, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 128, + "lr": 0.0002, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 32, + "max_context": 4096, + "max_horizon": 1024 + }, + "initialization": "random initialization in this workspace" + }, + { + "checkpoint": "runs/patch8/ema006000.pt", + "sha256": "308389b7217c080af9eb185559d4ee3cafa0f3e0f8c4dd8f5526b68198c89988", + "step": 6000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "patch8_initial.pt" + ] + }, + { + "checkpoint": "patch8_initial.pt", + "sha256": "e7da4d47a9cc984a9423296679d7c9127ef2d679be950b9e8d3758e6fca074cc", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "from_checkpoint": "/run-state/workspace/research/horizon_delta12k.pt", + "from_sha256": "22c08571978be31ba57368eb983089a40a44d56d4ae5e17da41afd2a761a258c", + "method": "fold input/query/recency halves by summation; retain first8 output rows; preserve physical position units", + "exact_function_preservation": false + }, + "parents": [ + "horizon_delta12k.pt", + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "runs/split_patch/ema012000.pt", + "sha256": "1a2fb20a9fb5cae6526f2e36ea47559626bece78fd9c284899836505030ae9fe", + "step": 12000, + "seed": 401, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 32, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300404 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 4, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "input_patch": 8 + }, + "parents": [ + "split_patch_initial.pt" + ] + }, + { + "checkpoint": "split_patch_initial.pt", + "sha256": "0719b4dce554764ef69181d8b19d8da11849ef32b35391ffee6700e639a73114", + "step": 0, + "seed": null, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 4, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "input_patch": 8 + }, + "conversion": { + "method": "retain input8; sum query/recency halves and keep first4 output rows; same physical position coordinates", + "exact_function_preservation": false, + "parent_sha256": "308389b7217c080af9eb185559d4ee3cafa0f3e0f8c4dd8f5526b68198c89988" + }, + "parents": [ + "runs/patch8/ema006000.pt", + "runs/patch8/ema006000.pt" + ] + } + ], + "ensemble_weights": [ + 0.3333333333333333, + 0.3333333333333333, + 0.3333333333333333 + ], + "every_member_forecasts_every_instance": true, + "member_history_caps": [ + { + "input_and_summary": 4096, + "encoder_and_normalization": 4096, + "fixed_rules": 4096 + }, + { + "input_and_summary": 4096, + "encoder_and_normalization": 4096, + "fixed_rules": 4096 + }, + { + "input_and_summary": 4096, + "encoder_and_normalization": 4096, + "fixed_rules": 4096 + } + ], + "postprocessing_order": "each member: sign averaging, positivity, aligned seasonal rule, continuity, zero0.4, finite-value replacement; then equal quantile average", + "runtime_code_sha256": { + "infer.sh": "5fe66b4fe9a4787285d830cfd96975701e97286a75ba7c3687bd8891475edf68", + "continuity.py": "dbb08d2229ad80ad00f638b0b9f2f6ca13c663e0fd6730058e5fee8ff54545d5", + "zero_mass.py": "f079d509009bcda409b80eb64467c869b838cfbab11b2bd4c660c2875b6642fe", + "model2.py": "89bb87b2501b117ac02daf001a68f389ec488931ce18905445d15874760685be", + "seasonal.py": "b946e63048196ab5ea8b249137d48c80d8510943caccd0f180e4fb86d9b24b37", + "model0.py": "3eaa4aed0a1c62b80d94be6c3084b10a594e9fce17444eac17ca3f1b0b5c549e", + "ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "predict.py": "c1876617c78330ba89353f706cfacf7d3671e02a669620a48d9eb7c63e9aa7ef", + "model.py": "c27748fa4b1186b513f76eca26052753b8dcd1794994e5989addaf371ca70f2e", + "model1.py": "c27748fa4b1186b513f76eca26052753b8dcd1794994e5989addaf371ca70f2e" + }, + "notes": "All members originate from random initialization in this workspace. Only declared pretraining sources and local generators were used. Validation is selection/diagnostics only. No inference-time fitting or parameter adaptation." +} diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..e46eb51df22a18a082a86731f86b7d8b967c06fa --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/predict.py @@ -0,0 +1,72 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import importlib.util +from seasonal import apply_gate +from continuity import apply_continuity +from zero_mass import project +import ts_io + +def load_model(checkpoint,device='cuda'): + from types import SimpleNamespace + path=Path(checkpoint);descriptor=json.loads(path.read_text());members=[] + for entry in descriptor['members']: + ck=torch.load(path.parent/entry['weights'],map_location='cpu',weights_only=False) + spec=importlib.util.spec_from_file_location('member_model_'+str(len(members)),path.parent/entry['model_code']) + module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module) + model=module.DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval();members.append(model) + assert len(members)==3 + return SimpleNamespace(models=members,max_context=max(m.max_context for m in members)) + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + forecasts=[] + for member in model.models: + member_ctx=ctx[:,-member.max_context:] + member_x=x[:,-member.max_context:] + rule_context=getattr(member,'rule_context',member.max_context) + rule_ctx=member_ctx[:,-rule_context:] + rule_x=member_x[:,-rule_context:] + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16): + qq,mu,scale=member(torch.cat((member_x,-member_x),0),p.repeat(2,1),h) + qq=qq*scale[:,:,None]+mu[:,:,None] + qq=(qq[:len(ids)]-qq[len(ids):].flip(-1))*.5 + recent=rule_x[:,-4096:] + positive=((recent>=0)|~torch.isfinite(recent)).all(-1) + qq=torch.where(positive[:,None,None],qq.clamp(min=0),qq) + q=qq.transpose(1,2).float().cpu().numpy() + q=apply_gate(rule_ctx[:,-4096:],p.cpu().numpy(),q) + q=project(rule_ctx,apply_continuity(rule_ctx,q)) + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + forecasts.append(q) + q=(forecasts[0]+forecasts[1]+forecasts[2])/3 + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'config.json'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/model_manifest.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/model_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..6791dbc71db3e966ce77e49b8abc2a6560ca8053 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/model_manifest.json @@ -0,0 +1,1205 @@ +{ + "name": "direct-seasonal-foundation", + "contract": "timeseries-forecast/v1", + "parameters": 36849984, + "pretrained_assets": [], + "sources_used": [ + "gifteval_pretrain/BEIJING_SUBWAY_30MIN", + "gifteval_pretrain/HZMETRO", + "gifteval_pretrain/LOS_LOOP", + "gifteval_pretrain/PEMS03", + "gifteval_pretrain/PEMS04", + "gifteval_pretrain/PEMS07", + "gifteval_pretrain/PEMS08", + "gifteval_pretrain/PEMS_BAY", + "gifteval_pretrain/Q-TRAFFIC", + "gifteval_pretrain/SHMETRO", + "gifteval_pretrain/alibaba_cluster_trace_2018", + "gifteval_pretrain/australian_electricity_demand", + "gifteval_pretrain/azure_vm_traces_2017", + "gifteval_pretrain/bdg-2_bear", + "gifteval_pretrain/bdg-2_fox", + "gifteval_pretrain/bdg-2_panther", + "gifteval_pretrain/bdg-2_rat", + "gifteval_pretrain/bitcoin_with_missing", + "gifteval_pretrain/borealis", + "gifteval_pretrain/borg_cluster_data_2011", + "gifteval_pretrain/buildings_900k", + "gifteval_pretrain/bull", + "gifteval_pretrain/cdc_fluview_ilinet", + "gifteval_pretrain/cdc_fluview_who_nrevss", + "gifteval_pretrain/china_air_quality", + "gifteval_pretrain/cif_2016_12", + "gifteval_pretrain/cif_2016_6", + "gifteval_pretrain/cmip6_2000", + "gifteval_pretrain/cmip6_2005", + "gifteval_pretrain/cmip6_2010", + "gifteval_pretrain/cockatoo", + "gifteval_pretrain/covid19_energy", + "gifteval_pretrain/covid_mobility", + "gifteval_pretrain/elecdemand", + "gifteval_pretrain/elf", + "gifteval_pretrain/era5_2010", + "gifteval_pretrain/era5_2011", + "gifteval_pretrain/era5_2012", + "gifteval_pretrain/era5_2013", + "gifteval_pretrain/era5_2014", + "gifteval_pretrain/era5_2015", + "gifteval_pretrain/era5_2016", + "gifteval_pretrain/era5_2017", + "gifteval_pretrain/era5_2018", + "gifteval_pretrain/extended_web_traffic_with_missing", + "gifteval_pretrain/favorita_sales", + "gifteval_pretrain/favorita_transactions", + "gifteval_pretrain/gfc12_load", + "gifteval_pretrain/gfc14_load", + "gifteval_pretrain/gfc17_load", + "gifteval_pretrain/godaddy", + "gifteval_pretrain/hog", + "gifteval_pretrain/ideal", + "gifteval_pretrain/kaggle_web_traffic_weekly", + "gifteval_pretrain/kdd2022", + "gifteval_pretrain/largest_2017", + "gifteval_pretrain/largest_2018", + "gifteval_pretrain/largest_2019", + "gifteval_pretrain/largest_2020", + "gifteval_pretrain/largest_2021", + "gifteval_pretrain/lcl", + "gifteval_pretrain/london_smart_meters_with_missing", + "gifteval_pretrain/m1_monthly", + "gifteval_pretrain/m1_quarterly", + "gifteval_pretrain/m1_yearly", + "gifteval_pretrain/m5", + "gifteval_pretrain/monash_m3_monthly", + "gifteval_pretrain/monash_m3_other", + "gifteval_pretrain/monash_m3_quarterly", + "gifteval_pretrain/nn5_daily_with_missing", + "gifteval_pretrain/nn5_weekly", + "gifteval_pretrain/oikolab_weather", + "gifteval_pretrain/pdb", + "gifteval_pretrain/project_tycho", + "gifteval_pretrain/residential_load_power", + "gifteval_pretrain/residential_pv_power", + "gifteval_pretrain/rideshare_with_missing", + "gifteval_pretrain/sceaux", + "gifteval_pretrain/smart", + "gifteval_pretrain/solar_power", + "gifteval_pretrain/spain", + "gifteval_pretrain/subseasonal", + "gifteval_pretrain/subseasonal_precip", + "gifteval_pretrain/sunspot_with_missing", + "gifteval_pretrain/taxi_30min", + "gifteval_pretrain/tourism_quarterly", + "gifteval_pretrain/tourism_yearly", + "gifteval_pretrain/traffic_hourly", + "gifteval_pretrain/traffic_weekly", + "gifteval_pretrain/uber_tlc_daily", + "gifteval_pretrain/uber_tlc_hourly", + "gifteval_pretrain/vehicle_trips_with_missing", + "gifteval_pretrain/wiki-rolling_nips", + "gifteval_pretrain/wind_farms_with_missing", + "gifteval_pretrain/wind_power", + "synthetic:both original and sign-reflected orientations of each sampled allowed or locally generated window; paired quantile loss, seed 197", + "synthetic:both original and sign-reflected orientations of each sampled window, seed 197", + "synthetic:independent sign reflection of sampled allowed-corpus and locally generated windows; seeds 43,47,59,79,89,197", + "synthetic:own Fourier/trend/AR/intermittent/changepoint generator at weekly periods52,1, replacing a Bernoulli1/11 share of the original synthetic rows with unchanged total synthetic fraction; independent seed 1000200", + "synthetic:own Fourier/trend/intermittent generator with AR time constant log-uniform from 1 to 10000 steps and zero initial state; seed 79", + "synthetic:own direct_v1 Fourier seasons, damped trends, AR noise, changepoints and intermittent demand; seeds 23,43,47,59,79,89,197,503", + "synthetic:own random requested-horizon prefixes, half of rows retain the full horizon and half use a patch-rounded prefix between one-quarter and the full horizon; independent seed 300200", + "synthetic:own stationary Gaussian residuals generated by FFT, equal Matern0.5/1.5/2.5 and RBF spectral families, length scale log-uniform1to10000, theoretical unit marginal variance, FFT size next power of two at least4times window; replacing half of original synthetic residuals with all other generator components unchanged; independent seed 1100200" + ], + "weights_sha256": "8a2b252b733cc79c31778ea27ba00fbe61206fef50454514b667c54a928d80a4", + "config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true + }, + "training_lineage": [ + { + "checkpoint": "long_seasonal_transfer12k.pt", + "sha256": "8a2b252b733cc79c31778ea27ba00fbe61206fef50454514b667c54a928d80a4", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true + }, + "conversion": { + "method": "matched training delta after zero extension of new seasonal query/head parameters", + "formula": "extend_zero(base) + candidate - extend_zero(control)", + "coefficient": 1.0, + "new_parameters_from_candidate": [ + "long_head.bias", + "long_head.weight", + "long_query.weight" + ], + "parent_hashes": { + "/workspace/research/spectral_add_delta6k.pt": "c3dfc433d51355228fc13d04913db1a7edf83030c33283b150bdcc50f5ae6ea2", + "/workspace/research/runs/long_seasonal/ema012000.pt": "d512cdac520239f0c10e021721424d87cee30086fa70f6cbc41f21e2e04988c3", + "/workspace/research/runs/overflow_control/ema012000.pt": "f11d056b95f1c5eeef174265ebc51742952600e0dae1fa52900860447d5be819" + }, + "base_extension_forward_bitwise_equal": true, + "check_seed": 571, + "seconds": 2.5279976530000567, + "optimizer_updates": 0, + "validation_data_read": false + }, + "parents": [ + "spectral_add_delta6k.pt", + "runs/long_seasonal/ema012000.pt", + "runs/overflow_control/ema012000.pt" + ] + }, + { + "checkpoint": "spectral_add_delta6k.pt", + "sha256": "c3dfc433d51355228fc13d04913db1a7edf83030c33283b150bdcc50f5ae6ea2", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/weekly_slow_ar_delta6k.pt": "c8adf9cadf97dac5e120d8d4d2c8c025bffa2e8b55d8664bf900cce55d00a70b", + "/workspace/research/runs/spectral_synth/ema006000.pt": "683f3824d3c1f605d17bb08d3eef127a54c67eca3867cfbcf1158710a55c4b24", + "/workspace/research/runs/overflow_control/ema006000.pt": "b19875c52ed5024383fb69ccc48cb07a5629ad8011abf134c7dcfcdc50fae2af" + }, + "seconds": 1.4204325219616294 + }, + "parents": [ + "weekly_slow_ar_delta6k.pt", + "runs/spectral_synth/ema006000.pt", + "runs/overflow_control/ema006000.pt" + ] + }, + { + "checkpoint": "runs/long_seasonal/ema012000.pt", + "sha256": "d512cdac520239f0c10e021721424d87cee30086fa70f6cbc41f21e2e04988c3", + "step": 12000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null, + "teacher_coefficient": null + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true + }, + "parents": [ + "long_seasonal_initial.pt", + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "runs/overflow_control/ema012000.pt", + "sha256": "f11d056b95f1c5eeef174265ebc51742952600e0dae1fa52900860447d5be819", + "step": 12000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "weekly_slow_ar_delta6k.pt", + "sha256": "c8adf9cadf97dac5e120d8d4d2c8c025bffa2e8b55d8664bf900cce55d00a70b", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/postloss_slow_ar_delta6k.pt": "0ae7875b49b99a44c295dc2b8243327aeacadc25b2354988abb2c37250359a49", + "/workspace/research/runs/weekly_synth/ema006000.pt": "de053e5baf9641e9245519990d6e5193fc91392cb76e72ceffee1ce63f578fca", + "/workspace/research/runs/overflow_control/ema006000.pt": "b19875c52ed5024383fb69ccc48cb07a5629ad8011abf134c7dcfcdc50fae2af" + }, + "seconds": 2.0751679679378867 + }, + "parents": [ + "postloss_slow_ar_delta6k.pt", + "runs/weekly_synth/ema006000.pt", + "runs/overflow_control/ema006000.pt" + ] + }, + { + "checkpoint": "runs/spectral_synth/ema006000.pt", + "sha256": "683f3824d3c1f605d17bb08d3eef127a54c67eca3867cfbcf1158710a55c4b24", + "step": 6000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null, + "teacher_coefficient": null, + "spectral_synthetic_seed": 1100200, + "spectral_replacement_probability": 0.5, + "spectral_length_scale": [ + 1, + 10000 + ], + "spectral_families": [ + "Matern0.5", + "Matern1.5", + "Matern2.5", + "RBF" + ] + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt", + "runs/confidence_query/ema006000.pt", + "runs/horizon_jitter/ema012000.pt", + "runs/large_corpus_control/ema012000.pt" + ] + }, + { + "checkpoint": "runs/overflow_control/ema006000.pt", + "sha256": "b19875c52ed5024383fb69ccc48cb07a5629ad8011abf134c7dcfcdc50fae2af", + "step": 6000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "long_seasonal_initial.pt", + "sha256": "470ef98d69d00b17defbf41c70a92b22574154cdb6e0317993bccf113e4af93b", + "step": 0, + "seed": 503, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "long_seasonal_features": true + }, + "conversion": { + "method": "zero-initialized sixteen-cycle centered seasonal query/head additions", + "parent_sha256": "22c08571978be31ba57368eb983089a40a44d56d4ae5e17da41afd2a761a258c", + "initial_function_bitwise_equal": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "horizon_delta12k.pt", + "sha256": "22c08571978be31ba57368eb983089a40a44d56d4ae5e17da41afd2a761a258c", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/runs/confidence_query/ema006000.pt": "0bad97e8994aac49ea173443db0a4fa8d72d33f9eb9e2660f06de75f7f1403eb", + "/workspace/research/runs/horizon_jitter/ema012000.pt": "830179d763916a1065fc615d2c5e22f4a3b5b19390dde707ab0f057e13cadff6", + "/workspace/research/runs/large_corpus_control/ema012000.pt": "7f9ba5e01ac59c51a3b63d3067b442e23e15d0abc51ddbcccdd04d6083ae4add" + }, + "seconds": 1.2663014469435439 + }, + "parents": [ + "runs/confidence_query/ema006000.pt", + "runs/horizon_jitter/ema012000.pt", + "runs/large_corpus_control/ema012000.pt" + ] + }, + { + "checkpoint": "postloss_slow_ar_delta6k.pt", + "sha256": "0ae7875b49b99a44c295dc2b8243327aeacadc25b2354988abb2c37250359a49", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/runs/postloss/ema003000.pt": "82c785d40998e155a20290c9965c346c26cd397fa0f3cf36278377ad2aed5c7d", + "/workspace/research/runs/long_memory_synth_recovery/ema006000.pt": "fea5b5290a3a9be5618eaeaf67e918e4f677d5be908d562040ce4bdfeb549bd9", + "/workspace/research/runs/partial_targets/ema006000.pt": "67562486b099a350da53c3caa5ff0932fe7fecdfe72c1879b064b2a9bb173dfb" + }, + "seconds": 1.0092943429481238 + }, + "parents": [ + "runs/postloss/ema003000.pt", + "runs/long_memory_synth_recovery/ema006000.pt", + "runs/partial_targets/ema006000.pt" + ] + }, + { + "checkpoint": "runs/weekly_synth/ema006000.pt", + "sha256": "de053e5baf9641e9245519990d6e5193fc91392cb76e72ceffee1ce63f578fca", + "step": 6000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true, + "weekly_synthetic_seed": 1000200, + "weekly_replacement_probability": 0.09090909090909091, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "runs/confidence_query/ema006000.pt", + "sha256": "0bad97e8994aac49ea173443db0a4fa8d72d33f9eb9e2660f06de75f7f1403eb", + "step": 6000, + "seed": 89, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 0.0002, + "steps": 6000 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true + }, + "parents": [ + "runs/recency_features/ema024000.pt" + ] + }, + { + "checkpoint": "runs/horizon_jitter/ema012000.pt", + "sha256": "830179d763916a1065fc615d2c5e22f4a3b5b19390dde707ab0f057e13cadff6", + "step": 12000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "partial_target_lengths": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/large_corpus_control/ema012000.pt", + "sha256": "7f9ba5e01ac59c51a3b63d3067b442e23e15d0abc51ddbcccdd04d6083ae4add", + "step": 12000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/postloss/ema003000.pt", + "sha256": "82c785d40998e155a20290c9965c346c26cd397fa0f3cf36278377ad2aed5c7d", + "step": 3000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "fixed_postprocessing_loss": true, + "normalization_overflow_fallback": true + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "runs/long_memory_synth_recovery/ema006000.pt", + "sha256": "fea5b5290a3a9be5618eaeaf67e918e4f677d5be908d562040ce4bdfeb549bd9", + "step": 6000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "context": null, + "sample_context": 4096, + "synthetic_ar_time_constants": [ + 1, + 10000 + ] + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "partial_target_lengths": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/partial_targets/ema006000.pt", + "sha256": "67562486b099a350da53c3caa5ff0932fe7fecdfe72c1879b064b2a9bb173dfb", + "step": 6000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "partial_target_lengths": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/recency_features/ema024000.pt", + "sha256": "1530fbb577a87ca4eb39da83d6fee9b8ee5bc924202e021e3a7b56493112f564", + "step": 24000, + "seed": 59, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/patch16_trial/ema006000.pt" + ] + }, + { + "checkpoint": "runs/recency_features/ema012000.pt", + "sha256": "8ccb6870a025e1097331a3a288b1183741a413f3460fbf3352d0c589c6a4394c", + "step": 12000, + "seed": 59, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/patch16_trial/ema006000.pt" + ] + }, + { + "checkpoint": "runs/patch16_trial/ema006000.pt", + "sha256": "0ff54447074e0271d2e331c7d3e6e9e0fdd73353e4d8cef0175ff627385f71c3", + "step": 6000, + "seed": 47, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024 + }, + "parents": [ + "patch16_init.pt" + ] + }, + { + "checkpoint": "patch16_init.pt", + "sha256": "d69531bfde5bf801e7f36c515bf15fd0cae0bd84f7d1479d35f4a7b67f26b508", + "step": 6000, + "seed": 43, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024 + }, + "conversion": { + "from_checkpoint": "/run-state/workspace/research/runs/large_sign/ema006000.pt", + "from_sha256": "96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547", + "method": "fold input/query halves by summation; retain first 16 output rows; preserve physical positional units" + }, + "parents": [ + "runs/large_sign/ema006000.pt" + ] + }, + { + "checkpoint": "runs/large_sign/ema006000.pt", + "sha256": "96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547", + "step": 6000, + "seed": 43, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 32, + "max_context": 4096, + "max_horizon": 1024 + }, + "parents": [ + "runs/direct_large/step024000.pt" + ] + }, + { + "checkpoint": "runs/direct_large/step024000.pt", + "sha256": "b7e4f38aebcd2cf38ce484edaad8d19851317fb3b8df485e2faa0d0423cbcb48", + "step": 24000, + "seed": 23, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 128, + "lr": 0.0002, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 32, + "max_context": 4096, + "max_horizon": 1024 + }, + "initialization": "random initialization in this workspace" + } + ], + "symmetric_averaging": true, + "seasonal_gate": { + "variance_ratio_threshold": 0.25, + "maximum_weight": 0.98, + "cycles_averaged": 4, + "template_mode": "aligned", + "amplitude_ratio_clip": [ + 0.5, + 2.0 + ], + "latest_cycle_minimum_coverage": 0.75, + "variance_noise_correction": "mean squared seasonal differences / 2" + }, + "continuity": { + "decay_steps": 24, + "variance_ratio_threshold": 0.5, + "maximum_weight": 0.95, + "lookback": 512, + "slope_median_differences": 8 + }, + "notes": "All training lineage originates from random initialization here, using only the declared corpus and locally generated series. Validation was used only for selection and diagnostics. Context transformations are fixed formulas; there is no inference-time fitting or parameter adaptation.", + "runtime_code_sha256": { + "seasonal.py": "b946e63048196ab5ea8b249137d48c80d8510943caccd0f180e4fb86d9b24b37", + "continuity.py": "dbb08d2229ad80ad00f638b0b9f2f6ca13c663e0fd6730058e5fee8ff54545d5", + "predict.py": "9bde896945a2cd8f892e7eeb6328ed2dfda09293532f3a4a64d929c9943614ef", + "infer.sh": "5fe66b4fe9a4787285d830cfd96975701e97286a75ba7c3687bd8891475edf68", + "zero_mass.py": "f079d509009bcda409b80eb64467c869b838cfbab11b2bd4c660c2875b6642fe", + "ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "model.py": "3eaa4aed0a1c62b80d94be6c3084b10a594e9fce17444eac17ca3f1b0b5c549e" + }, + "checkpoint_composition": { + "method": "matched training delta after zero extension of new seasonal query/head parameters", + "formula": "extend_zero(base) + candidate - extend_zero(control)", + "coefficient": 1.0, + "new_parameters_from_candidate": [ + "long_head.bias", + "long_head.weight", + "long_query.weight" + ], + "parent_hashes": { + "/workspace/research/spectral_add_delta6k.pt": "c3dfc433d51355228fc13d04913db1a7edf83030c33283b150bdcc50f5ae6ea2", + "/workspace/research/runs/long_seasonal/ema012000.pt": "d512cdac520239f0c10e021721424d87cee30086fa70f6cbc41f21e2e04988c3", + "/workspace/research/runs/overflow_control/ema012000.pt": "f11d056b95f1c5eeef174265ebc51742952600e0dae1fa52900860447d5be819" + }, + "base_extension_forward_bitwise_equal": true, + "check_seed": 571, + "seconds": 2.5279976530000567, + "optimizer_updates": 0, + "validation_data_read": false + }, + "normalization_overflow_fallback": { + "trigger": "nonfinite float32 context mean or scale", + "arithmetic": "float64 context statistics on affected rows; original arithmetic on ordinary rows", + "inference_fitting": false + }, + "trend_summary": { + "fixed_averaging_width": 128, + "matches_all_pretraining_context_widths": true, + "independent_of_batch_padding": true + }, + "zero_mass_projection": { + "threshold_in_context_standard_deviations": 0.4, + "nonnegative_context_required": true, + "minimum_exact_zeros": 4, + "minimum_zero_fraction": 0.1, + "context_cap": 4096 + }, + "recency_features": { + "query_projection_parameters": 32768, + "latest_vs_four_cycle_level": true, + "amplitude_ratio_clip": [ + 0.5, + 2.0 + ], + "minimum_observed_cycles": 3 + }, + "long_seasonal_features": { + "cycles": [ + 4, + 16 + ], + "each_cycle_centered": true, + "minimum_total_cycles": 8, + "minimum_recent_cycles": 2, + "query_features": [ + "centered16-minus4 phase mean", + "observed16-cycle fraction" + ], + "median_shift": "sum of two learned tanh gates times template differences", + "same_shift_all_quantiles": true, + "maximum_context": 4096, + "parameters_fixed_at_inference": true + }, + "confidence_features": { + "query_projection_parameters": 3072, + "backbone_frozen_during_projection_training": true, + "training_objective": "weighted quantile and median loss after averaging both sign orientations", + "statistics": [ + "mean absolute difference", + "root mean square difference" + ], + "lags": "one and the two frequency-derived periods", + "lookback": "512 for lag one; eight cycles for seasonal lags", + "minimum_valid_pairs": 8, + "insufficient_pair_defaults": [ + 1, + 1.4142135623730951 + ], + "statistic_clip": 10, + "transform": "log1p", + "stage_scope": "Frozen-backbone details refer to projection introduction; subsequent updates are recorded in training_lineage.training_settings." + }, + "partial_target_training": { + "available_horizon": "last finite training-label position rounded up to the patch boundary", + "decoder_future_key_mask": true, + "per_row_horizon_metadata": true, + "inference_uses_requested_horizon_only": true + }, + "training_provenance_code_sha256": { + "confidence_query/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "confidence_query/model.py": "b4f11ba2018e2b50879cdc33acf0138301548971508b58035a7c96a29aaa6f2d", + "confidence_query/train.py": "fc8a7555a5a6b0a6f91e80ac8cc9cbbfddaa2b26468c57f49dfb17671b22ce93", + "direct_large/data.py": "6e6db217936f8dd79380d2ceff3eaa8598a44f1b60b17acae7bfde2363116847", + "direct_large/evaluate.py": "eaea99e8cd44c9f7c70a45fa9abf51354ae5449dbad273fcb55e48ad02652223", + "direct_large/model.py": "146d93a3f95b13bda8b1b437bc36621b91356cf946e94f62999f89e7fb348071", + "direct_large/pack.py": "3bcc4ce9eb3361ad741ceebd7efce7a2fb86fb49543f52c72aabd0e3e8cd17ce", + "direct_large/predict.py": "930a9f18f9f5da47c03859698c9d2f5567d1e1c73fd61edac1ed20b3a6f9bb50", + "direct_large/publish.py": "3c167f33e8571731c26f1cb70168eda54ef9cb4c76423dfd374240b75ca5f106", + "direct_large/record.py": "b3b00b0ed14bc3af00c7b1ad97195238ecb8f06e96bc41f0c07913bc3f6ed949", + "direct_large/train.py": "b9ad6b2adddeaf12961b529d6535dd33f6d044a31979b5c9e49dceafbadd3ac0", + "direct_large/ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "direct_large/validation_subset.py": "8d3eb9d3f3aa124368761ef402ff066935c0be31a62b25b8551a45dcb922e28d", + "full_paired/check.py": "90ac1c78846439d51ab8acd62a19bd536c7c394bd02e94f6d5ff17c0af8bd116", + "full_paired/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "full_paired/model.py": "c27748fa4b1186b513f76eca26052753b8dcd1794994e5989addaf371ca70f2e", + "horizon_jitter/data.py": "5044cf648323420095ed6058d29f837c07ff5559b606df8b00cc8d1e95c8b58e", + "horizon_jitter/model.py": "186bb282236f23cc665a012194d26e58f51004c680393352ec053f5308f1240f", + "horizon_jitter/train.py": "4e9cbca1293f18f7eea2c72dba127815c0934a13c86e8f6cc881a749676d41a6", + "large_corpus/data.py": "27c078cb0ed085717a364f556b5ff976fd803d5af37612cf3a03a0a3ca12a678", + "large_corpus/model.py": "e3a1bc01e89a0d6d750ede2cc969272ad01e1ca580b174af7dee00db029f1cf7", + "large_corpus/train.py": "3baca16c3945e6ef241ccbc9c13644539e3c265f71095cbbaa61a3d338e4fafe", + "large_sign/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "large_sign/evaluate.py": "eaea99e8cd44c9f7c70a45fa9abf51354ae5449dbad273fcb55e48ad02652223", + "large_sign/model.py": "3fff6445a1982a1b3c92f06a9b5f1bb627dda6a291b0b2364bcfb1a6457830d7", + "large_sign/pack.py": "3bcc4ce9eb3361ad741ceebd7efce7a2fb86fb49543f52c72aabd0e3e8cd17ce", + "large_sign/predict.py": "930a9f18f9f5da47c03859698c9d2f5567d1e1c73fd61edac1ed20b3a6f9bb50", + "large_sign/publish.py": "3c167f33e8571731c26f1cb70168eda54ef9cb4c76423dfd374240b75ca5f106", + "large_sign/record.py": "b3b00b0ed14bc3af00c7b1ad97195238ecb8f06e96bc41f0c07913bc3f6ed949", + "large_sign/train.py": "a597f40ab87cce04e96dc654d12e56cdf40ffd87f00034d8bc4d56dff4eb7c68", + "large_sign/ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "large_sign/validation_subset.py": "8d3eb9d3f3aa124368761ef402ff066935c0be31a62b25b8551a45dcb922e28d", + "long_memory_synth/data.py": "2955ec414de97f7ec91c8863873b7ae50ebe8f0ccb7fe48c41599e69da88ec34", + "long_memory_synth/model.py": "186bb282236f23cc665a012194d26e58f51004c680393352ec053f5308f1240f", + "long_memory_synth/train.py": "75918ac02d30ad8289632bc8a3ce1386c949fd670522799af59536d4cab0b9e9", + "long_seasonal/check.py": "e55fe780892204889e210d1591ae3f0b964d72ec1916b9b5e768b938aba28fc1", + "long_seasonal/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "long_seasonal/launch.py": "68c56b8abde125eb8de866807f8deb946c30e4c52866bc0cafcab82198b58def", + "long_seasonal/long_features.py": "270d84ff1208085f65856e8c489998e6248af5c5ea1c3c47b5161f7d6b621b13", + "long_seasonal/model.py": "3eaa4aed0a1c62b80d94be6c3084b10a594e9fce17444eac17ca3f1b0b5c549e", + "long_seasonal/transfer.py": "301df5a793988edbe50b3384c5777d8679161142943578bc7723a552ed4f3d04", + "overflow_control/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "overflow_control/model.py": "44eeb23c037e91b8f67e432615ce46540a7ac4242919785f9c4218de23121499", + "partial_delta/merge.py": "63984a0f46f7d48817037f5bf5a1c9319e45a9b1924cde62c667ac49ce47532e", + "partial_targets/data.py": "27c078cb0ed085717a364f556b5ff976fd803d5af37612cf3a03a0a3ca12a678", + "partial_targets/model.py": "186bb282236f23cc665a012194d26e58f51004c680393352ec053f5308f1240f", + "partial_targets/train.py": "3baca16c3945e6ef241ccbc9c13644539e3c265f71095cbbaa61a3d338e4fafe", + "patch16/convert.py": "11e1d30100ab25311020ac1f4ab8227ec66156836df5de613300867977091c45", + "patch16/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "patch16/evaluate.py": "eaea99e8cd44c9f7c70a45fa9abf51354ae5449dbad273fcb55e48ad02652223", + "patch16/model.py": "8031c597b354eb2cf464140bee40c3ec8dff86c775b5c55c5ce910302b443582", + "patch16/pack.py": "3bcc4ce9eb3361ad741ceebd7efce7a2fb86fb49543f52c72aabd0e3e8cd17ce", + "patch16/predict.py": "930a9f18f9f5da47c03859698c9d2f5567d1e1c73fd61edac1ed20b3a6f9bb50", + "patch16/publish.py": "3c167f33e8571731c26f1cb70168eda54ef9cb4c76423dfd374240b75ca5f106", + "patch16/record.py": "b3b00b0ed14bc3af00c7b1ad97195238ecb8f06e96bc41f0c07913bc3f6ed949", + "patch16/train.py": "3156710f76111a31447cbe638ee27fe2811d060917aa083aab0b5134d98accf8", + "patch16/ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "patch16/validation_subset.py": "8d3eb9d3f3aa124368761ef402ff066935c0be31a62b25b8551a45dcb922e28d", + "postloss/check_numerical_fix.py": "527dffcd94ec1a02b214dd300261d189b06c386f0b8c4d4df3320098f5fc0e68", + "postloss/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "postloss/diagnose_nonfinite.py": "82d10c5751ea1d21ecd36cd5eb54c00aabcaf78a8562b259551d028d452be47b", + "postloss/gpu_check.py": "c0a7e23d9f74cdab4fa04e1a4b9f89c64bb58f5e24228aa5e0f2cf554fef2d1f", + "postloss/launch_completion.py": "ef584b22259e3bc741b16ef876a6120bfcee08e2b9237a7990ed560a0dbf77ae", + "postloss/model.py": "d4b76fb1a63789e091b114dd947abe30be3e47c2e2e9d41cecb3e3353af86ac5", + "postloss/model_before_numerical_fix.py": "1ad846ac7adc16298b9643a79f4ee1b94f4db82fa716c6db77a2fcbb2160c261", + "postloss/restart.py": "5baa9a0947a0d30f7773113c05bd1f53b8ed1817aeaa2365078b06df9ce2fbca", + "postloss/torch_post.py": "0762fc5d330a4039798a81788e4adb8bfe206aba2aa29a1b53ecad0bd3bff217", + "recency_features/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "recency_features/model.py": "e3a1bc01e89a0d6d750ede2cc969272ad01e1ca580b174af7dee00db029f1cf7", + "recency_features/train.py": "a654b9a27b6c27141e1d4e517ab28fcae3f2c23d061742fa2f6c01e3d23c8a00", + "recovery/brief.py": "ee9ea6b8e1778f4b735cf96ef890364866d58310b4cdd9296d374c0417593ceb", + "recovery/capacity_curves.py": "2bdc6635705b70a868e115cd13eb529563acacf6f47c71f250a50dce8e943be4", + "recovery/exposure_audit.py": "54c194a626b8876ece84686b39b22360155c9fada7248a393ca9b7d6ee38002b", + "recovery/quantile_coverage.py": "7a4057d1aa38c5e7de0ca601db0003a8fd3a9a2e6123b2fdb81fa8aedbc34787", + "recovery/relaunch_20261022b.py": "f90ddd77928a793c8e151ba74cfa9cc84c8aefad0c0d943a833c74bc07b79313", + "recovery/relaunch_20261023.py": "a4c40c5674b0d05cfe9bb1fffe907f02dec16c53cbddb8b86efbba1b96649097", + "recovery/schedules.py": "7748fd6b2bbbe64037472faf7e6583d03cf339138d2f3c07b1bac9e65bf2d4f5", + "recovery/seasonal_history_support.py": "fe2da1a695715c3add9472f0bfebc946783b179b1a8415f85565a937885f7076", + "recovery/snapshot.py": "83f026b90a7dd9182da20f34bf206e6bd449b7c7ff7ea12ae2ad5e32024a5820", + "recovery/train.py": "5c486372fd12a84eee823f1a2c2de14d64bde6b7bd6adafd5e80339b9dd7a6bd", + "spectral_synth/check.py": "c308c87af0a6756fafefa460751cc370ed44ee98f3f52364b1ed6879a3c4e110", + "spectral_synth/data.py": "1780475ef9573c9731cf67f46c1a339ab2fa466c28bbbee5948322ae3f33ca29", + "spectral_synth/launch.py": "5888c115ae4b38b307ac1ac1bb4a9c200a1aa35850819dab55eaeb47946c38e2", + "spectral_synth/model.py": "44eeb23c037e91b8f67e432615ce46540a7ac4242919785f9c4218de23121499", + "spectral_synth/spectral.py": "347aa6d352df72ff18ef35a267b8e0479546263b26174d5256d4e9903cce5f71", + "spectral_transfer/run.py": "33fb544faca0633cd96440e2e4fa3c0e38c8e8cde8a215bfaf8357ed224bfcd8", + "weekly_synth/check.py": "a122b553d9ddc01a506a36713a0df478b03d7fe0b3f9ee1fa34c22c3e982adbf", + "weekly_synth/data.py": "774d0d5216fa263db9d809289dd3daa877f0bcea6ed44a628dd9f8e53829815f", + "weekly_synth/launch.py": "b28347982ecf6d87b45970824d0961027297296e8a6d4372414caeae28427e9d", + "weekly_synth/model.py": "44eeb23c037e91b8f67e432615ce46540a7ac4242919785f9c4218de23121499" + } +} diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/confidence_query/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/confidence_query/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/confidence_query/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/confidence_query/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/confidence_query/model.py new file mode 100644 index 0000000000000000000000000000000000000000..b881039b3752b3396e06415a8d01d24956fa29a7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/confidence_query/model.py @@ -0,0 +1,190 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + if self.recency is not None: + pos=torch.arange(c,device=z.device)[None,:];extras=[] + for j in range(2): + period=periods[:,j:j+1] + recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + n=ctx.shape[0] + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1]) + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/confidence_query/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/confidence_query/train.py new file mode 100644 index 0000000000000000000000000000000000000000..fd9d2a3a0502cee1a67c41c832266c7f87cc5a80 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/confidence_query/train.py @@ -0,0 +1,54 @@ +"""Train only confidence-query features on a frozen model, using paired-sign forecast loss.""" +import argparse,json,math,time,os +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) +ap.add_argument('--initialize-from',required=True);ap.add_argument('--steps',type=int,default=6000) +ap.add_argument('--batch',type=int,default=128);ap.add_argument('--lr',type=float,default=2e-4) +ap.add_argument('--seed',type=int,default=89);ap.add_argument('--save-every',type=int,default=1000);a=ap.parse_args() +torch.set_num_threads(1);torch.manual_seed(a.seed);torch.backends.cuda.matmul.allow_tf32=True +out=Path(a.out);out.mkdir(parents=True,exist_ok=True) +ck=torch.load(a.initialize_from,map_location='cpu',weights_only=False) +config={**ck['config'],'confidence_features':True};model=DirectForecaster(**config).cuda() +missing,unexpected=model.load_state_dict(ck['model'],strict=False) +assert not unexpected and all(k.startswith('confidence.') for k in missing) +for name,param in model.named_parameters():param.requires_grad_(name.startswith('confidence.')) +params=[p for p in model.parameters() if p.requires_grad] +opt=torch.optim.AdamW(params,lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) +ema={k:v.detach().clone() for k,v in model.state_dict().items()};sampler=Sampler(a.packed,seed=a.seed) +(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)) +rng=np.random.default_rng(a.seed) +def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) +def save(step): + for prefix,weights in [('step',model.state_dict()),('ema',ema)]: + state={'model':weights,'config':model.config,'step':step,'args':vars(a),'ema':prefix=='ema'} + path=out/f'{prefix}{step:06d}.pt';torch.save(state,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) +save(0);pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] +for step in range(1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch);x,y,p=[torch.from_numpy(x).cuda() for x in arrays] + lr=a.lr*min(1,step/200)*(.2+.8*.5*(1+math.cos(math.pi*step/a.steps))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(params,1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items(): + if k.startswith('confidence.'):ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + if step%a.save_every==0 or step==a.steps:save(step) +pool.shutdown() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/direct_large/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/direct_large/data.py new file mode 100644 index 0000000000000000000000000000000000000000..2378e33d7352ba5ad97d566148782e63e64b367c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/direct_large/data.py @@ -0,0 +1,71 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + return ctx,tgt,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/direct_large/evaluate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/direct_large/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..05f086d4d84def4a48165f9e65d2948877675e56 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/direct_large/evaluate.py @@ -0,0 +1,16 @@ +import sys,json,argparse,time,hashlib +from pathlib import Path +import torch +from predict import load_model,run +sys.path.insert(0,'/workspace/evaluation') +from score import score,json_safe + +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);ap.add_argument('--valid',default='/workspace/research/valid_screen');ap.add_argument('--baseline',default='/workspace/research/valid_screen/baseline.json');a=ap.parse_args() +torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cuda.matmul.allow_tf32=False +t0=time.time();out=Path(a.out);v=Path(a.valid) +run(load_model(a.weights),v/'input',out) +base=json.loads(Path(a.baseline).read_text())['configs'] +rep=score(v/'truth',out,base) +rep['checkpoint_sha256']=hashlib.sha256(Path(a.weights).read_bytes()).hexdigest();rep['eval_seconds']=time.time()-t0 +(out/'report.json').write_text(json.dumps(json_safe(rep),indent=1)) +print(json.dumps({k:rep[k] for k in ('skill_score','rel_mase_gmean','rel_wql_gmean','n_failed','groups','eval_seconds')},indent=1)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/direct_large/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/direct_large/model.py new file mode 100644 index 0000000000000000000000000000000000000000..7a224cc12a159446a1e427b2052b53d1d1f7e83e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/direct_large/model.py @@ -0,0 +1,142 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional(torch.arange(-nt,0,device=z.device),self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + q=self.query(base.reshape(b,h//p,p*9))+positional(torch.arange(h//p,device=z.device),self.d)[None]+emb + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + pin=torch.maximum(levels*err,(levels-1)*err).mean(-1) + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + return per.mean() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/direct_large/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/direct_large/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/direct_large/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/direct_large/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/direct_large/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..e20c6630475d6b4fa6906eb4ed9454b7b5aeec2c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/direct_large/predict.py @@ -0,0 +1,43 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):q=model.predict(x,p,h).float().cpu().numpy() + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/direct_large/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/direct_large/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf95c9aec5936076b881c340edb960786f2d40d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/direct_large/publish.py @@ -0,0 +1,31 @@ +"""Assemble a relocatable package, then atomically exchange complete directories.""" +import json,os,shutil,ctypes,hashlib,argparse +from pathlib import Path +import torch +HERE=Path(__file__).resolve().parent + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',default='/workspace/submission');ap.add_argument('--report',required=True);ap.add_argument('--experiments',default=str(HERE/'EXPERIMENTS.md'));a=ap.parse_args() + final=Path(a.out);staging=final.parent/f'.{final.name}-staging-{os.getpid()}' + shutil.rmtree(staging,ignore_errors=True);staging.mkdir(parents=True) + for file in ('model.py','predict.py','infer.sh','ts_io.py'): + shutil.copy(HERE/file,staging/file) + shutil.copy(a.weights,staging/'weights.pt');shutil.copy('/opt/runtime/requirements.txt',staging/'requirements.txt') + ck=torch.load(a.weights,map_location='cpu',weights_only=False);digest=hashlib.sha256((staging/'weights.pt').read_bytes()).hexdigest() + sources=json.loads(Path('/workspace/research/packed_sample/meta.json').read_text())['dirs'] + manifest={'name':'direct-seasonal-quantile-v1','contract':'timeseries-forecast/v1','parameters':sum(x.numel() for x in ck['model'].values()),'pretrained_assets':[],'sources_used':[f'gifteval_pretrain/{d}' for d in sources]+['synthetic:direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; data.py generator seed 17'],'weights_sha256':digest,'training_step':ck['step'],'config':ck['config'],'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.'} + (staging/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') + (staging/'config.json').write_text(json.dumps(ck['config'],indent=2)+'\n') + shutil.copy(a.experiments,staging/'EXPERIMENTS.md');shutil.copy(a.report,staging/'validation_report.json') + # Include generator/sampler provenance, which is not imported by inference. + (staging/'provenance').mkdir() + for file in ('pack.py','data.py','train.py'):shutil.copy(HERE/file,staging/'provenance'/file) + (staging/'README.md').write_text('# Direct seasonal quantile foundation forecaster\n\nRun `bash infer.sh INPUT_DIR OUTPUT_DIR`. This package contains all inference assets and uses only its supplied input directory. The 6.76M 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.\n\nThe 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.\n') + if final.exists(): + libc=ctypes.CDLL(None,use_errno=True) + if libc.renameat2(-100,os.fsencode(staging),-100,os.fsencode(final),2):raise OSError(ctypes.get_errno(),os.strerror(ctypes.get_errno())) + shutil.rmtree(staging) + else:os.replace(staging,final) + print(json.dumps(manifest,indent=1)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/direct_large/record.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/direct_large/record.py new file mode 100644 index 0000000000000000000000000000000000000000..1850a33f46fa3ee4d78cac4a5d6152404801a131 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/direct_large/record.py @@ -0,0 +1,9 @@ +import argparse,json,math +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('report');ap.add_argument('--label',required=True);ap.add_argument('--outcome',default='Screened for model selection.');a=ap.parse_args() +r=json.loads(Path(a.report).read_text());p=Path(__file__).with_name('EXPERIMENTS.md') +lines=[f'\n## {a.label}',f'- Checkpoint SHA-256: `{r.get("checkpoint_sha256","see model_manifest.json")}`.',f'- Evaluation: {r["n_configs"]} configurations, {r["n_instances"]} instances, {r["n_failed"]} failed configurations; {r.get("eval_seconds","not separately timed")} seconds.',f'- Overall skill {r["skill_score"]:.6f}; relative MASE {r["rel_mase_gmean"]:.6f}; relative WQL {r["rel_wql_gmean"]:.6f}.'] +for group,entries in r['groups'].items(): + lines.append(f'- {group} skill: '+', '.join(f'{k}={1-math.sqrt(v["rel_mase_gmean"]*v["rel_wql_gmean"]):.4f}' for k,v in entries.items())+'.') +lines.append('- Outcome: '+a.outcome) +with p.open('a') as f:f.write('\n'.join(lines)+'\n') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/direct_large/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/direct_large/train.py new file mode 100644 index 0000000000000000000000000000000000000000..a2ccc736bfef804259199a2dd315347d9854b680 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/direct_large/train.py @@ -0,0 +1,67 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(6);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/direct_large/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/direct_large/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/direct_large/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/direct_large/validation_subset.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/direct_large/validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..4df83e69c4f9a3365955e5d17ffcfc0af71372b7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/direct_large/validation_subset.py @@ -0,0 +1,18 @@ +"""Model-selection-only subset spanning all 97 configurations, seed 2026.""" +import sys,json,copy +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +import ts_io + +root=Path('/workspace/data/valid');out=Path('/workspace/research/valid_screen') +idx=json.loads((root/'input/index.json').read_text());new=copy.deepcopy(idx);rng=np.random.default_rng(2026) +for cfg in new['configs']: + cid=cfg['config_id'];case=ts_io.CaseFile(root/'input/cases'/f'{cid}.h5') + ids=np.sort(rng.choice(case.n,min(case.n,192),replace=False)) + ts_io.write_case_subset(case,ids,out/'input/cases'/f'{cid}.h5') + lab,se,meta=ts_io.read_truth_file(root/'truth/cases'/f'{cid}.h5') + ts_io.write_truth_file(out/'truth/cases'/f'{cid}.h5',lab[ids],se[ids],meta) + cfg['n_instances']=len(ids);case.close() +for kind in ('input','truth'):(out/kind/'index.json').write_text(json.dumps(new,indent=1)) +print('screen instances',sum(c['n_instances'] for c in new['configs'])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/full_paired/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/full_paired/check.py new file mode 100644 index 0000000000000000000000000000000000000000..fda928e16338305fd9912f7bc08cacff58bd8aa4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/full_paired/check.py @@ -0,0 +1,34 @@ +import importlib.util,json,time +from pathlib import Path +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +r=Path('/workspace/research');torch.set_num_threads(1);torch.manual_seed(197);start=time.monotonic() +ck=torch.load(r/'horizon_delta12k.pt',map_location='cpu',weights_only=False) +spec=importlib.util.spec_from_file_location('parent_model',r/'confidence_inference/model.py') +old=importlib.util.module_from_spec(spec);spec.loader.exec_module(old) +parent=old.DirectForecaster(**ck['config']);parent.load_state_dict(ck['model']) +m=DirectForecaster(**ck['config']);m.load_state_dict(ck['model']) +x=torch.randn(4,512);x[0,:50]=float('nan');p=torch.tensor([[24,168]]*4);y=torch.randn(4,128);y[0,32:]=float('nan') +with torch.inference_mode(): + assert all(torch.equal(a,b) for a,b in zip(m(x,p,48),parent(x,p,48))) + short=m(x,p,32)[0];long=m(x,p,128,forecast_lengths=torch.full((4,),32))[0][:,:32] + assert torch.allclose(short,long,atol=3e-6,rtol=1e-6),(short-long).abs().max() + paired=float(loss_fn(m,x,y,p,paired=True));reverse=float(loss_fn(m,-x,-y,p,paired=True)) + assert abs(paired-reverse)<1e-7,(paired,reverse) +a=Sampler(r/'packed_sample',197);b=Sampler(r/'packed_sample',197) +for c,h in [(512,32),(4096,1024)]: + assert all(np.array_equal(v,w,equal_nan=True) for v,w in zip(a.sample(16,c,h),b.sample(16,c,h))) +assert a.rng.bit_generator.state==b.rng.bit_generator.state and a.horizon_rng.bit_generator.state==b.horizon_rng.bit_generator.state +cpu=time.monotonic()-start;del parent,ck,a,b +m=m.cuda();ema={k:v.detach().clone() for k,v in m.state_dict().items()} +moments=[torch.zeros_like(v) for v in m.parameters() for _ in range(2)] +torch.backends.cuda.matmul.allow_tf32=True;torch.cuda.reset_peak_memory_stats();start=time.monotonic() +x=torch.randn(64,4096,device='cuda');y=torch.randn(64,1024,device='cuda');p=torch.tensor([[24,168]]*64,device='cuda') +with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(m,x,y,p,paired=True) +loss.backward();torch.cuda.synchronize() +assert torch.isfinite(loss) and all(v.grad is not None and torch.isfinite(v.grad).all() for v in m.parameters()) +z={'cpu_seconds':cpu,'initial_forecast_bitwise_parent':True,'unused_future_tokens_do_not_change_requested_prefix':True,'paired_loss_sign_symmetric':True,'matched_sampler_main_and_horizon_rng':True,'gpu_fixture_seconds':time.monotonic()-start,'allocated_mib':torch.cuda.max_memory_allocated()/2**20,'reserved_mib':torch.cuda.max_memory_reserved()/2**20,'optimizer_updates':0} +(r/'full_paired_checks.json').write_text(json.dumps(z,indent=2));print(json.dumps(z),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/full_paired/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/full_paired/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/full_paired/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/full_paired/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/full_paired/model.py new file mode 100644 index 0000000000000000000000000000000000000000..dedcdff4698028a8ba655865f8425d0dc3ef0dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/full_paired/model.py @@ -0,0 +1,204 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/horizon_jitter/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/horizon_jitter/data.py new file mode 100644 index 0000000000000000000000000000000000000000..3d632af7e96a71f30b7964a2b3fd73bc1c3f3f3e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/horizon_jitter/data.py @@ -0,0 +1,86 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/horizon_jitter/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/horizon_jitter/model.py new file mode 100644 index 0000000000000000000000000000000000000000..4ffe50d9aadf21d73949e2052ceb7f3642bf65d3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/horizon_jitter/model.py @@ -0,0 +1,180 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(ctx,periods,target.shape[-1],forecast_lengths=lengths) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/horizon_jitter/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/horizon_jitter/train.py new file mode 100644 index 0000000000000000000000000000000000000000..768d33da4421b24bd760d7d9680d0c2cd9bd84e4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/horizon_jitter/train.py @@ -0,0 +1,74 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler,truncate_targets + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + horizon_rng=np.random.default_rng(a.seed+startstep+300003) + def nextbatch(): + 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])) + return truncate_targets(sampler.sample(a.batch,c,h),horizon_rng,a.patch) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_corpus/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_corpus/data.py new file mode 100644 index 0000000000000000000000000000000000000000..a51e912d3c4b63a3ec0cd85133bf0e7aa3429569 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_corpus/data.py @@ -0,0 +1,73 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_corpus/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_corpus/model.py new file mode 100644 index 0000000000000000000000000000000000000000..f8271c5b0bf9a5edb961e1c7839761fe50a2e40b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_corpus/model.py @@ -0,0 +1,171 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024,recency_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + if self.recency is not None: + pos=torch.arange(c,device=z.device)[None,:];extras=[] + for j in range(2): + period=periods[:,j:j+1] + recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_corpus/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_corpus/train.py new file mode 100644 index 0000000000000000000000000000000000000000..2e77612e443d78dd80bcb6a0cc6d01169f61a3a4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_corpus/train.py @@ -0,0 +1,73 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_sign/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_sign/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_sign/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_sign/evaluate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_sign/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..05f086d4d84def4a48165f9e65d2948877675e56 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_sign/evaluate.py @@ -0,0 +1,16 @@ +import sys,json,argparse,time,hashlib +from pathlib import Path +import torch +from predict import load_model,run +sys.path.insert(0,'/workspace/evaluation') +from score import score,json_safe + +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);ap.add_argument('--valid',default='/workspace/research/valid_screen');ap.add_argument('--baseline',default='/workspace/research/valid_screen/baseline.json');a=ap.parse_args() +torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cuda.matmul.allow_tf32=False +t0=time.time();out=Path(a.out);v=Path(a.valid) +run(load_model(a.weights),v/'input',out) +base=json.loads(Path(a.baseline).read_text())['configs'] +rep=score(v/'truth',out,base) +rep['checkpoint_sha256']=hashlib.sha256(Path(a.weights).read_bytes()).hexdigest();rep['eval_seconds']=time.time()-t0 +(out/'report.json').write_text(json.dumps(json_safe(rep),indent=1)) +print(json.dumps({k:rep[k] for k in ('skill_score','rel_mase_gmean','rel_wql_gmean','n_failed','groups','eval_seconds')},indent=1)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_sign/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_sign/model.py new file mode 100644 index 0000000000000000000000000000000000000000..60aeb14b5f4fa298521ddce8a3276d076c1bb631 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_sign/model.py @@ -0,0 +1,154 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional(torch.arange(-nt,0,device=z.device),self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + q=self.query(base.reshape(b,h//p,p*9))+positional(torch.arange(h//p,device=z.device),self.d)[None]+emb + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_sign/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_sign/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_sign/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_sign/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_sign/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..e20c6630475d6b4fa6906eb4ed9454b7b5aeec2c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_sign/predict.py @@ -0,0 +1,43 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):q=model.predict(x,p,h).float().cpu().numpy() + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_sign/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_sign/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf95c9aec5936076b881c340edb960786f2d40d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_sign/publish.py @@ -0,0 +1,31 @@ +"""Assemble a relocatable package, then atomically exchange complete directories.""" +import json,os,shutil,ctypes,hashlib,argparse +from pathlib import Path +import torch +HERE=Path(__file__).resolve().parent + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',default='/workspace/submission');ap.add_argument('--report',required=True);ap.add_argument('--experiments',default=str(HERE/'EXPERIMENTS.md'));a=ap.parse_args() + final=Path(a.out);staging=final.parent/f'.{final.name}-staging-{os.getpid()}' + shutil.rmtree(staging,ignore_errors=True);staging.mkdir(parents=True) + for file in ('model.py','predict.py','infer.sh','ts_io.py'): + shutil.copy(HERE/file,staging/file) + shutil.copy(a.weights,staging/'weights.pt');shutil.copy('/opt/runtime/requirements.txt',staging/'requirements.txt') + ck=torch.load(a.weights,map_location='cpu',weights_only=False);digest=hashlib.sha256((staging/'weights.pt').read_bytes()).hexdigest() + sources=json.loads(Path('/workspace/research/packed_sample/meta.json').read_text())['dirs'] + manifest={'name':'direct-seasonal-quantile-v1','contract':'timeseries-forecast/v1','parameters':sum(x.numel() for x in ck['model'].values()),'pretrained_assets':[],'sources_used':[f'gifteval_pretrain/{d}' for d in sources]+['synthetic:direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; data.py generator seed 17'],'weights_sha256':digest,'training_step':ck['step'],'config':ck['config'],'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.'} + (staging/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') + (staging/'config.json').write_text(json.dumps(ck['config'],indent=2)+'\n') + shutil.copy(a.experiments,staging/'EXPERIMENTS.md');shutil.copy(a.report,staging/'validation_report.json') + # Include generator/sampler provenance, which is not imported by inference. + (staging/'provenance').mkdir() + for file in ('pack.py','data.py','train.py'):shutil.copy(HERE/file,staging/'provenance'/file) + (staging/'README.md').write_text('# Direct seasonal quantile foundation forecaster\n\nRun `bash infer.sh INPUT_DIR OUTPUT_DIR`. This package contains all inference assets and uses only its supplied input directory. The 6.76M 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.\n\nThe 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.\n') + if final.exists(): + libc=ctypes.CDLL(None,use_errno=True) + if libc.renameat2(-100,os.fsencode(staging),-100,os.fsencode(final),2):raise OSError(ctypes.get_errno(),os.strerror(ctypes.get_errno())) + shutil.rmtree(staging) + else:os.replace(staging,final) + print(json.dumps(manifest,indent=1)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_sign/record.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_sign/record.py new file mode 100644 index 0000000000000000000000000000000000000000..1850a33f46fa3ee4d78cac4a5d6152404801a131 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_sign/record.py @@ -0,0 +1,9 @@ +import argparse,json,math +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('report');ap.add_argument('--label',required=True);ap.add_argument('--outcome',default='Screened for model selection.');a=ap.parse_args() +r=json.loads(Path(a.report).read_text());p=Path(__file__).with_name('EXPERIMENTS.md') +lines=[f'\n## {a.label}',f'- Checkpoint SHA-256: `{r.get("checkpoint_sha256","see model_manifest.json")}`.',f'- Evaluation: {r["n_configs"]} configurations, {r["n_instances"]} instances, {r["n_failed"]} failed configurations; {r.get("eval_seconds","not separately timed")} seconds.',f'- Overall skill {r["skill_score"]:.6f}; relative MASE {r["rel_mase_gmean"]:.6f}; relative WQL {r["rel_wql_gmean"]:.6f}.'] +for group,entries in r['groups'].items(): + lines.append(f'- {group} skill: '+', '.join(f'{k}={1-math.sqrt(v["rel_mase_gmean"]*v["rel_wql_gmean"]):.4f}' for k,v in entries.items())+'.') +lines.append('- Outcome: '+a.outcome) +with p.open('a') as f:f.write('\n'.join(lines)+'\n') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_sign/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_sign/train.py new file mode 100644 index 0000000000000000000000000000000000000000..d089166fb1612ddf4955fcd2f096cb0b33624dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_sign/train.py @@ -0,0 +1,70 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(3);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_sign/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_sign/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_sign/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_sign/validation_subset.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_sign/validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..4df83e69c4f9a3365955e5d17ffcfc0af71372b7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/large_sign/validation_subset.py @@ -0,0 +1,18 @@ +"""Model-selection-only subset spanning all 97 configurations, seed 2026.""" +import sys,json,copy +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +import ts_io + +root=Path('/workspace/data/valid');out=Path('/workspace/research/valid_screen') +idx=json.loads((root/'input/index.json').read_text());new=copy.deepcopy(idx);rng=np.random.default_rng(2026) +for cfg in new['configs']: + cid=cfg['config_id'];case=ts_io.CaseFile(root/'input/cases'/f'{cid}.h5') + ids=np.sort(rng.choice(case.n,min(case.n,192),replace=False)) + ts_io.write_case_subset(case,ids,out/'input/cases'/f'{cid}.h5') + lab,se,meta=ts_io.read_truth_file(root/'truth/cases'/f'{cid}.h5') + ts_io.write_truth_file(out/'truth/cases'/f'{cid}.h5',lab[ids],se[ids],meta) + cfg['n_instances']=len(ids);case.close() +for kind in ('input','truth'):(out/kind/'index.json').write_text(json.dumps(new,indent=1)) +print('screen instances',sum(c['n_instances'] for c in new['configs'])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/long_memory_synth/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/long_memory_synth/data.py new file mode 100644 index 0000000000000000000000000000000000000000..95410ba700e638fc2e1375b14dece4df57c10110 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/long_memory_synth/data.py @@ -0,0 +1,73 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=np.exp(-10**(-r.uniform(0,4)));noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/long_memory_synth/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/long_memory_synth/model.py new file mode 100644 index 0000000000000000000000000000000000000000..4ffe50d9aadf21d73949e2052ceb7f3642bf65d3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/long_memory_synth/model.py @@ -0,0 +1,180 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(ctx,periods,target.shape[-1],forecast_lengths=lengths) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/long_memory_synth/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/long_memory_synth/train.py new file mode 100644 index 0000000000000000000000000000000000000000..61de733eea03837247278d9010c2ed8b955d7359 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/long_memory_synth/train.py @@ -0,0 +1,74 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + a.synthetic_ar_time_constants=[1,10000] + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/long_seasonal/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/long_seasonal/check.py new file mode 100644 index 0000000000000000000000000000000000000000..beba62576fae73576eef907b81c674e96622670d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/long_seasonal/check.py @@ -0,0 +1,145 @@ +"""Check exact initialization, fixed feature arithmetic and allowed-data gradients.""" +import argparse +import hashlib +import importlib.util +import json +import sys +import time +from pathlib import Path + +import numpy as np +import torch + +R = Path('/workspace/research') +sys.path.insert(0, str(R / 'long_seasonal')) +from model import DirectForecaster, centered_seasonal_difference, loss_fn +from data import Sampler + +ap = argparse.ArgumentParser() +ap.add_argument('--gpu', action='store_true') +a = ap.parse_args() +torch.set_num_threads(2) +torch.manual_seed(503) +started = time.monotonic() +spec = importlib.util.spec_from_file_location('long_control_model', R / 'overflow_control/model.py') +control_code = importlib.util.module_from_spec(spec) +spec.loader.exec_module(control_code) +parent_path = R / 'horizon_delta12k.pt' +parent = torch.load(parent_path, map_location='cpu', weights_only=False) +config = dict(parent['config'], long_seasonal_features=True) +candidate = DirectForecaster(**config) +missing, unexpected = candidate.load_state_dict(parent['model'], strict=False) +assert set(missing) == {'long_query.weight', 'long_head.weight', 'long_head.bias'} +assert not unexpected +assert all(torch.count_nonzero(candidate.state_dict()[key]) == 0 for key in missing) +control = control_code.DirectForecaster(**parent['config']) +control.load_state_dict(parent['model']) +assert all(torch.equal(value, candidate.state_dict()[key]) for key, value in parent['model'].items()) + +if a.gpu: + import fcntl + lock = open(R / '.evaluation.lock', 'a') + fcntl.flock(lock, fcntl.LOCK_EX) + device = 'cuda' + torch.backends.cuda.matmul.allow_tf32 = False + candidate = candidate.cuda() + control = control.cuda() + rng = np.random.default_rng(509) + x = torch.tensor(rng.normal(size=(8, 512)).astype(np.float32), device=device) + x[0, :23] = float('nan') + x[1] = 0 + p = torch.tensor([[24,168],[7,365],[12,1],[52,1],[4,1],[1,1],[96,672],[2,14]], device=device) + with torch.inference_mode(), torch.autocast('cuda', dtype=torch.bfloat16): + expected = control(x, p, 128) + actual = candidate(x, p, 128) + assert all(torch.equal(v, w) for v, w in zip(expected, actual)) + del control, expected, actual, x, p + torch.cuda.empty_cache() + torch.cuda.reset_peak_memory_stats() + sampler = Sampler(R / 'packed_sample', seed=509, source_weights_from=R / 'packed_sample') + arrays = sampler.sample(64, 4096, 1024) + tensors = [torch.from_numpy(v).cuda() for v in arrays] + placeholders = [torch.zeros_like(v) for v in candidate.parameters() for _ in range(3)] + with torch.autocast('cuda', dtype=torch.bfloat16): + loss = loss_fn(candidate, *tensors, paired=True) + loss.backward() + assert torch.isfinite(loss) + assert all(v.grad is None or torch.isfinite(v.grad).all() for v in candidate.parameters()) + gradients = {key: float(dict(candidate.named_parameters())[key].grad.norm()) for key in missing} + assert gradients['long_head.weight'] > 0 and gradients['long_query.weight'] > 0 + result = dict(seed=509, gpu_initial_function_bitwise_equal=True, + max_shape=[64,4096,1024], loss=float(loss.detach()), added_gradient_norms=gradients, + reserved_mib=torch.cuda.max_memory_reserved()/2**20, + allocated_mib=torch.cuda.max_memory_allocated()/2**20, + includes_ema_and_adam_placeholders=True, seconds=time.monotonic()-started, + optimizer_updates=0, validation_data_read=False) + (R / 'long_seasonal_gpu_checks.json').write_text(json.dumps(result, indent=2)) + print(json.dumps(result)) + raise SystemExit() + +rng = np.random.default_rng(503) +z = rng.normal(size=(4, 96)).astype(np.float32) +valid = rng.random(z.shape) > .12 +z[~valid] = 0 +periods = np.array([[4,7],[2,3],[12,1],[24,168]], dtype=np.int64) +delta, extra = centered_seasonal_difference(torch.from_numpy(z), torch.from_numpy(valid), + torch.from_numpy(periods), 23) +expected = np.zeros((4,23,2), np.float32) +support = np.zeros_like(expected) +for row in range(4): + for j in range(2): + period = int(periods[row,j]) + for t in range(23): + observations, recent = [], [] + for cycle in range(16): + end = max(0, 96-cycle*period) + start = max(0, 96-(cycle+1)*period) + index = 96-period+t%period-cycle*period + if index < 0 or not valid[row,index]: + continue + mean = z[row,start:end][valid[row,start:end]].mean(dtype=np.float64) + value = float(z[row,index])-mean + observations.append(value) + if cycle < 4: + recent.append(value) + if period>=2 and len(observations)>=8 and len(recent)>=2: + expected[row,t,j] = np.mean(observations)-np.mean(recent) + support[row,t,j] = len(observations)/16 +assert np.max(np.abs(delta.numpy()-expected)) < 1e-6 +assert np.array_equal(extra.numpy()[:,:,[1,3]], support) +# Adding a different constant to each complete cycle leaves centered templates unchanged. +z0 = torch.tensor(rng.normal(size=(1,64)).astype(np.float32)) +offsets = torch.tensor(rng.normal(size=(1,16,1)).astype(np.float32)) +z1 = (z0.view(1,16,4)+offsets).view(1,64) +p = torch.tensor([[4,4]]) +ones = torch.ones_like(z0,dtype=torch.bool) +v0 = centered_seasonal_difference(z0,ones,p,16)[0] +v1 = centered_seasonal_difference(z1,ones,p,16)[0] +assert torch.max(torch.abs(v0-v1)) < 1e-6 +for c,h in [(32,6),(96,23),(512,128)]: + ctx = torch.tensor(rng.normal(size=(4,c)).astype(np.float32)) + ctx[0,:c//3] = float('nan') + ctx[1] = 0 + ctx[2] = float('nan') + with torch.inference_mode(): + expected = control(ctx,torch.from_numpy(periods),h) + actual = candidate(ctx,torch.from_numpy(periods),h) + assert all(torch.equal(v,w) for v,w in zip(expected,actual)) +assert (R/'long_seasonal/data.py').read_bytes()==(R/'overflow_control/data.py').read_bytes() +out = R / 'long_seasonal_initial.pt' +assert not out.exists(), 'Do not overwrite an existing declared initial checkpoint' +checkpoint = dict(model=candidate.state_dict(), config=config, step=0, + args=dict(packed=str(R/'packed_sample'), seed=503), + parent_checkpoints=[str(parent_path)], + conversion=dict(method='zero-initialized sixteen-cycle centered seasonal query/head additions', + parent_sha256=hashlib.sha256(parent_path.read_bytes()).hexdigest(), + initial_function_bitwise_equal=True)) +torch.save(checkpoint,out) +result = dict(seed=503, independent_feature_arithmetic=True, centered_cycle_offset_invariance=True, + initial_function_bitwise_equal=True, inherited_weights_bitwise_equal=True, + sampler_byte_identical=True, added_parameters=sum(candidate.state_dict()[k].numel() for k in missing), + total_parameters=sum(v.numel() for v in candidate.parameters()), + checkpoint_sha256=hashlib.sha256(out.read_bytes()).hexdigest(), + seconds=time.monotonic()-started, optimizer_updates=0, validation_data_read=False) +(R/'long_seasonal_checks.json').write_text(json.dumps(result,indent=2)) +print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/long_seasonal/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/long_seasonal/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/long_seasonal/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/long_seasonal/launch.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/long_seasonal/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..d7fd732aae9def625f17a4d15dd2dbe3f4cd9317 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/long_seasonal/launch.py @@ -0,0 +1,31 @@ +"""Queue the audited learned sixteen-cycle summary after nested-volume training.""" +def main(): + import json + import os + import subprocess + from pathlib import Path + R=Path('/workspace/research') + checks=json.loads((R/'long_seasonal_checks.json').read_text()) + assert checks['initial_function_bitwise_equal'] and checks['inherited_weights_bitwise_equal'] + assert checks['independent_feature_arithmetic'] and checks['sampler_byte_identical'] + gpu=json.loads((R/'long_seasonal_gpu_checks.json').read_text()) + assert gpu['gpu_initial_function_bitwise_equal'] and gpu['reserved_mib']<10000 + env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1') + command=['python3',str(R/'recovery/train.py'),'--code-dir',str(R/'long_seasonal'), + '--packed',str(R/'packed_sample'),'--source-weights-from',str(R/'packed_sample'), + '--out',str(R/'runs/long_seasonal'),'--initialize-from',str(R/'long_seasonal_initial.pt'), + '--steps','12000','--batch','64','--lr','.00002','--seed','197','--loss-mode','paired', + '--stop-file',str(R/'long_seasonal.stop')] + with (R/'long_seasonal_queue.log').open('w') as qlog,(R/'long_seasonal_watch.log').open('w') as wlog: + queued=subprocess.Popen(['python3',str(R/'queued_train.py'),'--label','E107 learned sixteen-cycle summary seed197', + '--log',str(R/'long_seasonal_train.log'),'--receipt',str(R/'long_seasonal_queue.json'), + '--wait-pid','13470','--require-checkpoint',str(R/'runs/stratified_volume/recovery.pt'), + '--',*command],stdout=qlog,stderr=subprocess.STDOUT,env=env) + watch=subprocess.Popen(['python3',str(R/'watch_evaluate.py'),'--run',str(R/'runs/long_seasonal'), + '--evaluator',str(R/'long_seasonal_inference/evaluate.py'),'--name','long_seasonal', + '--expected-packed',str(R/'packed_sample'),'--steps','1000,3000,6000,12000'],stdout=wlog,stderr=subprocess.STDOUT,env=env) + print({'queue_pid':queued.pid,'watch_pid':watch.pid},flush=True) + result=queued.wait() + if result:watch.terminate() + watch.wait();raise SystemExit(result) +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/long_seasonal/long_features.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/long_seasonal/long_features.py new file mode 100644 index 0000000000000000000000000000000000000000..efc6e3ba327c6016d844148fcfcc29ac63863f23 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/long_seasonal/long_features.py @@ -0,0 +1,37 @@ +"""Fixed within-context phase summaries; no estimated or adapted parameters.""" +import torch +from torch.nn import functional as F + + +def centered_seasonal_difference(z, valid, periods, horizon): + b, c = z.shape + time = torch.arange(horizon, device=z.device)[None, :] + sums = F.pad((z * valid).cumsum(-1), (1, 0)) + counts = F.pad(valid.float().cumsum(-1), (1, 0)) + deltas, extras = [], [] + for j in range(2): + period = periods[:, j:j+1].clamp(min=1) + anchor = c - period + time % period + centered, masks = [], [] + for cycle in range(16): + end = (c - cycle * period).clamp(min=0, max=c) + start = (c - (cycle + 1) * period).clamp(min=0, max=c) + count = counts.gather(1, end) - counts.gather(1, start) + mean = (sums.gather(1, end) - sums.gather(1, start)) / count.clamp(min=1) + index = anchor - cycle * period + safe = index.clamp(min=0, max=c-1) + present = (index >= 0) & valid.gather(1, safe) + centered.append(z.gather(1, safe) - mean) + masks.append(present) + values = torch.stack(centered) + seen = torch.stack(masks) + n4 = seen[:4].sum(0) + n16 = seen.sum(0) + mean4 = (values[:4] * seen[:4]).sum(0) / n4.clamp(min=1) + mean16 = (values * seen).sum(0) / n16.clamp(min=1) + active = (period >= 2) & (n4 >= 2) & (n16 >= 8) + delta = torch.where(active, mean16 - mean4, 0.) + support = torch.where(active, n16.float() / 16, 0.) + deltas.append(delta) + extras.extend([delta, support]) + return torch.stack(deltas, -1), torch.stack(extras, -1) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/long_seasonal/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/long_seasonal/model.py new file mode 100644 index 0000000000000000000000000000000000000000..298ee3b840cbc8b7da585ee5e47a3822d06717b0 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/long_seasonal/model.py @@ -0,0 +1,260 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + + +def centered_seasonal_difference(z, valid, periods, horizon): + b, c = z.shape + time = torch.arange(horizon, device=z.device)[None, :] + sums = F.pad((z * valid).cumsum(-1), (1, 0)) + counts = F.pad(valid.float().cumsum(-1), (1, 0)) + deltas, extras = [], [] + for j in range(2): + period = periods[:, j:j+1].clamp(min=1) + anchor = c - period + time % period + centered, masks = [], [] + for cycle in range(16): + end = (c - cycle * period).clamp(min=0, max=c) + start = (c - (cycle + 1) * period).clamp(min=0, max=c) + count = counts.gather(1, end) - counts.gather(1, start) + mean = (sums.gather(1, end) - sums.gather(1, start)) / count.clamp(min=1) + index = anchor - cycle * period + safe = index.clamp(min=0, max=c-1) + present = (index >= 0) & valid.gather(1, safe) + centered.append(z.gather(1, safe) - mean) + masks.append(present) + values = torch.stack(centered) + seen = torch.stack(masks) + n4 = seen[:4].sum(0) + n16 = seen.sum(0) + mean4 = (values[:4] * seen[:4]).sum(0) / n4.clamp(min=1) + mean16 = (values * seen).sum(0) / n16.clamp(min=1) + active = (period >= 2) & (n4 >= 2) & (n16 >= 8) + delta = torch.where(active, mean16 - mean4, 0.) + support = torch.where(active, n16.float() / 16, 0.) + deltas.append(delta) + extras.extend([delta, support]) + return torch.stack(deltas, -1), torch.stack(extras, -1) + + + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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,long_seasonal_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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,long_seasonal_features=long_seasonal_features) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + self.long_query=nn.Linear(patch*4,d,bias=False) if long_seasonal_features else None + self.long_head=nn.Linear(d,patch*2) if long_seasonal_features else None + if long_seasonal_features: + nn.init.zeros_(self.long_query.weight) + nn.init.zeros_(self.long_head.weight);nn.init.zeros_(self.long_head.bias) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + if self.long_query is not None:long_delta,long_extra=centered_seasonal_difference(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + hidden=self.norm(q) + out=self.head(hidden).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + if self.long_head is not None: + gates=self.long_head(hidden).view(b,h,2).float().tanh() + median=median+(gates*long_delta).sum(-1) + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/long_seasonal/transfer.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/long_seasonal/transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..c20a4df852f5b150e634ae2c06510d01c7ea18b3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/long_seasonal/transfer.py @@ -0,0 +1,73 @@ +"""Apply one matched feature-learning difference with explicit zero-extension semantics.""" +import argparse +import hashlib +import importlib.util +import json +import sys +import time +from pathlib import Path + +import numpy as np +import torch + +R = Path('/workspace/research') +parser = argparse.ArgumentParser() +for key in ['base','candidate','control','out']: + parser.add_argument('--'+key,required=True) +args = parser.parse_args() +torch.set_num_threads(2) +torch.manual_seed(571) +started = time.monotonic() +paths = [Path(args.base),Path(args.candidate),Path(args.control)] +base,candidate,control = [torch.load(p,map_location='cpu',weights_only=False) for p in paths] +extra = {'long_query.weight','long_head.weight','long_head.bias'} +assert set(base['model'])==set(control['model']) +assert set(candidate['model'])==set(base['model'])|extra +config = dict(candidate['config']) +assert config.pop('long_seasonal_features') is True +assert config==base['config']==control['config'] +sys.path.insert(0,str(R/'long_seasonal')) +from model import DirectForecaster +extended = DirectForecaster(**candidate['config']) +missing,unexpected = extended.load_state_dict(base['model'],strict=False) +assert set(missing)==extra and not unexpected +assert all(torch.count_nonzero(extended.state_dict()[k])==0 for k in extra) +spec = importlib.util.spec_from_file_location('transfer_original_model',R/'overflow_control/model.py') +code = importlib.util.module_from_spec(spec) +spec.loader.exec_module(code) +original = code.DirectForecaster(**base['config']) +original.load_state_dict(base['model']) +rng = np.random.default_rng(571) +periods = torch.tensor([[24,168],[7,365],[52,1],[1,1]]) +for c,h in [(32,6),(512,128)]: + ctx = torch.tensor(rng.normal(size=(4,c)).astype(np.float32)) + ctx[0,:c//3] = float('nan') + ctx[1] = 0 + ctx[2] = float('nan') + with torch.inference_mode(): + a = original(ctx,periods,h) + b = extended(ctx,periods,h) + assert all(torch.equal(v,w) for v,w in zip(a,b)) +weights = {k:v.clone() for k,v in extended.state_dict().items()} +for k in weights: + if k in extra: + weights[k].copy_(candidate['model'][k]) + else: + assert weights[k].shape==candidate['model'][k].shape==control['model'][k].shape + weights[k].add_(candidate['model'][k]-control['model'][k]) +assert all(torch.isfinite(v).all() for v in weights.values()) +out = Path(args.out) +assert not out.exists(),'Refuse to overwrite a declared fixed candidate' +conversion = dict(method='matched training delta after zero extension of new seasonal query/head parameters', + formula='extend_zero(base) + candidate - extend_zero(control)',coefficient=1.0, + new_parameters_from_candidate=sorted(extra), + parent_hashes={str(p):hashlib.sha256(p.read_bytes()).hexdigest() for p in paths}, + base_extension_forward_bitwise_equal=True,check_seed=571, + seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False) +checkpoint = dict(model=weights,config=candidate['config'],step=0,args={'packed':base['args']['packed']}, + parent_checkpoints=[str(p) for p in paths],conversion=conversion) +torch.save(checkpoint,out) +result = dict(conversion,checkpoint_sha256=hashlib.sha256(out.read_bytes()).hexdigest(), + parameters=sum(v.numel() for v in weights.values())) +out.with_suffix('.json').write_text(json.dumps(result,indent=2)) +print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/overflow_control/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/overflow_control/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/overflow_control/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/overflow_control/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/overflow_control/model.py new file mode 100644 index 0000000000000000000000000000000000000000..3532e5063bd8b5013f6b6e35703707ffef66e00b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/overflow_control/model.py @@ -0,0 +1,213 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/partial_delta/merge.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/partial_delta/merge.py new file mode 100644 index 0000000000000000000000000000000000000000..3dde47d52d25ed2b013942b3887f1bf686e42ed8 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/partial_delta/merge.py @@ -0,0 +1,16 @@ +"""Apply the difference of two matched, locally trained checkpoints to our selected model.""" +import argparse,torch,hashlib,json,time +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('--base',required=True);ap.add_argument('--candidate',required=True);ap.add_argument('--control',required=True);ap.add_argument('--out',required=True);a=ap.parse_args() +torch.set_num_threads(1);start=time.monotonic() +base=torch.load(a.base,map_location='cpu',weights_only=False);candidate=torch.load(a.candidate,map_location='cpu',weights_only=False);control=torch.load(a.control,map_location='cpu',weights_only=False) +assert set(candidate['model'])==set(control['model']) +weights={k:v.clone() for k,v in base['model'].items()} +for k in candidate['model']: + assert k in weights and weights[k].shape==candidate['model'][k].shape==control['model'][k].shape + weights[k].add_(candidate['model'][k]-control['model'][k]) +assert all(torch.isfinite(v).all() for v in weights.values()) +parents=[a.base,a.candidate,a.control] +conversion={'method':'matched training delta','formula':'base + candidate - control','coefficient':1.0,'parent_hashes':{p:hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in parents},'seconds':time.monotonic()-start} +ck={'model':weights,'config':base['config'],'step':0,'args':{'packed':base['args']['packed']},'parent_checkpoints':parents,'conversion':conversion} +torch.save(ck,a.out);print(json.dumps(conversion)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/partial_targets/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/partial_targets/data.py new file mode 100644 index 0000000000000000000000000000000000000000..a51e912d3c4b63a3ec0cd85133bf0e7aa3429569 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/partial_targets/data.py @@ -0,0 +1,73 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/partial_targets/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/partial_targets/model.py new file mode 100644 index 0000000000000000000000000000000000000000..4ffe50d9aadf21d73949e2052ceb7f3642bf65d3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/partial_targets/model.py @@ -0,0 +1,180 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(ctx,periods,target.shape[-1],forecast_lengths=lengths) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/partial_targets/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/partial_targets/train.py new file mode 100644 index 0000000000000000000000000000000000000000..2e77612e443d78dd80bcb6a0cc6d01169f61a3a4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/partial_targets/train.py @@ -0,0 +1,73 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/convert.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/convert.py new file mode 100644 index 0000000000000000000000000000000000000000..b2cbc8fc919be6a77eca9ab19c4faa06060a2e0d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/convert.py @@ -0,0 +1,18 @@ +"""Convert only our own trained checkpoint from 32- to 16-point patches. + +Context/query projections fold the two halves by summation, preserving the +embedding of constant features. The output projection keeps the first half. +Attention/MLP weights are inherited unchanged; position units remain 32 points. +""" +import argparse,torch,hashlib +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('--input',required=True);ap.add_argument('--output',required=True);a=ap.parse_args() +ck=torch.load(a.input,map_location='cpu',weights_only=False);state=ck['model'];d=ck['config']['d'];assert ck['config']['patch']==32 +old=state['embed.0.weight'].reshape(d,2,32);state['embed.0.weight']=(old[:,:,:16]+old[:,:,16:]).reshape(d,32) +old=state['query.0.weight'].reshape(d,32,9);state['query.0.weight']=(old[:,:16]+old[:,16:]).reshape(d,16*9) +state['head.weight']=state['head.weight'].reshape(32,18,d)[:16].reshape(16*18,d).clone() +state['head.bias']=state['head.bias'].reshape(32,18)[:16].reshape(16*18).clone() +ck['config']['patch']=16 +ck['conversion']={'from_checkpoint':str(Path(a.input).resolve()),'from_sha256':hashlib.sha256(Path(a.input).read_bytes()).hexdigest(),'method':'fold input/query halves by summation; retain first 16 output rows; preserve physical positional units'} +ck['args']={**ck['args'],'initialize_from':str(Path(a.input).resolve()),'converted':True} +torch.save(ck,a.output) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/evaluate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..05f086d4d84def4a48165f9e65d2948877675e56 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/evaluate.py @@ -0,0 +1,16 @@ +import sys,json,argparse,time,hashlib +from pathlib import Path +import torch +from predict import load_model,run +sys.path.insert(0,'/workspace/evaluation') +from score import score,json_safe + +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);ap.add_argument('--valid',default='/workspace/research/valid_screen');ap.add_argument('--baseline',default='/workspace/research/valid_screen/baseline.json');a=ap.parse_args() +torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cuda.matmul.allow_tf32=False +t0=time.time();out=Path(a.out);v=Path(a.valid) +run(load_model(a.weights),v/'input',out) +base=json.loads(Path(a.baseline).read_text())['configs'] +rep=score(v/'truth',out,base) +rep['checkpoint_sha256']=hashlib.sha256(Path(a.weights).read_bytes()).hexdigest();rep['eval_seconds']=time.time()-t0 +(out/'report.json').write_text(json.dumps(json_safe(rep),indent=1)) +print(json.dumps({k:rep[k] for k in ('skill_score','rel_mase_gmean','rel_wql_gmean','n_failed','groups','eval_seconds')},indent=1)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/model.py new file mode 100644 index 0000000000000000000000000000000000000000..06cce56e2ce671b6683f0246900abfcac06bb3c0 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/model.py @@ -0,0 +1,154 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..e20c6630475d6b4fa6906eb4ed9454b7b5aeec2c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/predict.py @@ -0,0 +1,43 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):q=model.predict(x,p,h).float().cpu().numpy() + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf95c9aec5936076b881c340edb960786f2d40d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/publish.py @@ -0,0 +1,31 @@ +"""Assemble a relocatable package, then atomically exchange complete directories.""" +import json,os,shutil,ctypes,hashlib,argparse +from pathlib import Path +import torch +HERE=Path(__file__).resolve().parent + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',default='/workspace/submission');ap.add_argument('--report',required=True);ap.add_argument('--experiments',default=str(HERE/'EXPERIMENTS.md'));a=ap.parse_args() + final=Path(a.out);staging=final.parent/f'.{final.name}-staging-{os.getpid()}' + shutil.rmtree(staging,ignore_errors=True);staging.mkdir(parents=True) + for file in ('model.py','predict.py','infer.sh','ts_io.py'): + shutil.copy(HERE/file,staging/file) + shutil.copy(a.weights,staging/'weights.pt');shutil.copy('/opt/runtime/requirements.txt',staging/'requirements.txt') + ck=torch.load(a.weights,map_location='cpu',weights_only=False);digest=hashlib.sha256((staging/'weights.pt').read_bytes()).hexdigest() + sources=json.loads(Path('/workspace/research/packed_sample/meta.json').read_text())['dirs'] + manifest={'name':'direct-seasonal-quantile-v1','contract':'timeseries-forecast/v1','parameters':sum(x.numel() for x in ck['model'].values()),'pretrained_assets':[],'sources_used':[f'gifteval_pretrain/{d}' for d in sources]+['synthetic:direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; data.py generator seed 17'],'weights_sha256':digest,'training_step':ck['step'],'config':ck['config'],'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.'} + (staging/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') + (staging/'config.json').write_text(json.dumps(ck['config'],indent=2)+'\n') + shutil.copy(a.experiments,staging/'EXPERIMENTS.md');shutil.copy(a.report,staging/'validation_report.json') + # Include generator/sampler provenance, which is not imported by inference. + (staging/'provenance').mkdir() + for file in ('pack.py','data.py','train.py'):shutil.copy(HERE/file,staging/'provenance'/file) + (staging/'README.md').write_text('# Direct seasonal quantile foundation forecaster\n\nRun `bash infer.sh INPUT_DIR OUTPUT_DIR`. This package contains all inference assets and uses only its supplied input directory. The 6.76M 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.\n\nThe 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.\n') + if final.exists(): + libc=ctypes.CDLL(None,use_errno=True) + if libc.renameat2(-100,os.fsencode(staging),-100,os.fsencode(final),2):raise OSError(ctypes.get_errno(),os.strerror(ctypes.get_errno())) + shutil.rmtree(staging) + else:os.replace(staging,final) + print(json.dumps(manifest,indent=1)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/record.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/record.py new file mode 100644 index 0000000000000000000000000000000000000000..1850a33f46fa3ee4d78cac4a5d6152404801a131 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/record.py @@ -0,0 +1,9 @@ +import argparse,json,math +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('report');ap.add_argument('--label',required=True);ap.add_argument('--outcome',default='Screened for model selection.');a=ap.parse_args() +r=json.loads(Path(a.report).read_text());p=Path(__file__).with_name('EXPERIMENTS.md') +lines=[f'\n## {a.label}',f'- Checkpoint SHA-256: `{r.get("checkpoint_sha256","see model_manifest.json")}`.',f'- Evaluation: {r["n_configs"]} configurations, {r["n_instances"]} instances, {r["n_failed"]} failed configurations; {r.get("eval_seconds","not separately timed")} seconds.',f'- Overall skill {r["skill_score"]:.6f}; relative MASE {r["rel_mase_gmean"]:.6f}; relative WQL {r["rel_wql_gmean"]:.6f}.'] +for group,entries in r['groups'].items(): + lines.append(f'- {group} skill: '+', '.join(f'{k}={1-math.sqrt(v["rel_mase_gmean"]*v["rel_wql_gmean"]):.4f}' for k,v in entries.items())+'.') +lines.append('- Outcome: '+a.outcome) +with p.open('a') as f:f.write('\n'.join(lines)+'\n') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/train.py new file mode 100644 index 0000000000000000000000000000000000000000..3cdc106980371c99d81c71d6746943c47206be83 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/train.py @@ -0,0 +1,71 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(3);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/validation_subset.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..4df83e69c4f9a3365955e5d17ffcfc0af71372b7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/patch16/validation_subset.py @@ -0,0 +1,18 @@ +"""Model-selection-only subset spanning all 97 configurations, seed 2026.""" +import sys,json,copy +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +import ts_io + +root=Path('/workspace/data/valid');out=Path('/workspace/research/valid_screen') +idx=json.loads((root/'input/index.json').read_text());new=copy.deepcopy(idx);rng=np.random.default_rng(2026) +for cfg in new['configs']: + cid=cfg['config_id'];case=ts_io.CaseFile(root/'input/cases'/f'{cid}.h5') + ids=np.sort(rng.choice(case.n,min(case.n,192),replace=False)) + ts_io.write_case_subset(case,ids,out/'input/cases'/f'{cid}.h5') + lab,se,meta=ts_io.read_truth_file(root/'truth/cases'/f'{cid}.h5') + ts_io.write_truth_file(out/'truth/cases'/f'{cid}.h5',lab[ids],se[ids],meta) + cfg['n_instances']=len(ids);case.close() +for kind in ('input','truth'):(out/kind/'index.json').write_text(json.dumps(new,indent=1)) +print('screen instances',sum(c['n_instances'] for c in new['configs'])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/postloss/check_numerical_fix.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/postloss/check_numerical_fix.py new file mode 100644 index 0000000000000000000000000000000000000000..0dd7f0b04a538020f59a4d4e8d6bc4884e0acd29 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/postloss/check_numerical_fix.py @@ -0,0 +1,26 @@ +"""Regression test for observed variance overflow in permitted training data.""" +import importlib.util +import json +from pathlib import Path +import time +import torch +from model import DirectForecaster,loss_fn + +R=Path('/workspace/research');torch.set_num_threads(1);started=time.monotonic() +spec=importlib.util.spec_from_file_location('original',Path(__file__).with_name('model_before_numerical_fix.py')) +original=importlib.util.module_from_spec(spec);spec.loader.exec_module(original) +torch.manual_seed(331);normal=torch.randn(8,512);normal[0,:200]=float('nan');normal[1]=float('nan');normal[2]=0 +old=original.DirectForecaster.standardize(normal);new=DirectForecaster.standardize(normal) +assert all(torch.equal(a,b) for a,b in zip(old,new)) +f=torch.load(R/'postloss_nonfinite_fixture.pt',map_location='cpu',weights_only=False) +indices=torch.tensor([37]);ctx=f['ctx'][indices];target=f['target'][indices];periods=f['periods'][indices] +z,valid,mu,scale=DirectForecaster.standardize(ctx) +assert torch.isfinite(z).all() and torch.isfinite(mu).all() and torch.isfinite(scale).all() +ck=torch.load(R/'horizon_delta12k.pt',map_location='cpu',weights_only=False) +m=DirectForecaster(**ck['config']).cuda();m.load_state_dict(ck['model']) +with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(m,ctx.cuda(),target.cuda(),periods.cuda(),paired=True) +loss.backward();torch.cuda.synchronize() +assert torch.isfinite(loss) and all(v.grad is not None and torch.isfinite(v.grad).all() for v in m.parameters()) +result={'ordinary_rows_bitwise_original':True,'observed_overflow_row_loss':float(loss.detach()), + 'all_gradients_finite':True,'optimizer_updates':0,'seconds':time.monotonic()-started} +(R/'postloss_numerical_fix_checks.json').write_text(json.dumps(result,indent=2));print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/postloss/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/postloss/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/postloss/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/postloss/diagnose_nonfinite.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/postloss/diagnose_nonfinite.py new file mode 100644 index 0000000000000000000000000000000000000000..770ff91d0718cbb6b947fc91fd61697ea50cbfd6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/postloss/diagnose_nonfinite.py @@ -0,0 +1,42 @@ +"""Find nonfinite fixed-transform outputs on the unchanged allowed-corpus stream.""" +import json +from pathlib import Path +import time +import numpy as np +import torch +from model import DirectForecaster +from data import Sampler +from torch_post import apply_fixed,context_statistics + +R=Path('/workspace/research');torch.set_num_threads(1);torch.manual_seed(197) +torch.backends.cuda.matmul.allow_tf32=True +ck=torch.load(R/'horizon_delta12k.pt',map_location='cpu',weights_only=False) +m=DirectForecaster(**ck['config']).cuda();m.load_state_dict(ck['model']);m.eval() +sampler=Sampler(R/'packed_sample',seed=197,source_weights_from=R/'packed_sample') +rng=np.random.default_rng(197);started=time.monotonic() +for step in range(1,251): + 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])) + arrays=sampler.sample(64,c,h);ctx,target,periods=[torch.from_numpy(v).cuda() for v in arrays] + with torch.no_grad(),torch.autocast('cuda',dtype=torch.bfloat16): + seen=torch.isfinite(target);pos=torch.arange(h,device=ctx.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + raw,mu,scale=m(torch.cat((ctx,-ctx),0),periods.repeat(2,1),h,forecast_lengths=lengths.repeat(2)) + q=(raw[:64]-raw[64:].flip(-1))*.5;mu=mu[:64];scale=scale[:64] + denormalized=q*scale[:,:,None]+mu[:,:,None] + post=apply_fixed(ctx,periods,denormalized) + bad=~torch.isfinite(post).all((1,2)) + if bad.any(): + stats=context_statistics(ctx,periods,h) + badids=torch.nonzero(bad)[:,0] + receipt={'step':step,'context':c,'horizon':h,'bad_rows':badids.tolist(), + 'raw_finite':bool(torch.isfinite(q).all()),'scale_finite':bool(torch.isfinite(scale).all()), + 'denormalized_finite':bool(torch.isfinite(denormalized).all()), + 'statistics_finite':[bool(torch.isfinite(v).all()) for v in stats], + 'bad_scale':scale[bad].tolist(),'bad_mu':mu[bad].tolist(), + 'bad_maximum_context':torch.nan_to_num(ctx[bad]).abs().max(-1).values.tolist(), + 'seconds':time.monotonic()-started,'optimizer_updates':0} + torch.save({'ctx':ctx.cpu(),'target':target.cpu(),'periods':periods.cpu(), + 'raw':denormalized.cpu(),'scale':scale.cpu(),'post':post.cpu(), + 'statistics':[v.cpu() for v in stats]},R/'postloss_nonfinite_fixture.pt') + (R/'postloss_nonfinite_diagnostic.json').write_text(json.dumps(receipt,indent=2));print(json.dumps(receipt));break +else:print(json.dumps({'no_nonfinite_fixed_parent_outputs_in_first_steps':250,'seconds':time.monotonic()-started})) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/postloss/gpu_check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/postloss/gpu_check.py new file mode 100644 index 0000000000000000000000000000000000000000..a457afa8d1dd55d2167434b70f4e1488e41e4049 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/postloss/gpu_check.py @@ -0,0 +1,24 @@ +"""Verify the new training loss at the largest scheduled bf16 shape.""" +import fcntl,json,sys,time +from pathlib import Path +import torch + +r=Path('/workspace/research');sys.path.insert(0,str(r/'postloss')) +from model import DirectForecaster,loss_fn +from data import Sampler +with open(r/'.evaluation.lock','a') as lock: + fcntl.flock(lock,fcntl.LOCK_EX) + torch.set_num_threads(1);torch.manual_seed(281);torch.backends.cuda.matmul.allow_tf32=True + started=time.monotonic() + ck=torch.load(r/'horizon_delta12k.pt',map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).cuda();model.load_state_dict(ck['model']) + x,y,p=[torch.from_numpy(a).cuda() for a in Sampler(r/'packed_sample',281).sample(64,4096,1024)] + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p,paired=True) + loss.backward();torch.cuda.synchronize() + assert torch.isfinite(loss) + assert all(v.grad is not None and torch.isfinite(v.grad).all() for v in model.parameters()) + result={'seed':281,'batch':64,'context':4096,'horizon':1024,'optimizer_updates':0, + 'loss':float(loss.detach()),'seconds':time.monotonic()-started, + 'peak_allocated_mib':torch.cuda.max_memory_allocated()/2**20, + 'peak_reserved_mib':torch.cuda.max_memory_reserved()/2**20} + (r/'postloss_gpu_check.json').write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/postloss/launch_completion.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/postloss/launch_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..8bdf1346b99ae846a2679a7494c9b88c1900bdce --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/postloss/launch_completion.py @@ -0,0 +1,30 @@ +"""Complete the original pruned schedule from its immutable exact training state.""" +def main(): + import json + import os + import subprocess + from pathlib import Path + R=Path('/workspace/research') + receipt=json.loads((R/'postloss_recovery003653.json').read_text()) + assert receipt['step']==3653 + assert json.loads((R/'postloss_completion_code_audit.json').read_text())['matches_original_E75_archived_training_code'] + assert (R/'postloss.stop').exists() + env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1') + command=['python3',str(R/'recovery/train.py'),'--code-dir',str(R/'postloss'), + '--packed',str(R/'packed_sample'),'--source-weights-from',str(R/'packed_sample'), + '--out',str(R/'runs/postloss_completion'),'--initialize-from',str(R/'horizon_delta12k.pt'), + '--resume',str(R/'postloss_recovery003653.pt'),'--steps','12000','--batch','64','--lr','.00002', + '--seed','197','--loss-mode','paired','--stop-file',str(R/'postloss_completion.stop')] + with (R/'postloss_completion_queue.log').open('w') as qlog,(R/'postloss_completion_watch.log').open('w') as wlog: + queued=subprocess.Popen(['python3',str(R/'queued_train.py'),'--label','E98 complete original E75 schedule', + '--log',str(R/'postloss_completion_train.log'),'--receipt',str(R/'postloss_completion_queue.json'), + '--wait-pid','9274','--require-checkpoint',str(R/'runs/split_patch/recovery.pt'), + '--',*command],stdout=qlog,stderr=subprocess.STDOUT,env=env) + watch=subprocess.Popen(['python3',str(R/'watch_evaluate.py'),'--run',str(R/'runs/postloss_completion'), + '--evaluator',str(R/'postloss_inference/evaluate.py'),'--name','postloss_completion', + '--steps','6000,12000'],stdout=wlog,stderr=subprocess.STDOUT,env=env) + print({'queue_pid':queued.pid,'watch_pid':watch.pid},flush=True) + result=queued.wait() + if result:watch.terminate() + watch.wait();raise SystemExit(result) +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/postloss/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/postloss/model.py new file mode 100644 index 0000000000000000000000000000000000000000..014b585df72cc69852a8eedf302320b52fe55aad --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/postloss/model.py @@ -0,0 +1,216 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + from torch_post import apply_fixed + q=apply_fixed(ctx,periods,q*scale[:,:,None]+mu[:,:,None]) + q=(q-mu[:,:,None])/scale[:,:,None] + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/postloss/model_before_numerical_fix.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/postloss/model_before_numerical_fix.py new file mode 100644 index 0000000000000000000000000000000000000000..1dab6e08582e4610693292e765d40a8b5392e97a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/postloss/model_before_numerical_fix.py @@ -0,0 +1,207 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + from torch_post import apply_fixed + q=apply_fixed(ctx,periods,q*scale[:,:,None]+mu[:,:,None]) + q=(q-mu[:,:,None])/scale[:,:,None] + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/postloss/restart.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/postloss/restart.py new file mode 100644 index 0000000000000000000000000000000000000000..fa09bf30ead55ac10ca2d8c9a55277ddd71986f7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/postloss/restart.py @@ -0,0 +1,25 @@ +"""Restart corrected E75 from the declared parent and record process compute.""" +import json +import os +from pathlib import Path +import subprocess +import time + +R=Path('/workspace/research');run=R/'runs/postloss' +receipt=json.loads((R/'postloss_queue_before_recovery2.json').read_text()) +command=receipt['command'] +assert not (run/'recovery.pt').exists(),'This script is only for the documented pre-checkpoint numerical restart.' +env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1') +with (R/'postloss_recovery3.log').open('w') as f: + p=subprocess.Popen(command,stdout=f,stderr=subprocess.STDOUT,env=env) +record={'command':command,'status':'running','pid':p.pid,'log':str(R/'postloss_recovery3.log'), + 'started_utc':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()), + 'note':'Restart own E62 initialization after verified float32 variance-overflow correction; original seed and recipe unchanged.'} +path=R/'postloss_recovery3_receipt.json';path.write_text(json.dumps(record,indent=2)) +watch=['python3',str(R/'watch_evaluate.py'),'--run',str(run),'--evaluator',str(R/'postloss_inference/evaluate.py'), + '--name','postloss','--steps','1000,3000,6000,12000'] +with (R/'postloss_watch_recovery3_fixed.log').open('w') as f: + subprocess.Popen(watch,stdout=f,stderr=subprocess.STDOUT,env=env) +started=time.monotonic();returncode=p.wait() +record.update(status='complete' if returncode==0 else 'failed',returncode=returncode,process_seconds=time.monotonic()-started) +path.write_text(json.dumps(record,indent=2));raise SystemExit(returncode) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/postloss/torch_post.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/postloss/torch_post.py new file mode 100644 index 0000000000000000000000000000000000000000..e19586bcc1677d56cedb6ce02c2f57797157f5f3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/postloss/torch_post.py @@ -0,0 +1,112 @@ +"""Differentiable forecast transforms with the package's fixed context rules. + +Context statistics are constants with respect to model parameters. Gradients +flow only through the forecast, including the continuity correction's anchor. +""" +import torch + + +@torch.no_grad() +def context_statistics(ctx, periods, horizon): + x=ctx.double(); finite=torch.isfinite(x); clean=torch.where(finite,x,0.) + b,c=x.shape; device=x.device + pos=torch.arange(c,device=device)[None,:] + count=finite.sum(-1).clamp(min=1) + mean=clean.sum(-1)/count + variance=(torch.where(finite,x-mean[:,None],0.).square()).sum(-1)/count + positive=((x>=0)|~finite).all(-1) + zeros=((x==0)&finite).sum(-1) + zero_active=positive&(zeros>=4)&(zeros/count>=.1) + cutoff=torch.where(zero_active,.4*variance.sqrt(),0.) + first=torch.where(finite,pos,c).min(-1).values + length=c-first + phase=torch.arange(max(1,c//3),device=device)[None,:] + future=torch.arange(horizon,device=device)[None,:] + z=torch.tensor([-1.2815515655,-.8416212336,-.5244005127,-.2533471031,0, + .2533471031,.5244005127,.8416212336,1.2815515655],device=device) + best_weight=torch.zeros(b,device=device,dtype=torch.float64) + prior=torch.zeros(b,horizon,9,device=device,dtype=torch.float64) + prior_valid=torch.zeros(b,horizon,device=device,dtype=torch.bool) + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + cycles=(length[:,None]//p).clamp(max=8) + history=finite&(pos>=c-cycles*p) + n=history.sum(-1).clamp(min=1) + center=(clean*history).sum(-1)/n + var=torch.where(history,x-center[:,None],0.).square().sum(-1)/n + previous=pos-p;safe=previous.clamp(min=0) + pairs=(previous>=c-cycles*p)&(previous>=0)&finite&finite.gather(1,safe) + pairs_count=pairs.sum(-1) + difference=clean-clean.gather(1,safe) + mse=(difference.square()*pairs).sum(-1)/pairs_count.clamp(min=1) + weight=(1-mse/(var+1e-12)/.25).clamp(0,.98) + eligible=(p[:,0]>=2)&(cycles[:,0]>=3)&(pairs_count>=p[:,0]) + weight=torch.where(eligible,weight,0.) + values=[];observed=[] + for cycle in range(4): + idx=c-p+phase-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(phase=0)&(cycle0 + template=(values*observed).sum(0)/nphase.clamp(min=1) + ntemplate=phase_valid.sum(-1).clamp(min=1) + template_mean=(template*phase_valid).sum(-1)/ntemplate + recent=finite&(pos>=c-p) + nr=recent.sum(-1).clamp(min=1) + recent_mean=(clean*recent).sum(-1)/nr + template=template+(recent_mean-template_mean)[:,None] + template_mean=(template*phase_valid).sum(-1)/ntemplate + recent_var=torch.where(recent,x-recent_mean[:,None],0.).square().sum(-1)/nr + template_var=((template-template_mean[:,None]).square()*phase_valid).sum(-1)/ntemplate + used_cycles=cycles[:,0].clamp(min=1,max=4) + noise=mse/2 + target_var=(recent_var-noise).clamp(min=0) + base_var=(template_var-noise/used_cycles).clamp(min=0) + ratio=(target_var/base_var.clamp(min=1e-12)).sqrt().clamp(.5,2.) + align=nr>=torch.maximum(torch.full_like(nr,2),.75*p[:,0]) + ratio=torch.where(align,ratio,1.) + template=template_mean[:,None]+(template-template_mean[:,None])*ratio[:,None] + sigma=(noise*(1+1/used_cycles)).sqrt() + index=(future%p).clamp(max=phase.shape[-1]-1) + selected=template.gather(1,index) + valid=phase_valid.gather(1,index) + q=selected[:,:,None]+sigma[:,None,None]*z[None,None,:] + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + choose=weight>best_weight + prior=torch.where(choose[:,None,None],q,prior) + prior_valid=torch.where(choose[:,None],valid,prior_valid) + best_weight=torch.maximum(best_weight,weight) + seasonal_weight=best_weight[:,None]*prior_valid + + recent=x[:,-512:];seen=torch.isfinite(recent) + n=seen.sum(-1).clamp(min=1);clean_recent=torch.where(seen,recent,0.) + center=clean_recent.sum(-1)/n + var=torch.where(seen,recent-center[:,None],0.).square().sum(-1)/n + differences=recent[:,1:]-recent[:,:-1] + diff_seen=torch.isfinite(differences);nd=diff_seen.sum(-1) + mse=torch.where(diff_seen,differences,0.).square().sum(-1)/nd.clamp(min=1) + tail=differences[:,-8:] + tail_seen=torch.isfinite(tail);nt=tail_seen.sum(-1) + sorted_tail=torch.where(tail_seen,tail,float('inf')).sort(-1).values + if tail.shape[-1]: + lo=((nt-1).clamp(min=0)//2)[:,None];hi=(nt//2).clamp(max=tail.shape[-1]-1)[:,None] + median=(sorted_tail.gather(1,lo)+sorted_tail.gather(1,hi))[:,0]/2 + else:median=torch.zeros(b,device=device,dtype=x.dtype) + continuity_weight=(1-mse/(var+1e-12)/.5).clamp(0,.95) + active=(nd>=8)&(nt>0)&seen[:,-1] + continuity_weight=torch.where(active,continuity_weight,0.) + anchor=torch.where(active,recent[:,-1]+median,0.) + return seasonal_weight,prior,continuity_weight,anchor,positive,cutoff + + +def apply_fixed(ctx,periods,quant): + """Quantiles are raw-scale tensors of shape (batch,horizon,9).""" + weight,prior,cweight,anchor,positive,cutoff=context_statistics(ctx,periods,quant.shape[1]) + q=torch.where(positive[:,None,None],quant.clamp(min=0),quant) + q=((1-weight[:,:,None])*q+weight[:,:,None]*prior).float() + bias=(cweight*(anchor-q[:,0,4])).float() + decay=torch.exp(-torch.arange(q.shape[1],device=q.device,dtype=torch.float64)/24) + q=(q.double()+bias[:,None,None]*decay[None,:,None]).float() + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return torch.where((q>=0)&(q8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/recency_features/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/recency_features/model.py new file mode 100644 index 0000000000000000000000000000000000000000..f8271c5b0bf9a5edb961e1c7839761fe50a2e40b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/recency_features/model.py @@ -0,0 +1,171 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024,recency_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + if self.recency is not None: + pos=torch.arange(c,device=z.device)[None,:];extras=[] + for j in range(2): + period=periods[:,j:j+1] + recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/recency_features/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/recency_features/train.py new file mode 100644 index 0000000000000000000000000000000000000000..3bfb8b90f1a6656881b7598f864becaa737a76f4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/recency_features/train.py @@ -0,0 +1,73 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(3);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/recovery/brief.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/recovery/brief.py new file mode 100644 index 0000000000000000000000000000000000000000..f9b0612d121dbc6b618909f6539ce19a871c2827 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/recovery/brief.py @@ -0,0 +1,31 @@ +"""Write a short, current recovery handoff; never modify training state.""" +import datetime +import json +from pathlib import Path + +R = Path('/workspace/research') +s = json.loads((R/'CURRENT_RESEARCH_STATE.json').read_text()) +lines = ['# Current recovery brief', '', datetime.datetime.now(datetime.timezone.utc).isoformat(), '', + 'Continuous research; no endpoint/final hand-in. One H10080GB,22CPUs,224GiB requested RAM; no network or pretrained assets. Do not inspect credentials or spawn agents.', '', + '## Published', '', json.dumps(s['published']), '', '## Pending selection', '', + json.dumps(s.get('next_candidate',{})), '', '## Active and queued training', ''] +for name, job in s.get('external_jobs',{}).items(): + if job['status'] not in ['running','waiting']: + continue + lines += [f'- {name}: {job["status"]}; receipt {job["receipt"]}; queue PID snapshot {job["queue_pid_at_snapshot"]}; children {job["child_pids_at_snapshot"]}.', + f' Last logged record: {json.dumps(job["last_phase_record"])}', + f' Complete recovery: {job["complete_recovery_checkpoint"]}; latest EMA: {job["latest_saved_ema"]}.'] +lines += ['', '## Recovery rules', '', + '- PIDs and launch-script dependencies are snapshots. After an operator restart, restore running jobs from each complete recovery.pt, preserving optimizer/EMA/RNG/prefetched batch and original schedules. Rewire waiting jobs to the newly launched dependency PIDs; do not blindly rerun old launch scripts.', + '- Waiting dependency chain: weekly_replication_control after long_seasonal; weekly_replication_candidate after that control; lowfreq_windows after that candidate; long_seasonal_replication after lowfreq_windows. phase_joint waits for random_capacity_512 final96000; seasonal_dispersion waits for phase_joint final12000.', + '- E101 distillation teacher is immutable /workspace/research/distill_teacher_E96, even after later publications. Do not substitute the current submission.', + '- Restore compiler_cache_backup to the same /tmp cache paths before restarting compiled trainers. Exact environment and commands are in CURRENT_RESEARCH_STATE.json.', + '- E105 output collision is documented in incidents/stratified_volume_output_collision. Correct E105 output is runs/stratified_volume. E95final and2k..12k weights survive, but E95optimizer recovery and original1k weights were lost. Do not resume completed E95.', + '- All previous negative/stopped branches stay stopped unless a new matched experiment explicitly revisits them. Never retrain the supplied baselines.', + '- Current training-source publisher archives all Python modules from explicitly declared directories, fixing earlier omissions of spectral.py and schedules.py. Complete-source members carry a -complete suffix when rebuilt. Runtime/weight hashes were unchanged.', + '- Full evaluation and GPU diagnostics use .evaluation.lock; the six trainers legitimately share the one H100. Dataset windows under data/valid and all earlier cutoffs are selection only, never training.', + '- Master journal direct_v1/EXPERIMENTS.md, chronological SESSION_20261023_PROGRESS.md, and RESEARCH_IDEAS.md contain decisions and rejected candidates. Recheck live processes and latest reports before acting.', + '', '## Time anchor', '', + 'Latest operator recovery allowance:151596research seconds at2026-10-23T02:45:51UTC. Pauses/preflight excluded. The goal remains active and has no requested token budget.', ''] +(R/'RECOVERY_BRIEF.md').write_text('\n'.join(lines)) +print('Wrote RECOVERY_BRIEF.md with '+str(sum(j['status'] in ['running','waiting'] for j in s.get('external_jobs',{}).values()))+' active/queued jobs.') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/recovery/capacity_curves.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/recovery/capacity_curves.py new file mode 100644 index 0000000000000000000000000000000000000000..c89a28a84243dc16ae52a1215c182a00f15dbc4e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/recovery/capacity_curves.py @@ -0,0 +1,50 @@ +"""Summarize completed validation checkpoints and measured shared-GPU training time.""" +import csv +import json +import time +from pathlib import Path + +R = Path('/workspace/research') +started = time.monotonic() +names = ['random_capacity_512', 'random_capacity_1024', 'random_capacity_1024_halflr', + 'random_capacity_full', 'distill_ensemble', 'random_capacity_512_anneal'] +rows = [] +for name in names: + log = R/(name+'_train.log') + records = {} + if log.exists(): + for line in log.read_text().splitlines(): + try: + item = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(item,dict) and 'step' in item and 'seconds' in item: + records[item['step']] = item + config_path = R/'runs'/name/'config.json' + config = json.loads(config_path.read_text()) if config_path.exists() else {} + for report in sorted((R/'evals').glob(name+'_ema*/report.json')): + result = json.loads(report.read_text()) + step = int(report.parent.name.rsplit('ema',1)[1]) + if result['n_failed']: + continue + record = records.get(step,{}) + rows.append(dict(run=name,step=step,parameters=config.get('parameters'), + seed=config.get('seed'),batch=config.get('batch'),learning_rate=config.get('lr'), + packed=config.get('packed'),skill=result['skill_score'], + rel_mase=result['rel_mase_gmean'],rel_wql=result['rel_wql_gmean'], + checkpoint_sha256=result['checkpoint_sha256'], + training_phase_loop_seconds=record.get('seconds'), + evaluation_seconds=result.get('eval_seconds'),report=str(report))) +rows.sort(key=lambda item:(names.index(item['run']),item['step'])) +output = dict(generated_utc=time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()), + note='Validation selection only. Time is logged process wall on the shared single H100, not isolated GPU time. The cooldown arm starts from the same saved24000state; its phase clock resets. No missing log time is inferred.', + rows=rows,analysis_seconds=time.monotonic()-started,no_training_or_new_inference=True) +(R/'capacity_learning_curves.json').write_text(json.dumps(output,indent=2)) +with (R/'capacity_learning_curves.csv').open('w',newline='') as handle: + writer = csv.DictWriter(handle,fieldnames=list(rows[0]) if rows else ['run']) + writer.writeheader() + writer.writerows(rows) +for name in names: + selected = [r for r in rows if r['run']==name] + if selected: + print(json.dumps(selected[-1])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/recovery/exposure_audit.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/recovery/exposure_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..fb67738bc9ed77f87173feda2430365e66c75966 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/recovery/exposure_audit.py @@ -0,0 +1,46 @@ +"""Describe sampled observation exposure and training invested in selected ancestry.""" +import json +import sys +import time +from pathlib import Path +import numpy as np + +R=Path('/workspace/research') +sys.path.insert(0,str(R/'random_capacity')) +from data import Sampler + +started=time.monotonic() +seed=521 +sampler=Sampler(R/'packed_sample',seed=seed,source_weights_from=R/'packed_sample') +rng=np.random.default_rng(seed) +rows=context_points=target_points=0 +for _ in range(320): + 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])) + x,y,p=sampler.sample(64,c,h) + rows+=len(x) + context_points+=int(np.isfinite(x).sum()) + target_points+=int(np.isfinite(y).sum()) +manifest=json.loads(Path('/workspace/submission/model_manifest.json').read_text()) +runs={} +for item in manifest['training_lineage']: + path=Path(item['checkpoint']) + batch=item.get('training_settings',{}).get('batch') + if path.parts[0]!='runs' or not batch: + continue + run=path.parts[1] + step=item.get('step',0) + if step>runs.get(run,{}).get('step',0): + runs[run]=dict(step=step,batch=batch,rows=step*batch,checkpoint=item['checkpoint']) +ancestral_rows=sum(v['rows'] for v in runs.values()) +mean_points=(context_points+target_points)/rows +result=dict(seed=seed,seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False, + sampled_rows=rows,mean_finite_context_points=context_points/rows, + mean_finite_target_points=target_points/rows,mean_finite_points=mean_points, + selected_descriptor=manifest['checkpoint_sha256'],ancestral_runs=runs, + selected_ancestral_rows_before_sign_pairing=ancestral_rows, + fresh96000_batch48_rows=96000*48, + fresh96000_batch48_gross_observation_presentations_estimate=96000*48*mean_points, + note='Gross sampled presentations include overlapping/resampled windows and synthetic values, not unique observations. Ancestral run maxima count compute invested in different branches, including subtracted controls; they are not an equivalent single-model training trajectory. Sign pairing duplicates compute but not distinct sampled rows. No future training recipe is inferred from this audit alone.') +(R/'training_exposure_audit.json').write_text(json.dumps(result,indent=2)) +print(json.dumps({k:v for k,v in result.items() if k!='ancestral_runs'})) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/recovery/quantile_coverage.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/recovery/quantile_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..d7f4958ae772a15c4a580eed59bb9257b065154d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/recovery/quantile_coverage.py @@ -0,0 +1,59 @@ +"""Validation-only quantile coverage, with separate strict/inclusive coverage at atoms.""" +import argparse +import json +import sys +import time +from pathlib import Path + +import numpy as np + +sys.path.insert(0,'/workspace/evaluation') +from ts_io import read_prediction_file, read_truth_file + +parser = argparse.ArgumentParser() +parser.add_argument('--valid',required=True) +parser.add_argument('--pred',required=True) +parser.add_argument('--report',required=True) +parser.add_argument('--out',required=True) +args = parser.parse_args() +started = time.monotonic() +root = Path(args.valid) +index = json.loads((root/'input/index.json').read_text()) +report = json.loads(Path(args.report).read_text()) +levels = np.arange(1,10)/10 +rows = [] +for cfg in index['configs']: + relative = Path('cases')/(cfg['config_id']+'.h5') + y,scale,_ = read_truth_file(root/'truth'/relative) + _,q = read_prediction_file(Path(args.pred)/relative) + valid = np.isfinite(y) + assert q.shape==(*y.shape[:2],9,y.shape[-1]) and np.isfinite(q).all() + count = int(valid.sum()) + assert count>0 + strict = ((y[:,:,None,:] anneal_from_step + assert 0 < anneal_final_lr <= anneal_from_lr + progress=max(0.,min(1.,(step-anneal_from_step)/(steps-anneal_from_step))) + return anneal_final_lr+.5*(anneal_from_lr-anneal_final_lr)*(1+math.cos(math.pi*progress)) + warm_step=step-reset_at if reset_at>=0 and step>reset_at else step + return peak*min(1,warm_step/400)*(.2+.4*(1+math.cos(math.pi*step/steps))) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/recovery/seasonal_history_support.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/recovery/seasonal_history_support.py new file mode 100644 index 0000000000000000000000000000000000000000..84314b30b22a4a761447fc5ee1cffb9301e725b9 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/recovery/seasonal_history_support.py @@ -0,0 +1,23 @@ +"""Context-metadata diagnostic of potential 8-cycle support, with no targets read.""" +import importlib.util,json,time +from pathlib import Path +import h5py,numpy as np +R=Path('/workspace/research');started=time.monotonic() +spec=importlib.util.spec_from_file_location('support_model',R/'long_seasonal/model.py');m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m) +root=Path('/workspace/data/valid/input');index=json.loads((root/'index.json').read_text());rows=[] +for cfg in index['configs']: + with h5py.File(root/'cases'/(cfg['config_id']+'.h5'),'r') as f:lengths=np.asarray(f['context_length']) + h=cfg['prediction_length'];periods=m.periods_for_freq(cfg['freq']);row={k:cfg[k] for k in ['config_id','freq','term','domain']};row['periods']=periods;row['n_instances']=len(lengths) + for cap in [4096,16384]: + support=[];cycles=[] + for p in periods: + count=np.clip(1+(np.minimum(lengths,cap)[:,None]-p+np.arange(h)[None,:]%p)//p,0,16) + support.append(float(np.mean((count>=8)&(p>=2))));cycles.append(float(np.mean(np.where(p>=2,count,0)))) + row[str(cap)]={'phase_support_fraction':support,'mean_available_cycles':cycles} + row['support_gain_sum']=sum(row['16384']['phase_support_fraction'])-sum(row['4096']['phase_support_fraction']);rows.append(row) +changed=[r for r in rows if r['support_gain_sum']>0] +result=dict(kind='optimistic potential support before missing-value masks; not measured forecast improvement',input_metadata_only=True,validation_targets_read=False,optimizer_updates=0,configs=rows, + changed_configurations=len(changed),changed_domains=sorted(set(r['domain'] for r in changed)),seconds=time.monotonic()-started) +(R/'seasonal_history_support.json').write_text(json.dumps(result,indent=2)) +print(json.dumps({k:v for k,v in result.items() if k!='configs'})) +for r in sorted(changed,key=lambda x:x['support_gain_sum'],reverse=True)[:20]:print(json.dumps(r)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/recovery/snapshot.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/recovery/snapshot.py new file mode 100644 index 0000000000000000000000000000000000000000..7695f1a2fd58bde1c457a589e3162b9ba9f71988 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/recovery/snapshot.py @@ -0,0 +1,99 @@ +"""Write a compact authoritative research recovery index without touching training state.""" +import datetime +import json +import os +from pathlib import Path + +R=Path('/workspace/research');p=R/'CURRENT_RESEARCH_STATE.json' +s=json.loads(p.read_text()) +s['snapshot_utc']=datetime.datetime.now(datetime.timezone.utc).isoformat() +receipt=json.loads((R/'recovery3_launch_receipt.json').read_text()) +s['runs']={} +for name,job in receipt['jobs'].items(): + run=R/'runs'/name + log=Path(job['log']) + records=[] + for line in log.read_text().splitlines(): + try: + record=json.loads(line) + if 'step' in record or 'completed_step' in record:records.append(record) + except json.JSONDecodeError:pass + s['runs'][name]={'config':json.loads((run/'config.json').read_text()) if (run/'config.json').exists() else None, + 'last_phase_record':records[-1] if records else None, + 'phase_log':str(log),'supervisor_receipt':str(R/'recovery3_launch_receipt.json'), + 'latest_saved_ema':str(max(run.glob('ema*.pt'))) if list(run.glob('ema*.pt')) else None, + 'complete_recovery_checkpoint':str(run/'recovery.pt') if (run/'recovery.pt').exists() else None, + 'pid_at_snapshot':job['pid'],'returncode':job.get('returncode'), + 'note':'Check actual live process and checkpoint state before resuming; this is only a snapshot.'} +s['queues']={name:{'status':q['status'],'dependency':q['dependency'],'command':q['command'], + 'required_checkpoints':q['required_checkpoints']} + for name,q in receipt['queues'].items()} +s.pop('prepared_not_launched',None) +s['deferred_unqueued']={'E72':'temporal_mixup, prepared and checked but not queued','ideas':'RESEARCH_IDEAS.md, no jobs attached'} +s['completed_since_previous_recovery']={ + 'E67_control12000':{'skill':.37724286394256845,'training_loop_seconds':2794.8358458959847}, + 'E67_paired12000':{'skill':.377427077277383,'training_loop_seconds':2794.867385860998}, + 'E63_expanded146M':'Stopped8501, complete recovery retained; allocation moved to E73; inconclusive data scaling', + 'E61_slowAR':'Complete12000; E76 used6000 correction, final transfer rejected', + 'E65_recent_normalization':'Complete12000; E81 equal ensemble rejected', + 'E58_small_control':'Complete32000', + 'E58_wide146M':'Complete32000; no gain over37Mcontrol; do not resume', + 'E71_patch8':'Complete12000; selected6000 used in E87/E96/E102 ensembles', + 'E69_volatility':'Complete12000; final below matched control; no transfer', + 'E89_patch8_control':'Complete12000; final0.380847096,loop2729.052105s; selected starting E71parent remains stronger', + 'E89_fullpatch4':'Complete12000,main0.381640078; E96 used6000, E103final cached alternative mixed; loop5066.016522s', + 'E93_split_patch':'Complete12000,main0.381711986; selected final is E102 published thirdmember; loop3153.565149s', + 'E92_robust_normalization':'Complete12000,final0.377099312 belowcontrol; rejected;E97started', + 'E90_metric_scale':'Complete12000; final0.377373344 ties/slightly trailsE80; no selection; loop2702.166704s', + 'E84_coarse':'Complete12000; daily gain but weekly regression; not selected', + 'E88_late_patch8_slowAR':'Complete12000; small9k gain lost atfinal; rejected', + 'E80_overflow':'Complete12000; finaltiesoriginal; selected3k compositeE91rejected', + 'E78_multiscaleAR':'Complete12000; no gain over single slowAR', + 'E86_protected_graft':'Complete8000; below own initialization; no publication', + 'E75_postloss':'Stopped3653 deliberately; immutable snapshot retained; E98 separately declared completion active in another output, original stopfile remains', + 'E73_independent_graft':'Stopped8683 after negative8000; replaced by E86; stopfile remains', + 'E95_stratified_corpus':'Complete12000,final0.377983250,earliermixed; E105collision destroyed only1000weights and optimizer recovery;2k..12k preserved; do not resume', + 'E97_weekly_synth':'Complete12000,final0.380439539; E112final weekly correction now published; loop2600.472750s', + 'E105_stratified_volume':'Complete12000,final0.377529200,earlier0.336713522/0.359535697/0.390349158 mixed; corrected continuationloop2013.982814s plus original incident phase', + 'E106_spectral_synth':'Complete12000,final0.377641399,earlier0.337647555/0.361626447/0.385497870, average matched gap negligible; loop2206.272278s; E114fixed6000transfers in selection', + 'E98_postloss_completion':'Complete12000,final0.376034254 below3000 andcontrol; rejected,loop1995.386513s', + 'E99_early_cooldown':'Complete36000,final0.363306598 trails original36k0.364859034; rejected,loop1603.635706s', + 'E77_pairedslowAR':'Complete12000;6000 strongest main/earlier comparison'} +s['external_receipts']=[str(R/'postloss_recovery3_receipt.json'),str(R/'random_capacity_512_queue.json'),str(R/'random_capacity_1024_queue.json'),str(R/'multiscale_ar_queue.json'),str(R/'overflow_control_queue.json'),str(R/'coarse_aggregate_queue.json'),str(R/'patch8_long_memory_queue.json'),str(R/'wide_graft_frozen_queue.json'),str(R/'patch4_candidate_queue.json'),str(R/'patch4_control_queue.json'),str(R/'metric_scale_queue.json'),str(R/'robust_normalization_queue.json'),str(R/'split_patch_queue.json'),str(R/'random_capacity_1024_halflr_queue.json'),str(R/'stratified_corpus_queue.json'),str(R/'weekly_synth_queue.json'),str(R/'postloss_completion_queue.json'),str(R/'random_capacity_512_anneal_queue.json'),str(R/'distill_ensemble_queue.json'),str(R/'stratified_volume_queue.json'),str(R/'spectral_synth_queue.json'),str(R/'long_seasonal_queue.json'),str(R/'random_capacity_full_queue.json'),str(R/'weekly_replication_control_queue.json'),str(R/'weekly_replication_candidate_queue.json'),str(R/'lowfreq_windows_queue.json'),str(R/'phase_joint_queue.json'),str(R/'long_seasonal_replication_queue.json'),str(R/'seasonal_dispersion_queue.json')] +queue_pids={'random_capacity_512_queue.json':965,'random_capacity_1024_queue.json':967, + 'multiscale_ar_queue.json':1678,'overflow_control_queue.json':1676, + 'coarse_aggregate_queue.json':3086,'patch8_long_memory_queue.json':3739, + 'wide_graft_frozen_queue.json':3931,'patch4_candidate_queue.json':4078, + 'patch4_control_queue.json':4080} +s['external_jobs']={} +for receipt_name in s['external_receipts']: + receipt_path=Path(receipt_name) + if not receipt_path.exists():continue + item=json.loads(receipt_path.read_text());command=item.get('command',[]) + if '--out' not in command:continue + run=Path(command[command.index('--out')+1]);log=Path(item.get('log',str(receipt_path).replace('_queue.json','_train.log'))) + last=None + if log.exists(): + for line in log.read_text().splitlines(): + try: + record=json.loads(line) + if isinstance(record,dict) and ('step' in record or 'completed_step' in record):last=record + except json.JSONDecodeError:pass + queue_pid=item.get('launcher_pid',queue_pids.get(receipt_path.name)) + children_file=Path(f'/proc/{queue_pid}/task/{queue_pid}/children') if queue_pid else None + children=list(map(int,children_file.read_text().split())) if children_file and children_file.exists() else [] + checkpoints=list(run.glob('ema*.pt')) + s['external_jobs'][run.name]={'receipt':str(receipt_path),'status':item.get('status'), + 'queue_pid_at_snapshot':queue_pid,'child_pids_at_snapshot':children, + 'last_phase_record':last,'log':str(log), + 'latest_saved_ema':str(max(checkpoints)) if checkpoints else None, + 'complete_recovery_checkpoint':str(run/'recovery.pt') if (run/'recovery.pt').exists() else None, + 'command':command,'note':'PIDs are only a snapshot; check actual processes and serialized state before recovery.'} +s['compiler_environment']={'OPENBLAS_NUM_THREADS':'1','OMP_NUM_THREADS':'1','TORCHINDUCTOR_COMPILE_THREADS':'2','MAX_JOBS':'2','PYTHONPATH':str(R/'compiler_support'),'TRITON_CACHE_MANAGER':'sibling_cache:SiblingFileCacheManager','TRITON_CACHE_DIR':'/tmp/timeseries-triton-cache','TORCHINDUCTOR_CACHE_DIR':'/tmp/timeseries-inductor-cache'} +for job in s['external_jobs'].values(): + job['environment']=s['compiler_environment'] if '--compile-loss' in job['command'] else {'OPENBLAS_NUM_THREADS':'1','OMP_NUM_THREADS':'1'} +s['compiler_cache_backup']=str(R/'compiler_cache_backup') +for stale in ['pending','pending_actions','active_experiments','next_experiments','prepared_experiments']: + s.pop(stale,None) +tmp=p.with_suffix('.tmp');tmp.write_text(json.dumps(s,indent=2));os.replace(tmp,p) +print(s['snapshot_utc']) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/recovery/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/recovery/train.py new file mode 100644 index 0000000000000000000000000000000000000000..211edc96d1ea1ee336190852fbff00fe60bef884 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/recovery/train.py @@ -0,0 +1,201 @@ +"""Resumable continuation of our existing permitted-corpus experiments.""" +import argparse,copy,fcntl,inspect,json,math,os,sys,time +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import numpy as np +import torch + +ap=argparse.ArgumentParser() +ap.add_argument('--code-dir',required=True);ap.add_argument('--packed',required=True) +ap.add_argument('--source-weights-from');ap.add_argument('--out',required=True) +ap.add_argument('--initialize-from',required=True);ap.add_argument('--initialize-ema') +ap.add_argument('--start-step',type=int,default=0);ap.add_argument('--resume') +ap.add_argument('--steps',type=int,required=True);ap.add_argument('--batch',type=int,required=True) +ap.add_argument('--lr',type=float,required=True);ap.add_argument('--seed',type=int,required=True) +ap.add_argument('--context',type=int);ap.add_argument('--sample-context',type=int,default=4096) +ap.add_argument('--save-every',type=int,default=1000);ap.add_argument('--stop-file') +ap.add_argument('--recovery-every',type=int,default=250) +ap.add_argument('--halt-after',type=int) +ap.add_argument('--loss-mode',choices=['individual','paired']) +ap.add_argument('--compile-loss',action='store_true') +ap.add_argument('--reset-at',type=int,default=-1);ap.add_argument('--reset-seed',type=int,default=179) +ap.add_argument('--anneal-from-step',type=int);ap.add_argument('--anneal-from-lr',type=float) +ap.add_argument('--anneal-final-lr',type=float) +ap.add_argument('--teacher-package');ap.add_argument('--teacher-coefficient',type=float) +a=ap.parse_args() +# Hold a process-lifetime lock before loading a model or touching GPU state. +_run_out=Path(a.out);_run_out.mkdir(parents=True,exist_ok=True) +_run_lock=open(_run_out/'.training.lock','a') +try:fcntl.flock(_run_lock,fcntl.LOCK_EX|fcntl.LOCK_NB) +except BlockingIOError:raise SystemExit('Another trainer already owns this output directory: '+str(_run_out)) +if not a.resume: + _saved=list(_run_out.glob('ema*.pt'))+list(_run_out.glob('step*.pt')) + if (_run_out/'recovery.pt').exists():_saved.append(_run_out/'recovery.pt') + if _saved: + raise SystemExit('Refusing fresh training into an output with saved checkpoints; use a new directory or explicit --resume: '+str(_run_out)) +sys.path.insert(0,a.code_dir) +from model import DirectForecaster,loss_fn +from data import Sampler +from schedules import learning_rate +torch.set_num_threads(2);torch.manual_seed(a.seed);torch.backends.cuda.matmul.allow_tf32=True +out=Path(a.out);out.mkdir(parents=True,exist_ok=True);a.trainable_scope='all' +if Path(a.code_dir).name in ('long_memory_synth','paired_long_memory','multiscale_ar','random_capacity','patch8_long_memory','distill_ensemble'):a.synthetic_ar_time_constants=[1,10000] +if Path(a.code_dir).name in ('full_paired','patch8','temporal_mixup','postloss','paired_long_memory','multiscale_ar','random_capacity','overflow_control','coarse_aggregate','patch8_long_memory','patch4','metric_scale','robust_normalization','split_patch','weekly_synth','distill_ensemble'):a.requested_horizon_seed=a.seed+300003 +if Path(a.code_dir).name=='multiscale_ar': + a.synthetic_ar_components=4;a.multiscale_ar_seed=a.seed+700003 +if Path(a.code_dir).name=='volatility_synth':a.stochastic_volatility_seed=a.seed+500003 +if Path(a.code_dir).name=='coarse_aggregate': + a.coarse_aggregation_seed=a.seed+900003;a.coarse_aggregation_probability=.2;a.coarse_aggregation_frequencies=['D','W'] +if Path(a.code_dir).name=='temporal_mixup':a.temporal_mixup_seed=a.seed+600003 +if Path(a.code_dir).name=='postloss': + a.fixed_postprocessing_loss=True;a.normalization_overflow_fallback=True +if Path(a.code_dir).name in ('overflow_control','metric_scale','random_capacity','weekly_synth','distill_ensemble'):a.normalization_overflow_fallback=True +if Path(a.code_dir).name=='weekly_synth': + a.weekly_synthetic_seed=a.seed+1000003;a.weekly_replacement_probability=1/11 +if Path(a.code_dir).name=='spectral_synth': + a.spectral_synthetic_seed=a.seed+1100003;a.spectral_replacement_probability=.5 + a.spectral_length_scale=[1,10000];a.spectral_families=['Matern0.5','Matern1.5','Matern2.5','RBF'] + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True +if Path(a.code_dir).name in ('long_seasonal','phase_joint','seasonal_dispersion'): + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True +if Path(a.code_dir).name=='lowfreq_windows': + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True + a.lowfreq_window_seed=a.seed+1200003;a.lowfreq_window_probability=.5 + a.lowfreq_window_rule='period2=1,period1<=52;finite-target endpoint;log-uniform horizon4..min(H,max(8,2p),span-8) with available-length fallback;context cap min(C,max(64,32p));at least4finite history' +if Path(a.code_dir).name=='metric_scale':a.loss_seasonality='lag1 for exact daily[7,365] and weekly[52,1] period pairs; unchanged otherwise' +if Path(a.code_dir).name=='robust_normalization':a.normalization_kind='finite median plus/minus6 mean absolute deviations winsorized mean/RMS, float64; original normalized history clipped30' +if Path(a.code_dir).name=='wide_graft_frozen':a.trainable_scope='new feature stream and cross-stream blocks; inherited parameter blocks frozen' +ck=torch.load(a.resume or a.initialize_from,map_location='cpu',weights_only=False) +# Keep immutable branch ancestry across a later restart from this run's own recovery. +lineage_parents=list(ck.get('parent_checkpoints',[])) +if a.initialize_ema:lineage_parents.append(a.initialize_ema) +if a.resume and Path(a.resume).parent.resolve()!=out.resolve():lineage_parents.append(a.resume) +previous_args=ck.get('args',{}) +previous_resume=previous_args.get('resume') +if previous_resume and Path(previous_resume).parent.resolve()!=Path(previous_args.get('out',a.out)).resolve(): + lineage_parents.append(previous_resume) +lineage_parents=list(dict.fromkeys(lineage_parents)) +config=dict(ck['config']) +if a.context:config['max_context']=a.context +model=DirectForecaster(**config).cuda();model.load_state_dict(ck['model']) +teacher=None +if Path(a.code_dir).name=='distill_ensemble': + assert a.teacher_package and a.teacher_coefficient is not None +if a.teacher_package: + assert Path(a.code_dir).name=='distill_ensemble' + from teacher import OwnEnsembleTeacher + with torch.random.fork_rng(devices=[torch.cuda.current_device()]): + teacher=OwnEnsembleTeacher(a.teacher_package) + if ck.get('args',{}).get('teacher_descriptor_sha256'): + assert ck['args']['teacher_descriptor_sha256']==teacher.descriptor_sha256 + assert ck['args']['teacher_coefficient']==a.teacher_coefficient + a.teacher_descriptor_sha256=teacher.descriptor_sha256 + a.teacher_checkpoint_sha256=teacher.member_hashes + a.teacher_target_kind='equal average of own frozen E96 raw normalized sign-paired neural quantiles, before postprocessing' + +protector=None +if Path(a.code_dir).name=='wide_graft_frozen': + from frozen import FreezeInherited + protector=FreezeInherited(model) + a.protected_parameters=protector.inherited_numel +if a.compile_loss: + torch._dynamo.config.recompile_limit=64 + objective=torch.compile(loss_fn,fullgraph=True,dynamic=False) +else:objective=loss_fn +multipliers=ck.get('lr_multipliers',{}) +def optimizer(): + groups=[] + for mult in sorted(set(multipliers.values())|{1.}): + params=[p for n,p in model.named_parameters() if multipliers.get(n,1.)==mult] + if params:groups.append({'params':params,'lr':a.lr*mult,'lr_multiplier':mult,'weight_decay':.05/mult}) + return torch.optim.AdamW(groups,betas=(.9,.95),fused=True) +opt=optimizer() +if a.resume: + start_step=ck['step'];opt.load_state_dict(ck['optimizer']) + ema={k:v.cuda() for k,v in ck['ema_state'].items()} +else: + start_step=a.start_step + ema_ck=torch.load(a.initialize_ema,map_location='cpu',weights_only=False) if a.initialize_ema else ck + ema={k:v.cuda().clone() for k,v in ema_ck['model'].items()} +del ck +def make_sampler(seed): + kwargs={'seed':seed} + if 'source_weights_from' in inspect.signature(Sampler).parameters:kwargs['source_weights_from']=a.source_weights_from + return Sampler(a.packed,**kwargs),np.random.default_rng(seed) +stream_seed=a.reset_seed if a.reset_at>=0 and start_step>=a.reset_at else a.seed +sampler,rng=make_sampler(stream_seed) +def next_batch(): + c=int(rng.choice([512,1024,2048,a.sample_context],p=[.1,.15,.35,.4])) + h=int(rng.choice([32,128,512,1024],p=[.1,.2,.2,.5])) + x,y,p=sampler.sample(a.batch,c,h) + return x[:,-model.max_context:].copy(),y,p +pool=ThreadPoolExecutor(1) +if a.resume: + recovery=torch.load(a.resume,map_location='cpu',weights_only=False) + rng.bit_generator.state=recovery['batch_rng_state'];sampler.rng.bit_generator.state=recovery['sampler_rng_state'] + for name,state in recovery.get('sampler_rng_states',{}).items():getattr(sampler,name).bit_generator.state=state + torch.set_rng_state(recovery['torch_rng_state']);torch.cuda.set_rng_state_all(recovery['cuda_rng_state']) + pending=recovery['prefetched_batch'];del recovery + future=pool.submit(lambda:pending) +else:future=pool.submit(next_batch) +parameters=sum(p.numel() for p in model.parameters()) +(out/'config.json').write_text(json.dumps({**vars(a),'model':model.config,'parameters':parameters},indent=2)) +print(json.dumps({'parameters':parameters,'starting_step':start_step,'stream_seed':stream_seed,'restored_complete_training_state':bool(a.resume)}),flush=True) +started=time.monotonic();losses=[] +def atomic_save(obj,path): + torch.save(obj,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) +def save(step,include_selection_weights=True): + global future + pending_batch=future.result() + common={'config':model.config,'step':step,'args':vars(a),'lr_multipliers':multipliers, + 'parent_checkpoints':list(dict.fromkeys(lineage_parents+(teacher.checkpoints if teacher else [])))} + if include_selection_weights: + for prefix,state in [('step',model.state_dict()),('ema',ema)]: + atomic_save({**common,'model':state,'ema':prefix=='ema'},out/f'{prefix}{step:06d}.pt') + atomic_save({**common,'model':model.state_dict(),'optimizer':opt.state_dict(),'ema_state':ema, + 'prefetched_batch':pending_batch,'batch_rng_state':copy.deepcopy(rng.bit_generator.state), + 'sampler_rng_state':copy.deepcopy(sampler.rng.bit_generator.state), + 'sampler_rng_states':{name:copy.deepcopy(value.bit_generator.state) for name,value in vars(sampler).items() if isinstance(value,np.random.Generator)}, + 'torch_rng_state':torch.get_rng_state(),'cuda_rng_state':torch.cuda.get_rng_state_all()},out/'recovery.pt') + future=pool.submit(lambda:pending_batch) +for step in range(start_step+1,a.steps+1): + if a.reset_at>=0 and step==a.reset_at+1 and start_step=a.halt_after) + selection_checkpoint=step%a.save_every==0 or step==a.steps or stop + # Persist a complete state before a fresh/resumed job warms its remaining compiled shapes. + if selection_checkpoint or step%a.recovery_every==0 or step==start_step+1: + save(step,include_selection_weights=selection_checkpoint) + if stop:break +pool.shutdown() +print(json.dumps({'completed_step':step,'training_process_loop_seconds':time.monotonic()-started}),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/spectral_synth/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/spectral_synth/check.py new file mode 100644 index 0000000000000000000000000000000000000000..18b155db82902843efdf6df4164d5ed87f249a47 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/spectral_synth/check.py @@ -0,0 +1,79 @@ +"""Check spectral covariance and unchanged control streams without validation data.""" +import copy +import hashlib +import importlib.util +import json +import sys +import time +from pathlib import Path + +import numpy as np + +R = Path('/workspace/research') +sys.path.insert(0, str(R / 'spectral_synth')) +from data import Sampler +from spectral import gaussian_residual, spectral_density + +spec = importlib.util.spec_from_file_location('spectral_control_data', R / 'overflow_control/data.py') +control_code = importlib.util.module_from_spec(spec) +spec.loader.exec_module(control_code) +started = time.monotonic() +seed = 499 +candidate = Sampler(R / 'packed_sample', seed=seed, source_weights_from=R / 'packed_sample') +control = control_code.Sampler(R / 'packed_sample', seed=seed, source_weights_from=R / 'packed_sample') +rng = np.random.default_rng(seed) +rows = synthetic_rows = replaced_rows = 0 +for _ in range(120): + c = int(rng.choice([512, 1024, 2048, 4096])) + h = int(rng.choice([32, 128, 512, 1024])) + expected = control.sample(64, c, h) + actual = candidate.sample(64, c, h) + replacements = np.array(candidate.last_spectral_rows, dtype=int) + unchanged = np.ones(64, dtype=bool) + unchanged[replacements] = False + for x, y in zip(expected, actual): + assert np.array_equal(x[unchanged], y[unchanged], equal_nan=True) + assert set(replacements) <= set(candidate.last_synthetic_rows) + assert np.array_equal(expected[2], actual[2]) + for x, y in zip(expected[:2], actual[:2]): + assert np.array_equal(np.isfinite(x), np.isfinite(y)) + assert candidate.rng.bit_generator.state == control.rng.bit_generator.state + assert candidate.horizon_rng.bit_generator.state == control.horizon_rng.bit_generator.state + rows += 64 + synthetic_rows += len(candidate.last_synthetic_rows) + replaced_rows += len(replacements) +sampler_seconds = time.monotonic() - started +states = {n: copy.deepcopy(v.bit_generator.state) for n, v in vars(candidate).items() + if isinstance(v, np.random.Generator)} +next_batch = candidate.sample(64, 4096, 1024) +for name, state in states.items(): + getattr(candidate, name).bit_generator.state = state +replayed = candidate.sample(64, 4096, 1024) +assert all(np.array_equal(x, y, equal_nan=True) for x, y in zip(next_batch, replayed)) + +covariances = [] +for family in range(4): + values = np.stack([gaussian_residual(512, rng, length_scale=8, family=family) + for _ in range(1024)]) + expected = np.fft.irfft(spectral_density(2048, 8, family), n=2048) + observed = [float(np.mean(values * values))] + observed += [float(np.mean(values[:, lag:] * values[:, :-lag])) for lag in [1, 8, 32]] + wanted = expected[[0, 1, 8, 32]] + assert np.max(np.abs(np.array(observed) - wanted)) < .045 + covariances.append(dict(family=family, observed=observed, theoretical=wanted.tolist())) +for family in range(4): + for n in [8, 40, 5120]: + for scale in [1., 1e4]: + assert np.isfinite(gaussian_residual(n, rng, scale, family)).all() +model_hash = hashlib.sha256((R / 'spectral_synth/model.py').read_bytes()).hexdigest() +assert model_hash == hashlib.sha256((R / 'overflow_control/model.py').read_bytes()).hexdigest() +result = dict(seed=seed, rows=rows, original_synthetic_rows=synthetic_rows, + replaced_spectral_rows=replaced_rows, probability=.5, + original_and_horizon_rng_bitwise_preserved=True, + unmodified_rows_bitwise_preserved=True, periods_and_finite_masks_unchanged=True, + all_numpy_rng_recovery_exact=True, model_sha256=model_hash, + model_bitwise_unchanged=True, covariance_checks=covariances, + sampler_comparison_seconds=sampler_seconds, seconds=time.monotonic()-started, + optimizer_updates=0, validation_data_read=False) +(R / 'spectral_synth_checks.json').write_text(json.dumps(result, indent=2)) +print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/spectral_synth/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/spectral_synth/data.py new file mode 100644 index 0000000000000000000000000000000000000000..bf91f33740715be702c2772f3cca89b656cea4dc --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/spectral_synth/data.py @@ -0,0 +1,102 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq +from spectral import gaussian_residual + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + if self.spectral_rng.random()8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + self.spectral_rng=np.random.default_rng(seed+1100003) + self.spectral_probability=.5 + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/spectral_synth/launch.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/spectral_synth/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..0134693b620294a3fb18eed15e107d649a0cc487 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/spectral_synth/launch.py @@ -0,0 +1,29 @@ +"""Queue spectral synthetic residuals after postloss completion finishes.""" +def main(): + import json + import os + import subprocess + from pathlib import Path + R=Path('/workspace/research') + checks=json.loads((R/'spectral_synth_checks.json').read_text()) + assert checks['original_and_horizon_rng_bitwise_preserved'] and checks['unmodified_rows_bitwise_preserved'] + assert checks['all_numpy_rng_recovery_exact'] and checks['model_bitwise_unchanged'] + env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1') + command=['python3',str(R/'recovery/train.py'),'--code-dir',str(R/'spectral_synth'), + '--packed',str(R/'packed_sample'),'--source-weights-from',str(R/'packed_sample'), + '--out',str(R/'runs/spectral_synth'),'--initialize-from',str(R/'horizon_delta12k.pt'), + '--steps','12000','--batch','64','--lr','.00002','--seed','197','--loss-mode','paired', + '--stop-file',str(R/'spectral_synth.stop')] + with (R/'spectral_synth_queue.log').open('w') as qlog,(R/'spectral_synth_watch.log').open('w') as wlog: + queued=subprocess.Popen(['python3',str(R/'queued_train.py'),'--label','E106 spectral synthetic residuals seed197', + '--log',str(R/'spectral_synth_train.log'),'--receipt',str(R/'spectral_synth_queue.json'), + '--wait-pid','10664','--require-checkpoint',str(R/'runs/postloss_completion/recovery.pt'), + '--',*command],stdout=qlog,stderr=subprocess.STDOUT,env=env) + watch=subprocess.Popen(['python3',str(R/'watch_evaluate.py'),'--run',str(R/'runs/spectral_synth'), + '--evaluator',str(R/'postloss_inference/evaluate.py'),'--name','spectral_synth', + '--expected-packed',str(R/'packed_sample'),'--steps','1000,3000,6000,12000'],stdout=wlog,stderr=subprocess.STDOUT,env=env) + print({'queue_pid':queued.pid,'watch_pid':watch.pid},flush=True) + result=queued.wait() + if result:watch.terminate() + watch.wait();raise SystemExit(result) +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/spectral_synth/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/spectral_synth/model.py new file mode 100644 index 0000000000000000000000000000000000000000..3532e5063bd8b5013f6b6e35703707ffef66e00b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/spectral_synth/model.py @@ -0,0 +1,213 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/spectral_synth/spectral.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/spectral_synth/spectral.py new file mode 100644 index 0000000000000000000000000000000000000000..f7358c3ec944849ea619ef2e73697775b48d408c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/spectral_synth/spectral.py @@ -0,0 +1,27 @@ +"""Locally generated finite stationary Gaussian fields with varied smoothness.""" +import numpy as np + + +def spectral_density(size, length_scale, family): + omega = 2 * np.pi * np.fft.rfftfreq(size) + if family == 3: + density = np.exp(-.5 * (length_scale * omega) ** 2) + else: + nu = [.5, 1.5, 2.5][family] + density = (1 + (length_scale * omega) ** 2 / (2 * nu)) ** (-nu - .5) + # Real FFT has one DC and one Nyquist coefficient, two of each interior bin. + variance = (density[0] + density[-1] + 2 * density[1:-1].sum()) / size + return density / variance + + +def gaussian_residual(n, rng, length_scale=None, family=None): + """The covariance is the discrete inverse Fourier transform of the declared PSD.""" + if length_scale is None: + length_scale = 10 ** rng.uniform(0, 4) + if family is None: + family = int(rng.integers(4)) + size = 1 << (max(16, 4 * n) - 1).bit_length() + density = spectral_density(size, length_scale, family) + white = rng.normal(size=size) + field = np.fft.irfft(np.fft.rfft(white) * np.sqrt(density), n=size) + return field[:n].astype(np.float32) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/spectral_transfer/run.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/spectral_transfer/run.py new file mode 100644 index 0000000000000000000000000000000000000000..b12c03e56acc3688932c441fd31aa259136f1bc1 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/spectral_transfer/run.py @@ -0,0 +1,55 @@ +"""E114: two predeclared coefficient-one spectral-prior transfers; selection only.""" +import hashlib +import json +import os +import subprocess +import time +from pathlib import Path + +R = Path('/workspace/research') +env = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1') +started = time.monotonic() +receipt = {'experiment': 'E114', 'status': 'running', 'steps': []} +receipt_path = R / 'spectral_transfer_receipt.json' + +def run(label, command): + receipt['current_step'] = label + receipt_path.write_text(json.dumps(receipt, indent=2)) + print(json.dumps({'starting': label}), flush=True) + t0 = time.monotonic() + result = subprocess.run(command, env=env, check=False) + receipt['steps'].append({'name': label, 'seconds': time.monotonic()-t0, + 'returncode': result.returncode}) + if result.returncode: + receipt.update(status='failed', seconds=time.monotonic()-started) + receipt_path.write_text(json.dumps(receipt, indent=2)) + raise SystemExit(result.returncode) + +add = R/'spectral_add_delta6k.pt' +replace = R/'spectral_replace_delta6k.pt' +assert not add.exists() and not replace.exists(), 'Refuse to overwrite fixed candidates' +run('add_spectral_delta', ['python3', str(R/'partial_delta/merge.py'), + '--base', str(R/'weekly_slow_ar_delta6k.pt'), + '--candidate', str(R/'runs/spectral_synth/ema006000.pt'), + '--control', str(R/'runs/overflow_control/ema006000.pt'), '--out', str(add)]) +run('remove_old_slow_ar_delta', ['python3', str(R/'partial_delta/merge.py'), + '--base', str(add), '--candidate', str(R/'runs/partial_targets/ema006000.pt'), + '--control', str(R/'runs/long_memory_synth_recovery/ema006000.pt'), '--out', str(replace)]) +receipt['candidate_hashes'] = {p.stem: hashlib.sha256(p.read_bytes()).hexdigest() for p in [add, replace]} +for weights in [add, replace]: + run(weights.stem+'_four_cutoffs', ['python3', str(R/'evaluate_cutoffs.py'), + '--name', weights.stem, '--weights', str(weights), + '--evaluator', str(R/'postloss_inference/evaluate.py')]) + for cutoff, folder in [('valid_screen','evals'), ('valid_backcast','backcast_evals'), + ('valid_backcast2','backcast2_evals'), ('valid_backcast3','backcast3_evals')]: + run(weights.stem+'_'+cutoff+'_record', ['python3', str(R/'direct_v1/record.py'), + str(R/folder/weights.stem/'report.json'), '--label', 'E114 '+weights.stem+' '+cutoff, + '--outcome', 'Fixed coefficient-one spectral transfer; additive and old-slow-AR replacement are the two predeclared ablations. No optimization. Ensemble selection recorded separately.']) + command = ['python3', str(R/'equal_ensemble_probe.py'), '--valid', str(R/cutoff), + '--out', str(R/(weights.stem+'_ensemble_'+cutoff+'.json'))] + for name in [weights.stem, 'patch8_ema6000', 'split_patch_ema12000']: + command += ['--pred', str(R/folder/name)] + run(weights.stem+'_'+cutoff+'_ensemble', command) +receipt.update(status='complete', seconds=time.monotonic()-started) +receipt_path.write_text(json.dumps(receipt, indent=2)) +print(json.dumps(receipt), flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/weekly_synth/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/weekly_synth/check.py new file mode 100644 index 0000000000000000000000000000000000000000..1797c7ca37791de3ac143f64843434ad7beda0ba --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/weekly_synth/check.py @@ -0,0 +1,45 @@ +"""Verify the weekly-only data change without using validation or optimizer steps.""" +import copy +import hashlib +import importlib.util +import json +import sys +import time +from pathlib import Path +import numpy as np + +R=Path('/workspace/research') +sys.path.insert(0,str(R/'weekly_synth')) +from data import Sampler +spec=importlib.util.spec_from_file_location('weekly_control_data',R/'overflow_control/data.py') +control_code=importlib.util.module_from_spec(spec);spec.loader.exec_module(control_code) +started=time.monotonic();seed=467 +candidate=Sampler(R/'packed_sample',seed=seed,source_weights_from=R/'packed_sample') +control=control_code.Sampler(R/'packed_sample',seed=seed,source_weights_from=R/'packed_sample') +rng=np.random.default_rng(seed);rows=synthetic_rows=weekly_rows=0 +for _ in range(120): + c=int(rng.choice([512,1024,2048,4096]));h=int(rng.choice([32,128,512,1024])) + expected=control.sample(64,c,h);actual=candidate.sample(64,c,h) + replacements=np.array(candidate.last_weekly_rows,dtype=int) + unchanged=np.ones(64,dtype=bool);unchanged[replacements]=False + for x,y in zip(expected,actual): + assert np.array_equal(x[unchanged],y[unchanged],equal_nan=True) + assert set(candidate.last_weekly_rows)<=set(candidate.last_synthetic_rows) + assert np.all(actual[2][replacements]==np.array([52,1])) + for x,y in zip(expected[:2],actual[:2]): + assert np.array_equal(np.isfinite(x),np.isfinite(y)) + assert candidate.rng.bit_generator.state==control.rng.bit_generator.state + assert candidate.horizon_rng.bit_generator.state==control.horizon_rng.bit_generator.state + rows+=64;synthetic_rows+=len(candidate.last_synthetic_rows);weekly_rows+=len(replacements) +states={n:copy.deepcopy(v.bit_generator.state) for n,v in vars(candidate).items() if isinstance(v,np.random.Generator)} +next_batch=candidate.sample(64,4096,1024) +for name,state in states.items():getattr(candidate,name).bit_generator.state=state +replayed=candidate.sample(64,4096,1024) +assert all(np.array_equal(x,y,equal_nan=True) for x,y in zip(next_batch,replayed)) +model_hash=hashlib.sha256((R/'weekly_synth/model.py').read_bytes()).hexdigest() +assert model_hash==hashlib.sha256((R/'overflow_control/model.py').read_bytes()).hexdigest() +result=dict(seed=seed,rows=rows,original_synthetic_rows=synthetic_rows,replaced_weekly_rows=weekly_rows, + probability=1/11,original_and_horizon_rng_bitwise_preserved=True,unmodified_rows_bitwise_preserved=True, + finite_masks_unchanged=True,all_numpy_rng_recovery_exact=True,model_sha256=model_hash, + model_bitwise_unchanged=True,seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False) +(R/'weekly_synth_checks.json').write_text(json.dumps(result,indent=2));print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/weekly_synth/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/weekly_synth/data.py new file mode 100644 index 0000000000000000000000000000000000000000..81f0f018cb212a6e2125543e0d4efa2f31b9d8fb --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/weekly_synth/data.py @@ -0,0 +1,113 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + self.weekly_rng=np.random.default_rng(seed+1000003) + self.weekly_probability=1/11 + def synthetic(self,n,p): + # Always consume the control generator first, preserving its complete RNG stream. + original=super().synthetic(n,p) + if self.weekly_rng.random()>=self.weekly_probability: + return original + original_rng=self.rng + try: + self.rng=self.weekly_rng + result=super().synthetic(n,[52,1]) + finally: + self.rng=original_rng + p[:]=[52,1] + self.last_weekly_rows.append(self._synthetic_row) + return result + + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/weekly_synth/launch.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/weekly_synth/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..ef36b1e3de2ad1cc424019100da141536161d07a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/weekly_synth/launch.py @@ -0,0 +1,29 @@ +"""Queue weekly synthetic coverage after robust-normalization training finishes.""" +def main(): + import json + import os + import subprocess + from pathlib import Path + R=Path('/workspace/research') + checks=json.loads((R/'weekly_synth_checks.json').read_text()) + assert checks['original_and_horizon_rng_bitwise_preserved'] and checks['unmodified_rows_bitwise_preserved'] + assert checks['all_numpy_rng_recovery_exact'] and checks['model_bitwise_unchanged'] + env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1') + command=['python3',str(R/'recovery/train.py'),'--code-dir',str(R/'weekly_synth'), + '--packed',str(R/'packed_sample'),'--source-weights-from',str(R/'packed_sample'), + '--out',str(R/'runs/weekly_synth'),'--initialize-from',str(R/'horizon_delta12k.pt'), + '--steps','12000','--batch','64','--lr','.00002','--seed','197','--loss-mode','paired', + '--stop-file',str(R/'weekly_synth.stop')] + with (R/'weekly_synth_queue.log').open('w') as qlog,(R/'weekly_synth_watch.log').open('w') as wlog: + queued=subprocess.Popen(['python3',str(R/'queued_train.py'),'--label','E97 weekly synthetic coverage seed197', + '--log',str(R/'weekly_synth_train.log'),'--receipt',str(R/'weekly_synth_queue.json'), + '--wait-pid','9354','--require-checkpoint',str(R/'runs/robust_normalization/recovery.pt'), + '--',*command],stdout=qlog,stderr=subprocess.STDOUT,env=env) + watch=subprocess.Popen(['python3',str(R/'watch_evaluate.py'),'--run',str(R/'runs/weekly_synth'), + '--evaluator',str(R/'postloss_inference/evaluate.py'),'--name','weekly_synth', + '--steps','1000,3000,6000,12000'],stdout=wlog,stderr=subprocess.STDOUT,env=env) + print({'queue_pid':queued.pid,'watch_pid':watch.pid},flush=True) + result=queued.wait() + if result:watch.terminate() + watch.wait();raise SystemExit(result) +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/weekly_synth/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/weekly_synth/model.py new file mode 100644 index 0000000000000000000000000000000000000000..3532e5063bd8b5013f6b6e35703707ffef66e00b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member0/training/weekly_synth/model.py @@ -0,0 +1,213 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/model_manifest.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/model_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..ed7d82d53ee418c27f3691dc143ede37891db0ef --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/model_manifest.json @@ -0,0 +1,660 @@ +{ + "name": "direct-seasonal-foundation", + "contract": "timeseries-forecast/v1", + "parameters": 36665488, + "pretrained_assets": [], + "sources_used": [ + "gifteval_pretrain/BEIJING_SUBWAY_30MIN", + "gifteval_pretrain/HZMETRO", + "gifteval_pretrain/LOS_LOOP", + "gifteval_pretrain/PEMS03", + "gifteval_pretrain/PEMS04", + "gifteval_pretrain/PEMS07", + "gifteval_pretrain/PEMS08", + "gifteval_pretrain/PEMS_BAY", + "gifteval_pretrain/Q-TRAFFIC", + "gifteval_pretrain/SHMETRO", + "gifteval_pretrain/alibaba_cluster_trace_2018", + "gifteval_pretrain/australian_electricity_demand", + "gifteval_pretrain/azure_vm_traces_2017", + "gifteval_pretrain/bdg-2_bear", + "gifteval_pretrain/bdg-2_fox", + "gifteval_pretrain/bdg-2_panther", + "gifteval_pretrain/bdg-2_rat", + "gifteval_pretrain/bitcoin_with_missing", + "gifteval_pretrain/borealis", + "gifteval_pretrain/borg_cluster_data_2011", + "gifteval_pretrain/buildings_900k", + "gifteval_pretrain/bull", + "gifteval_pretrain/cdc_fluview_ilinet", + "gifteval_pretrain/cdc_fluview_who_nrevss", + "gifteval_pretrain/china_air_quality", + "gifteval_pretrain/cif_2016_12", + "gifteval_pretrain/cif_2016_6", + "gifteval_pretrain/cmip6_2000", + "gifteval_pretrain/cmip6_2005", + "gifteval_pretrain/cmip6_2010", + "gifteval_pretrain/cockatoo", + "gifteval_pretrain/covid19_energy", + "gifteval_pretrain/covid_mobility", + "gifteval_pretrain/elecdemand", + "gifteval_pretrain/elf", + "gifteval_pretrain/era5_2010", + "gifteval_pretrain/era5_2011", + "gifteval_pretrain/era5_2012", + "gifteval_pretrain/era5_2013", + "gifteval_pretrain/era5_2014", + "gifteval_pretrain/era5_2015", + "gifteval_pretrain/era5_2016", + "gifteval_pretrain/era5_2017", + "gifteval_pretrain/era5_2018", + "gifteval_pretrain/extended_web_traffic_with_missing", + "gifteval_pretrain/favorita_sales", + "gifteval_pretrain/favorita_transactions", + "gifteval_pretrain/gfc12_load", + "gifteval_pretrain/gfc14_load", + "gifteval_pretrain/gfc17_load", + "gifteval_pretrain/godaddy", + "gifteval_pretrain/hog", + "gifteval_pretrain/ideal", + "gifteval_pretrain/kaggle_web_traffic_weekly", + "gifteval_pretrain/kdd2022", + "gifteval_pretrain/largest_2017", + "gifteval_pretrain/largest_2018", + "gifteval_pretrain/largest_2019", + "gifteval_pretrain/largest_2020", + "gifteval_pretrain/largest_2021", + "gifteval_pretrain/lcl", + "gifteval_pretrain/london_smart_meters_with_missing", + "gifteval_pretrain/m1_monthly", + "gifteval_pretrain/m1_quarterly", + "gifteval_pretrain/m1_yearly", + "gifteval_pretrain/m5", + "gifteval_pretrain/monash_m3_monthly", + "gifteval_pretrain/monash_m3_other", + "gifteval_pretrain/monash_m3_quarterly", + "gifteval_pretrain/nn5_daily_with_missing", + "gifteval_pretrain/nn5_weekly", + "gifteval_pretrain/oikolab_weather", + "gifteval_pretrain/pdb", + "gifteval_pretrain/project_tycho", + "gifteval_pretrain/residential_load_power", + "gifteval_pretrain/residential_pv_power", + "gifteval_pretrain/rideshare_with_missing", + "gifteval_pretrain/sceaux", + "gifteval_pretrain/smart", + "gifteval_pretrain/solar_power", + "gifteval_pretrain/spain", + "gifteval_pretrain/subseasonal", + "gifteval_pretrain/subseasonal_precip", + "gifteval_pretrain/sunspot_with_missing", + "gifteval_pretrain/taxi_30min", + "gifteval_pretrain/tourism_quarterly", + "gifteval_pretrain/tourism_yearly", + "gifteval_pretrain/traffic_hourly", + "gifteval_pretrain/traffic_weekly", + "gifteval_pretrain/uber_tlc_daily", + "gifteval_pretrain/uber_tlc_hourly", + "gifteval_pretrain/vehicle_trips_with_missing", + "gifteval_pretrain/wiki-rolling_nips", + "gifteval_pretrain/wind_farms_with_missing", + "gifteval_pretrain/wind_power", + "synthetic:both original and sign-reflected orientations of each sampled allowed or locally generated window; paired quantile loss, seed 197", + "synthetic:both original and sign-reflected orientations of each sampled window, seed 197", + "synthetic:independent sign reflection of sampled allowed-corpus and locally generated windows; seeds 43,47,59,79,89,197", + "synthetic:own direct_v1 Fourier seasons, damped trends, AR noise, changepoints and intermittent demand; seeds 23,43,47,59,79,89,197", + "synthetic:own random requested-horizon prefixes, half of rows retain the full horizon and half use a patch-rounded prefix between one-quarter and the full horizon; independent seed 300200" + ], + "weights_sha256": "308389b7217c080af9eb185559d4ee3cafa0f3e0f8c4dd8f5526b68198c89988", + "config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "training_lineage": [ + { + "checkpoint": "runs/patch8/ema006000.pt", + "sha256": "308389b7217c080af9eb185559d4ee3cafa0f3e0f8c4dd8f5526b68198c89988", + "step": 6000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "patch8_initial.pt" + ] + }, + { + "checkpoint": "patch8_initial.pt", + "sha256": "e7da4d47a9cc984a9423296679d7c9127ef2d679be950b9e8d3758e6fca074cc", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "from_checkpoint": "/run-state/workspace/research/horizon_delta12k.pt", + "from_sha256": "22c08571978be31ba57368eb983089a40a44d56d4ae5e17da41afd2a761a258c", + "method": "fold input/query/recency halves by summation; retain first8 output rows; preserve physical position units", + "exact_function_preservation": false + }, + "parents": [ + "horizon_delta12k.pt", + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "horizon_delta12k.pt", + "sha256": "22c08571978be31ba57368eb983089a40a44d56d4ae5e17da41afd2a761a258c", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/runs/confidence_query/ema006000.pt": "0bad97e8994aac49ea173443db0a4fa8d72d33f9eb9e2660f06de75f7f1403eb", + "/workspace/research/runs/horizon_jitter/ema012000.pt": "830179d763916a1065fc615d2c5e22f4a3b5b19390dde707ab0f057e13cadff6", + "/workspace/research/runs/large_corpus_control/ema012000.pt": "7f9ba5e01ac59c51a3b63d3067b442e23e15d0abc51ddbcccdd04d6083ae4add" + }, + "seconds": 1.2663014469435439 + }, + "parents": [ + "runs/confidence_query/ema006000.pt", + "runs/horizon_jitter/ema012000.pt", + "runs/large_corpus_control/ema012000.pt" + ] + }, + { + "checkpoint": "runs/confidence_query/ema006000.pt", + "sha256": "0bad97e8994aac49ea173443db0a4fa8d72d33f9eb9e2660f06de75f7f1403eb", + "step": 6000, + "seed": 89, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 0.0002, + "steps": 6000 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true + }, + "parents": [ + "runs/recency_features/ema024000.pt" + ] + }, + { + "checkpoint": "runs/horizon_jitter/ema012000.pt", + "sha256": "830179d763916a1065fc615d2c5e22f4a3b5b19390dde707ab0f057e13cadff6", + "step": 12000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "partial_target_lengths": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/large_corpus_control/ema012000.pt", + "sha256": "7f9ba5e01ac59c51a3b63d3067b442e23e15d0abc51ddbcccdd04d6083ae4add", + "step": 12000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/recency_features/ema024000.pt", + "sha256": "1530fbb577a87ca4eb39da83d6fee9b8ee5bc924202e021e3a7b56493112f564", + "step": 24000, + "seed": 59, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/patch16_trial/ema006000.pt" + ] + }, + { + "checkpoint": "runs/recency_features/ema012000.pt", + "sha256": "8ccb6870a025e1097331a3a288b1183741a413f3460fbf3352d0c589c6a4394c", + "step": 12000, + "seed": 59, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/patch16_trial/ema006000.pt" + ] + }, + { + "checkpoint": "runs/patch16_trial/ema006000.pt", + "sha256": "0ff54447074e0271d2e331c7d3e6e9e0fdd73353e4d8cef0175ff627385f71c3", + "step": 6000, + "seed": 47, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024 + }, + "parents": [ + "patch16_init.pt" + ] + }, + { + "checkpoint": "patch16_init.pt", + "sha256": "d69531bfde5bf801e7f36c515bf15fd0cae0bd84f7d1479d35f4a7b67f26b508", + "step": 6000, + "seed": 43, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024 + }, + "conversion": { + "from_checkpoint": "/run-state/workspace/research/runs/large_sign/ema006000.pt", + "from_sha256": "96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547", + "method": "fold input/query halves by summation; retain first 16 output rows; preserve physical positional units" + }, + "parents": [ + "runs/large_sign/ema006000.pt" + ] + }, + { + "checkpoint": "runs/large_sign/ema006000.pt", + "sha256": "96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547", + "step": 6000, + "seed": 43, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 32, + "max_context": 4096, + "max_horizon": 1024 + }, + "parents": [ + "runs/direct_large/step024000.pt" + ] + }, + { + "checkpoint": "runs/direct_large/step024000.pt", + "sha256": "b7e4f38aebcd2cf38ce484edaad8d19851317fb3b8df485e2faa0d0423cbcb48", + "step": 24000, + "seed": 23, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 128, + "lr": 0.0002, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 32, + "max_context": 4096, + "max_horizon": 1024 + }, + "initialization": "random initialization in this workspace" + } + ], + "symmetric_averaging": true, + "seasonal_gate": { + "variance_ratio_threshold": 0.25, + "maximum_weight": 0.98, + "cycles_averaged": 4, + "template_mode": "aligned", + "amplitude_ratio_clip": [ + 0.5, + 2.0 + ], + "latest_cycle_minimum_coverage": 0.75, + "variance_noise_correction": "mean squared seasonal differences / 2" + }, + "continuity": { + "decay_steps": 24, + "variance_ratio_threshold": 0.5, + "maximum_weight": 0.95, + "lookback": 512, + "slope_median_differences": 8 + }, + "notes": "All training lineage originates from random initialization here, using only the declared corpus and locally generated series. Validation was used only for selection and diagnostics. Context transformations are fixed formulas; there is no inference-time fitting or parameter adaptation.", + "runtime_code_sha256": { + "model.py": "c27748fa4b1186b513f76eca26052753b8dcd1794994e5989addaf371ca70f2e", + "infer.sh": "5fe66b4fe9a4787285d830cfd96975701e97286a75ba7c3687bd8891475edf68", + "continuity.py": "dbb08d2229ad80ad00f638b0b9f2f6ca13c663e0fd6730058e5fee8ff54545d5", + "ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "zero_mass.py": "f079d509009bcda409b80eb64467c869b838cfbab11b2bd4c660c2875b6642fe", + "seasonal.py": "b946e63048196ab5ea8b249137d48c80d8510943caccd0f180e4fb86d9b24b37", + "predict.py": "9bde896945a2cd8f892e7eeb6328ed2dfda09293532f3a4a64d929c9943614ef" + }, + "final_training_stage": { + "trainable_scope": "all parameters", + "sign_loss": "paired", + "learning_rate_multipliers": {} + }, + "trend_summary": { + "fixed_averaging_width": 128, + "matches_all_pretraining_context_widths": true, + "independent_of_batch_padding": true + }, + "zero_mass_projection": { + "threshold_in_context_standard_deviations": 0.4, + "nonnegative_context_required": true, + "minimum_exact_zeros": 4, + "minimum_zero_fraction": 0.1, + "context_cap": 4096 + }, + "recency_features": { + "query_projection_parameters": 16384, + "latest_vs_four_cycle_level": true, + "amplitude_ratio_clip": [ + 0.5, + 2.0 + ], + "minimum_observed_cycles": 3 + }, + "confidence_features": { + "query_projection_parameters": 3072, + "backbone_frozen_during_projection_training": true, + "training_objective": "weighted quantile and median loss after averaging both sign orientations", + "statistics": [ + "mean absolute difference", + "root mean square difference" + ], + "lags": "one and the two frequency-derived periods", + "lookback": "512 for lag one; eight cycles for seasonal lags", + "minimum_valid_pairs": 8, + "insufficient_pair_defaults": [ + 1, + 1.4142135623730951 + ], + "statistic_clip": 10, + "transform": "log1p", + "stage_scope": "Frozen-backbone details refer to projection introduction; subsequent updates are recorded in training_lineage.training_settings." + }, + "partial_target_training": { + "available_horizon": "last finite training-label position rounded up to the patch boundary", + "decoder_future_key_mask": true, + "per_row_horizon_metadata": true, + "inference_uses_requested_horizon_only": true + }, + "training_provenance_code_sha256": { + "confidence_query/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "confidence_query/model.py": "b4f11ba2018e2b50879cdc33acf0138301548971508b58035a7c96a29aaa6f2d", + "confidence_query/train.py": "fc8a7555a5a6b0a6f91e80ac8cc9cbbfddaa2b26468c57f49dfb17671b22ce93", + "direct_large/data.py": "6e6db217936f8dd79380d2ceff3eaa8598a44f1b60b17acae7bfde2363116847", + "direct_large/evaluate.py": "eaea99e8cd44c9f7c70a45fa9abf51354ae5449dbad273fcb55e48ad02652223", + "direct_large/model.py": "146d93a3f95b13bda8b1b437bc36621b91356cf946e94f62999f89e7fb348071", + "direct_large/pack.py": "3bcc4ce9eb3361ad741ceebd7efce7a2fb86fb49543f52c72aabd0e3e8cd17ce", + "direct_large/predict.py": "930a9f18f9f5da47c03859698c9d2f5567d1e1c73fd61edac1ed20b3a6f9bb50", + "direct_large/publish.py": "3c167f33e8571731c26f1cb70168eda54ef9cb4c76423dfd374240b75ca5f106", + "direct_large/record.py": "b3b00b0ed14bc3af00c7b1ad97195238ecb8f06e96bc41f0c07913bc3f6ed949", + "direct_large/train.py": "b9ad6b2adddeaf12961b529d6535dd33f6d044a31979b5c9e49dceafbadd3ac0", + "direct_large/ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "direct_large/validation_subset.py": "8d3eb9d3f3aa124368761ef402ff066935c0be31a62b25b8551a45dcb922e28d", + "full_paired/check.py": "90ac1c78846439d51ab8acd62a19bd536c7c394bd02e94f6d5ff17c0af8bd116", + "full_paired/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "full_paired/model.py": "c27748fa4b1186b513f76eca26052753b8dcd1794994e5989addaf371ca70f2e", + "horizon_jitter/data.py": "5044cf648323420095ed6058d29f837c07ff5559b606df8b00cc8d1e95c8b58e", + "horizon_jitter/model.py": "186bb282236f23cc665a012194d26e58f51004c680393352ec053f5308f1240f", + "horizon_jitter/train.py": "4e9cbca1293f18f7eea2c72dba127815c0934a13c86e8f6cc881a749676d41a6", + "large_corpus/data.py": "27c078cb0ed085717a364f556b5ff976fd803d5af37612cf3a03a0a3ca12a678", + "large_corpus/model.py": "e3a1bc01e89a0d6d750ede2cc969272ad01e1ca580b174af7dee00db029f1cf7", + "large_corpus/train.py": "3baca16c3945e6ef241ccbc9c13644539e3c265f71095cbbaa61a3d338e4fafe", + "large_sign/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "large_sign/evaluate.py": "eaea99e8cd44c9f7c70a45fa9abf51354ae5449dbad273fcb55e48ad02652223", + "large_sign/model.py": "3fff6445a1982a1b3c92f06a9b5f1bb627dda6a291b0b2364bcfb1a6457830d7", + "large_sign/pack.py": "3bcc4ce9eb3361ad741ceebd7efce7a2fb86fb49543f52c72aabd0e3e8cd17ce", + "large_sign/predict.py": "930a9f18f9f5da47c03859698c9d2f5567d1e1c73fd61edac1ed20b3a6f9bb50", + "large_sign/publish.py": "3c167f33e8571731c26f1cb70168eda54ef9cb4c76423dfd374240b75ca5f106", + "large_sign/record.py": "b3b00b0ed14bc3af00c7b1ad97195238ecb8f06e96bc41f0c07913bc3f6ed949", + "large_sign/train.py": "a597f40ab87cce04e96dc654d12e56cdf40ffd87f00034d8bc4d56dff4eb7c68", + "large_sign/ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "large_sign/validation_subset.py": "8d3eb9d3f3aa124368761ef402ff066935c0be31a62b25b8551a45dcb922e28d", + "partial_delta/merge.py": "63984a0f46f7d48817037f5bf5a1c9319e45a9b1924cde62c667ac49ce47532e", + "partial_targets/data.py": "27c078cb0ed085717a364f556b5ff976fd803d5af37612cf3a03a0a3ca12a678", + "partial_targets/model.py": "186bb282236f23cc665a012194d26e58f51004c680393352ec053f5308f1240f", + "partial_targets/train.py": "3baca16c3945e6ef241ccbc9c13644539e3c265f71095cbbaa61a3d338e4fafe", + "patch16/convert.py": "11e1d30100ab25311020ac1f4ab8227ec66156836df5de613300867977091c45", + "patch16/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "patch16/evaluate.py": "eaea99e8cd44c9f7c70a45fa9abf51354ae5449dbad273fcb55e48ad02652223", + "patch16/model.py": "8031c597b354eb2cf464140bee40c3ec8dff86c775b5c55c5ce910302b443582", + "patch16/pack.py": "3bcc4ce9eb3361ad741ceebd7efce7a2fb86fb49543f52c72aabd0e3e8cd17ce", + "patch16/predict.py": "930a9f18f9f5da47c03859698c9d2f5567d1e1c73fd61edac1ed20b3a6f9bb50", + "patch16/publish.py": "3c167f33e8571731c26f1cb70168eda54ef9cb4c76423dfd374240b75ca5f106", + "patch16/record.py": "b3b00b0ed14bc3af00c7b1ad97195238ecb8f06e96bc41f0c07913bc3f6ed949", + "patch16/train.py": "3156710f76111a31447cbe638ee27fe2811d060917aa083aab0b5134d98accf8", + "patch16/ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "patch16/validation_subset.py": "8d3eb9d3f3aa124368761ef402ff066935c0be31a62b25b8551a45dcb922e28d", + "patch8/convert.py": "9edaa0c8349310b7419d649fb4f21dd3ddb9067ebe984d5df3701a234be73780", + "patch8/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "patch8/memory_check.py": "78e8e5cca960bf1225ec0104980363c82f4c3c13c2d77ed154cea37a5b6f3fd1", + "patch8/model.py": "c27748fa4b1186b513f76eca26052753b8dcd1794994e5989addaf371ca70f2e", + "recency_features/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "recency_features/model.py": "e3a1bc01e89a0d6d750ede2cc969272ad01e1ca580b174af7dee00db029f1cf7", + "recency_features/train.py": "a654b9a27b6c27141e1d4e517ab28fcae3f2c23d061742fa2f6c01e3d23c8a00", + "recovery/capacity_curves.py": "2bdc6635705b70a868e115cd13eb529563acacf6f47c71f250a50dce8e943be4", + "recovery/exposure_audit.py": "54c194a626b8876ece84686b39b22360155c9fada7248a393ca9b7d6ee38002b", + "recovery/relaunch_20261022b.py": "f90ddd77928a793c8e151ba74cfa9cc84c8aefad0c0d943a833c74bc07b79313", + "recovery/relaunch_20261023.py": "a4c40c5674b0d05cfe9bb1fffe907f02dec16c53cbddb8b86efbba1b96649097", + "recovery/schedules.py": "7748fd6b2bbbe64037472faf7e6583d03cf339138d2f3c07b1bac9e65bf2d4f5", + "recovery/snapshot.py": "0f241a7e139e47ffff7efea40572205fd84c12efe6fb3c2dccd87c50d678a6c3", + "recovery/train.py": "63bee736565af670877b4cd7c75015fab06a18c66bbe132b0bb3faff5ebd80c7" + } +} diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/confidence_query/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/confidence_query/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/confidence_query/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/confidence_query/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/confidence_query/model.py new file mode 100644 index 0000000000000000000000000000000000000000..b881039b3752b3396e06415a8d01d24956fa29a7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/confidence_query/model.py @@ -0,0 +1,190 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + if self.recency is not None: + pos=torch.arange(c,device=z.device)[None,:];extras=[] + for j in range(2): + period=periods[:,j:j+1] + recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + n=ctx.shape[0] + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1]) + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/confidence_query/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/confidence_query/train.py new file mode 100644 index 0000000000000000000000000000000000000000..fd9d2a3a0502cee1a67c41c832266c7f87cc5a80 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/confidence_query/train.py @@ -0,0 +1,54 @@ +"""Train only confidence-query features on a frozen model, using paired-sign forecast loss.""" +import argparse,json,math,time,os +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) +ap.add_argument('--initialize-from',required=True);ap.add_argument('--steps',type=int,default=6000) +ap.add_argument('--batch',type=int,default=128);ap.add_argument('--lr',type=float,default=2e-4) +ap.add_argument('--seed',type=int,default=89);ap.add_argument('--save-every',type=int,default=1000);a=ap.parse_args() +torch.set_num_threads(1);torch.manual_seed(a.seed);torch.backends.cuda.matmul.allow_tf32=True +out=Path(a.out);out.mkdir(parents=True,exist_ok=True) +ck=torch.load(a.initialize_from,map_location='cpu',weights_only=False) +config={**ck['config'],'confidence_features':True};model=DirectForecaster(**config).cuda() +missing,unexpected=model.load_state_dict(ck['model'],strict=False) +assert not unexpected and all(k.startswith('confidence.') for k in missing) +for name,param in model.named_parameters():param.requires_grad_(name.startswith('confidence.')) +params=[p for p in model.parameters() if p.requires_grad] +opt=torch.optim.AdamW(params,lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) +ema={k:v.detach().clone() for k,v in model.state_dict().items()};sampler=Sampler(a.packed,seed=a.seed) +(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)) +rng=np.random.default_rng(a.seed) +def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) +def save(step): + for prefix,weights in [('step',model.state_dict()),('ema',ema)]: + state={'model':weights,'config':model.config,'step':step,'args':vars(a),'ema':prefix=='ema'} + path=out/f'{prefix}{step:06d}.pt';torch.save(state,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) +save(0);pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] +for step in range(1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch);x,y,p=[torch.from_numpy(x).cuda() for x in arrays] + lr=a.lr*min(1,step/200)*(.2+.8*.5*(1+math.cos(math.pi*step/a.steps))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(params,1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items(): + if k.startswith('confidence.'):ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + if step%a.save_every==0 or step==a.steps:save(step) +pool.shutdown() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/direct_large/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/direct_large/data.py new file mode 100644 index 0000000000000000000000000000000000000000..2378e33d7352ba5ad97d566148782e63e64b367c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/direct_large/data.py @@ -0,0 +1,71 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + return ctx,tgt,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/direct_large/evaluate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/direct_large/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..05f086d4d84def4a48165f9e65d2948877675e56 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/direct_large/evaluate.py @@ -0,0 +1,16 @@ +import sys,json,argparse,time,hashlib +from pathlib import Path +import torch +from predict import load_model,run +sys.path.insert(0,'/workspace/evaluation') +from score import score,json_safe + +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);ap.add_argument('--valid',default='/workspace/research/valid_screen');ap.add_argument('--baseline',default='/workspace/research/valid_screen/baseline.json');a=ap.parse_args() +torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cuda.matmul.allow_tf32=False +t0=time.time();out=Path(a.out);v=Path(a.valid) +run(load_model(a.weights),v/'input',out) +base=json.loads(Path(a.baseline).read_text())['configs'] +rep=score(v/'truth',out,base) +rep['checkpoint_sha256']=hashlib.sha256(Path(a.weights).read_bytes()).hexdigest();rep['eval_seconds']=time.time()-t0 +(out/'report.json').write_text(json.dumps(json_safe(rep),indent=1)) +print(json.dumps({k:rep[k] for k in ('skill_score','rel_mase_gmean','rel_wql_gmean','n_failed','groups','eval_seconds')},indent=1)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/direct_large/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/direct_large/model.py new file mode 100644 index 0000000000000000000000000000000000000000..7a224cc12a159446a1e427b2052b53d1d1f7e83e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/direct_large/model.py @@ -0,0 +1,142 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional(torch.arange(-nt,0,device=z.device),self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + q=self.query(base.reshape(b,h//p,p*9))+positional(torch.arange(h//p,device=z.device),self.d)[None]+emb + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + pin=torch.maximum(levels*err,(levels-1)*err).mean(-1) + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + return per.mean() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/direct_large/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/direct_large/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/direct_large/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/direct_large/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/direct_large/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..e20c6630475d6b4fa6906eb4ed9454b7b5aeec2c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/direct_large/predict.py @@ -0,0 +1,43 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):q=model.predict(x,p,h).float().cpu().numpy() + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/direct_large/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/direct_large/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf95c9aec5936076b881c340edb960786f2d40d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/direct_large/publish.py @@ -0,0 +1,31 @@ +"""Assemble a relocatable package, then atomically exchange complete directories.""" +import json,os,shutil,ctypes,hashlib,argparse +from pathlib import Path +import torch +HERE=Path(__file__).resolve().parent + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',default='/workspace/submission');ap.add_argument('--report',required=True);ap.add_argument('--experiments',default=str(HERE/'EXPERIMENTS.md'));a=ap.parse_args() + final=Path(a.out);staging=final.parent/f'.{final.name}-staging-{os.getpid()}' + shutil.rmtree(staging,ignore_errors=True);staging.mkdir(parents=True) + for file in ('model.py','predict.py','infer.sh','ts_io.py'): + shutil.copy(HERE/file,staging/file) + shutil.copy(a.weights,staging/'weights.pt');shutil.copy('/opt/runtime/requirements.txt',staging/'requirements.txt') + ck=torch.load(a.weights,map_location='cpu',weights_only=False);digest=hashlib.sha256((staging/'weights.pt').read_bytes()).hexdigest() + sources=json.loads(Path('/workspace/research/packed_sample/meta.json').read_text())['dirs'] + manifest={'name':'direct-seasonal-quantile-v1','contract':'timeseries-forecast/v1','parameters':sum(x.numel() for x in ck['model'].values()),'pretrained_assets':[],'sources_used':[f'gifteval_pretrain/{d}' for d in sources]+['synthetic:direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; data.py generator seed 17'],'weights_sha256':digest,'training_step':ck['step'],'config':ck['config'],'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.'} + (staging/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') + (staging/'config.json').write_text(json.dumps(ck['config'],indent=2)+'\n') + shutil.copy(a.experiments,staging/'EXPERIMENTS.md');shutil.copy(a.report,staging/'validation_report.json') + # Include generator/sampler provenance, which is not imported by inference. + (staging/'provenance').mkdir() + for file in ('pack.py','data.py','train.py'):shutil.copy(HERE/file,staging/'provenance'/file) + (staging/'README.md').write_text('# Direct seasonal quantile foundation forecaster\n\nRun `bash infer.sh INPUT_DIR OUTPUT_DIR`. This package contains all inference assets and uses only its supplied input directory. The 6.76M 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.\n\nThe 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.\n') + if final.exists(): + libc=ctypes.CDLL(None,use_errno=True) + if libc.renameat2(-100,os.fsencode(staging),-100,os.fsencode(final),2):raise OSError(ctypes.get_errno(),os.strerror(ctypes.get_errno())) + shutil.rmtree(staging) + else:os.replace(staging,final) + print(json.dumps(manifest,indent=1)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/direct_large/record.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/direct_large/record.py new file mode 100644 index 0000000000000000000000000000000000000000..1850a33f46fa3ee4d78cac4a5d6152404801a131 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/direct_large/record.py @@ -0,0 +1,9 @@ +import argparse,json,math +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('report');ap.add_argument('--label',required=True);ap.add_argument('--outcome',default='Screened for model selection.');a=ap.parse_args() +r=json.loads(Path(a.report).read_text());p=Path(__file__).with_name('EXPERIMENTS.md') +lines=[f'\n## {a.label}',f'- Checkpoint SHA-256: `{r.get("checkpoint_sha256","see model_manifest.json")}`.',f'- Evaluation: {r["n_configs"]} configurations, {r["n_instances"]} instances, {r["n_failed"]} failed configurations; {r.get("eval_seconds","not separately timed")} seconds.',f'- Overall skill {r["skill_score"]:.6f}; relative MASE {r["rel_mase_gmean"]:.6f}; relative WQL {r["rel_wql_gmean"]:.6f}.'] +for group,entries in r['groups'].items(): + lines.append(f'- {group} skill: '+', '.join(f'{k}={1-math.sqrt(v["rel_mase_gmean"]*v["rel_wql_gmean"]):.4f}' for k,v in entries.items())+'.') +lines.append('- Outcome: '+a.outcome) +with p.open('a') as f:f.write('\n'.join(lines)+'\n') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/direct_large/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/direct_large/train.py new file mode 100644 index 0000000000000000000000000000000000000000..a2ccc736bfef804259199a2dd315347d9854b680 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/direct_large/train.py @@ -0,0 +1,67 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(6);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/direct_large/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/direct_large/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/direct_large/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/direct_large/validation_subset.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/direct_large/validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..4df83e69c4f9a3365955e5d17ffcfc0af71372b7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/direct_large/validation_subset.py @@ -0,0 +1,18 @@ +"""Model-selection-only subset spanning all 97 configurations, seed 2026.""" +import sys,json,copy +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +import ts_io + +root=Path('/workspace/data/valid');out=Path('/workspace/research/valid_screen') +idx=json.loads((root/'input/index.json').read_text());new=copy.deepcopy(idx);rng=np.random.default_rng(2026) +for cfg in new['configs']: + cid=cfg['config_id'];case=ts_io.CaseFile(root/'input/cases'/f'{cid}.h5') + ids=np.sort(rng.choice(case.n,min(case.n,192),replace=False)) + ts_io.write_case_subset(case,ids,out/'input/cases'/f'{cid}.h5') + lab,se,meta=ts_io.read_truth_file(root/'truth/cases'/f'{cid}.h5') + ts_io.write_truth_file(out/'truth/cases'/f'{cid}.h5',lab[ids],se[ids],meta) + cfg['n_instances']=len(ids);case.close() +for kind in ('input','truth'):(out/kind/'index.json').write_text(json.dumps(new,indent=1)) +print('screen instances',sum(c['n_instances'] for c in new['configs'])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/full_paired/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/full_paired/check.py new file mode 100644 index 0000000000000000000000000000000000000000..fda928e16338305fd9912f7bc08cacff58bd8aa4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/full_paired/check.py @@ -0,0 +1,34 @@ +import importlib.util,json,time +from pathlib import Path +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +r=Path('/workspace/research');torch.set_num_threads(1);torch.manual_seed(197);start=time.monotonic() +ck=torch.load(r/'horizon_delta12k.pt',map_location='cpu',weights_only=False) +spec=importlib.util.spec_from_file_location('parent_model',r/'confidence_inference/model.py') +old=importlib.util.module_from_spec(spec);spec.loader.exec_module(old) +parent=old.DirectForecaster(**ck['config']);parent.load_state_dict(ck['model']) +m=DirectForecaster(**ck['config']);m.load_state_dict(ck['model']) +x=torch.randn(4,512);x[0,:50]=float('nan');p=torch.tensor([[24,168]]*4);y=torch.randn(4,128);y[0,32:]=float('nan') +with torch.inference_mode(): + assert all(torch.equal(a,b) for a,b in zip(m(x,p,48),parent(x,p,48))) + short=m(x,p,32)[0];long=m(x,p,128,forecast_lengths=torch.full((4,),32))[0][:,:32] + assert torch.allclose(short,long,atol=3e-6,rtol=1e-6),(short-long).abs().max() + paired=float(loss_fn(m,x,y,p,paired=True));reverse=float(loss_fn(m,-x,-y,p,paired=True)) + assert abs(paired-reverse)<1e-7,(paired,reverse) +a=Sampler(r/'packed_sample',197);b=Sampler(r/'packed_sample',197) +for c,h in [(512,32),(4096,1024)]: + assert all(np.array_equal(v,w,equal_nan=True) for v,w in zip(a.sample(16,c,h),b.sample(16,c,h))) +assert a.rng.bit_generator.state==b.rng.bit_generator.state and a.horizon_rng.bit_generator.state==b.horizon_rng.bit_generator.state +cpu=time.monotonic()-start;del parent,ck,a,b +m=m.cuda();ema={k:v.detach().clone() for k,v in m.state_dict().items()} +moments=[torch.zeros_like(v) for v in m.parameters() for _ in range(2)] +torch.backends.cuda.matmul.allow_tf32=True;torch.cuda.reset_peak_memory_stats();start=time.monotonic() +x=torch.randn(64,4096,device='cuda');y=torch.randn(64,1024,device='cuda');p=torch.tensor([[24,168]]*64,device='cuda') +with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(m,x,y,p,paired=True) +loss.backward();torch.cuda.synchronize() +assert torch.isfinite(loss) and all(v.grad is not None and torch.isfinite(v.grad).all() for v in m.parameters()) +z={'cpu_seconds':cpu,'initial_forecast_bitwise_parent':True,'unused_future_tokens_do_not_change_requested_prefix':True,'paired_loss_sign_symmetric':True,'matched_sampler_main_and_horizon_rng':True,'gpu_fixture_seconds':time.monotonic()-start,'allocated_mib':torch.cuda.max_memory_allocated()/2**20,'reserved_mib':torch.cuda.max_memory_reserved()/2**20,'optimizer_updates':0} +(r/'full_paired_checks.json').write_text(json.dumps(z,indent=2));print(json.dumps(z),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/full_paired/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/full_paired/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/full_paired/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/full_paired/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/full_paired/model.py new file mode 100644 index 0000000000000000000000000000000000000000..dedcdff4698028a8ba655865f8425d0dc3ef0dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/full_paired/model.py @@ -0,0 +1,204 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/horizon_jitter/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/horizon_jitter/data.py new file mode 100644 index 0000000000000000000000000000000000000000..3d632af7e96a71f30b7964a2b3fd73bc1c3f3f3e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/horizon_jitter/data.py @@ -0,0 +1,86 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/horizon_jitter/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/horizon_jitter/model.py new file mode 100644 index 0000000000000000000000000000000000000000..4ffe50d9aadf21d73949e2052ceb7f3642bf65d3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/horizon_jitter/model.py @@ -0,0 +1,180 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(ctx,periods,target.shape[-1],forecast_lengths=lengths) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/horizon_jitter/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/horizon_jitter/train.py new file mode 100644 index 0000000000000000000000000000000000000000..768d33da4421b24bd760d7d9680d0c2cd9bd84e4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/horizon_jitter/train.py @@ -0,0 +1,74 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler,truncate_targets + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + horizon_rng=np.random.default_rng(a.seed+startstep+300003) + def nextbatch(): + 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])) + return truncate_targets(sampler.sample(a.batch,c,h),horizon_rng,a.patch) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_corpus/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_corpus/data.py new file mode 100644 index 0000000000000000000000000000000000000000..a51e912d3c4b63a3ec0cd85133bf0e7aa3429569 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_corpus/data.py @@ -0,0 +1,73 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_corpus/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_corpus/model.py new file mode 100644 index 0000000000000000000000000000000000000000..f8271c5b0bf9a5edb961e1c7839761fe50a2e40b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_corpus/model.py @@ -0,0 +1,171 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024,recency_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + if self.recency is not None: + pos=torch.arange(c,device=z.device)[None,:];extras=[] + for j in range(2): + period=periods[:,j:j+1] + recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_corpus/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_corpus/train.py new file mode 100644 index 0000000000000000000000000000000000000000..2e77612e443d78dd80bcb6a0cc6d01169f61a3a4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_corpus/train.py @@ -0,0 +1,73 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_sign/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_sign/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_sign/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_sign/evaluate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_sign/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..05f086d4d84def4a48165f9e65d2948877675e56 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_sign/evaluate.py @@ -0,0 +1,16 @@ +import sys,json,argparse,time,hashlib +from pathlib import Path +import torch +from predict import load_model,run +sys.path.insert(0,'/workspace/evaluation') +from score import score,json_safe + +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);ap.add_argument('--valid',default='/workspace/research/valid_screen');ap.add_argument('--baseline',default='/workspace/research/valid_screen/baseline.json');a=ap.parse_args() +torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cuda.matmul.allow_tf32=False +t0=time.time();out=Path(a.out);v=Path(a.valid) +run(load_model(a.weights),v/'input',out) +base=json.loads(Path(a.baseline).read_text())['configs'] +rep=score(v/'truth',out,base) +rep['checkpoint_sha256']=hashlib.sha256(Path(a.weights).read_bytes()).hexdigest();rep['eval_seconds']=time.time()-t0 +(out/'report.json').write_text(json.dumps(json_safe(rep),indent=1)) +print(json.dumps({k:rep[k] for k in ('skill_score','rel_mase_gmean','rel_wql_gmean','n_failed','groups','eval_seconds')},indent=1)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_sign/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_sign/model.py new file mode 100644 index 0000000000000000000000000000000000000000..60aeb14b5f4fa298521ddce8a3276d076c1bb631 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_sign/model.py @@ -0,0 +1,154 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional(torch.arange(-nt,0,device=z.device),self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + q=self.query(base.reshape(b,h//p,p*9))+positional(torch.arange(h//p,device=z.device),self.d)[None]+emb + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_sign/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_sign/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_sign/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_sign/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_sign/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..e20c6630475d6b4fa6906eb4ed9454b7b5aeec2c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_sign/predict.py @@ -0,0 +1,43 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):q=model.predict(x,p,h).float().cpu().numpy() + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_sign/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_sign/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf95c9aec5936076b881c340edb960786f2d40d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_sign/publish.py @@ -0,0 +1,31 @@ +"""Assemble a relocatable package, then atomically exchange complete directories.""" +import json,os,shutil,ctypes,hashlib,argparse +from pathlib import Path +import torch +HERE=Path(__file__).resolve().parent + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',default='/workspace/submission');ap.add_argument('--report',required=True);ap.add_argument('--experiments',default=str(HERE/'EXPERIMENTS.md'));a=ap.parse_args() + final=Path(a.out);staging=final.parent/f'.{final.name}-staging-{os.getpid()}' + shutil.rmtree(staging,ignore_errors=True);staging.mkdir(parents=True) + for file in ('model.py','predict.py','infer.sh','ts_io.py'): + shutil.copy(HERE/file,staging/file) + shutil.copy(a.weights,staging/'weights.pt');shutil.copy('/opt/runtime/requirements.txt',staging/'requirements.txt') + ck=torch.load(a.weights,map_location='cpu',weights_only=False);digest=hashlib.sha256((staging/'weights.pt').read_bytes()).hexdigest() + sources=json.loads(Path('/workspace/research/packed_sample/meta.json').read_text())['dirs'] + manifest={'name':'direct-seasonal-quantile-v1','contract':'timeseries-forecast/v1','parameters':sum(x.numel() for x in ck['model'].values()),'pretrained_assets':[],'sources_used':[f'gifteval_pretrain/{d}' for d in sources]+['synthetic:direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; data.py generator seed 17'],'weights_sha256':digest,'training_step':ck['step'],'config':ck['config'],'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.'} + (staging/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') + (staging/'config.json').write_text(json.dumps(ck['config'],indent=2)+'\n') + shutil.copy(a.experiments,staging/'EXPERIMENTS.md');shutil.copy(a.report,staging/'validation_report.json') + # Include generator/sampler provenance, which is not imported by inference. + (staging/'provenance').mkdir() + for file in ('pack.py','data.py','train.py'):shutil.copy(HERE/file,staging/'provenance'/file) + (staging/'README.md').write_text('# Direct seasonal quantile foundation forecaster\n\nRun `bash infer.sh INPUT_DIR OUTPUT_DIR`. This package contains all inference assets and uses only its supplied input directory. The 6.76M 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.\n\nThe 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.\n') + if final.exists(): + libc=ctypes.CDLL(None,use_errno=True) + if libc.renameat2(-100,os.fsencode(staging),-100,os.fsencode(final),2):raise OSError(ctypes.get_errno(),os.strerror(ctypes.get_errno())) + shutil.rmtree(staging) + else:os.replace(staging,final) + print(json.dumps(manifest,indent=1)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_sign/record.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_sign/record.py new file mode 100644 index 0000000000000000000000000000000000000000..1850a33f46fa3ee4d78cac4a5d6152404801a131 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_sign/record.py @@ -0,0 +1,9 @@ +import argparse,json,math +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('report');ap.add_argument('--label',required=True);ap.add_argument('--outcome',default='Screened for model selection.');a=ap.parse_args() +r=json.loads(Path(a.report).read_text());p=Path(__file__).with_name('EXPERIMENTS.md') +lines=[f'\n## {a.label}',f'- Checkpoint SHA-256: `{r.get("checkpoint_sha256","see model_manifest.json")}`.',f'- Evaluation: {r["n_configs"]} configurations, {r["n_instances"]} instances, {r["n_failed"]} failed configurations; {r.get("eval_seconds","not separately timed")} seconds.',f'- Overall skill {r["skill_score"]:.6f}; relative MASE {r["rel_mase_gmean"]:.6f}; relative WQL {r["rel_wql_gmean"]:.6f}.'] +for group,entries in r['groups'].items(): + lines.append(f'- {group} skill: '+', '.join(f'{k}={1-math.sqrt(v["rel_mase_gmean"]*v["rel_wql_gmean"]):.4f}' for k,v in entries.items())+'.') +lines.append('- Outcome: '+a.outcome) +with p.open('a') as f:f.write('\n'.join(lines)+'\n') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_sign/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_sign/train.py new file mode 100644 index 0000000000000000000000000000000000000000..d089166fb1612ddf4955fcd2f096cb0b33624dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_sign/train.py @@ -0,0 +1,70 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(3);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_sign/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_sign/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_sign/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_sign/validation_subset.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_sign/validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..4df83e69c4f9a3365955e5d17ffcfc0af71372b7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/large_sign/validation_subset.py @@ -0,0 +1,18 @@ +"""Model-selection-only subset spanning all 97 configurations, seed 2026.""" +import sys,json,copy +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +import ts_io + +root=Path('/workspace/data/valid');out=Path('/workspace/research/valid_screen') +idx=json.loads((root/'input/index.json').read_text());new=copy.deepcopy(idx);rng=np.random.default_rng(2026) +for cfg in new['configs']: + cid=cfg['config_id'];case=ts_io.CaseFile(root/'input/cases'/f'{cid}.h5') + ids=np.sort(rng.choice(case.n,min(case.n,192),replace=False)) + ts_io.write_case_subset(case,ids,out/'input/cases'/f'{cid}.h5') + lab,se,meta=ts_io.read_truth_file(root/'truth/cases'/f'{cid}.h5') + ts_io.write_truth_file(out/'truth/cases'/f'{cid}.h5',lab[ids],se[ids],meta) + cfg['n_instances']=len(ids);case.close() +for kind in ('input','truth'):(out/kind/'index.json').write_text(json.dumps(new,indent=1)) +print('screen instances',sum(c['n_instances'] for c in new['configs'])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/partial_delta/merge.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/partial_delta/merge.py new file mode 100644 index 0000000000000000000000000000000000000000..3dde47d52d25ed2b013942b3887f1bf686e42ed8 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/partial_delta/merge.py @@ -0,0 +1,16 @@ +"""Apply the difference of two matched, locally trained checkpoints to our selected model.""" +import argparse,torch,hashlib,json,time +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('--base',required=True);ap.add_argument('--candidate',required=True);ap.add_argument('--control',required=True);ap.add_argument('--out',required=True);a=ap.parse_args() +torch.set_num_threads(1);start=time.monotonic() +base=torch.load(a.base,map_location='cpu',weights_only=False);candidate=torch.load(a.candidate,map_location='cpu',weights_only=False);control=torch.load(a.control,map_location='cpu',weights_only=False) +assert set(candidate['model'])==set(control['model']) +weights={k:v.clone() for k,v in base['model'].items()} +for k in candidate['model']: + assert k in weights and weights[k].shape==candidate['model'][k].shape==control['model'][k].shape + weights[k].add_(candidate['model'][k]-control['model'][k]) +assert all(torch.isfinite(v).all() for v in weights.values()) +parents=[a.base,a.candidate,a.control] +conversion={'method':'matched training delta','formula':'base + candidate - control','coefficient':1.0,'parent_hashes':{p:hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in parents},'seconds':time.monotonic()-start} +ck={'model':weights,'config':base['config'],'step':0,'args':{'packed':base['args']['packed']},'parent_checkpoints':parents,'conversion':conversion} +torch.save(ck,a.out);print(json.dumps(conversion)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/partial_targets/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/partial_targets/data.py new file mode 100644 index 0000000000000000000000000000000000000000..a51e912d3c4b63a3ec0cd85133bf0e7aa3429569 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/partial_targets/data.py @@ -0,0 +1,73 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/partial_targets/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/partial_targets/model.py new file mode 100644 index 0000000000000000000000000000000000000000..4ffe50d9aadf21d73949e2052ceb7f3642bf65d3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/partial_targets/model.py @@ -0,0 +1,180 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(ctx,periods,target.shape[-1],forecast_lengths=lengths) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/partial_targets/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/partial_targets/train.py new file mode 100644 index 0000000000000000000000000000000000000000..2e77612e443d78dd80bcb6a0cc6d01169f61a3a4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/partial_targets/train.py @@ -0,0 +1,73 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/convert.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/convert.py new file mode 100644 index 0000000000000000000000000000000000000000..b2cbc8fc919be6a77eca9ab19c4faa06060a2e0d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/convert.py @@ -0,0 +1,18 @@ +"""Convert only our own trained checkpoint from 32- to 16-point patches. + +Context/query projections fold the two halves by summation, preserving the +embedding of constant features. The output projection keeps the first half. +Attention/MLP weights are inherited unchanged; position units remain 32 points. +""" +import argparse,torch,hashlib +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('--input',required=True);ap.add_argument('--output',required=True);a=ap.parse_args() +ck=torch.load(a.input,map_location='cpu',weights_only=False);state=ck['model'];d=ck['config']['d'];assert ck['config']['patch']==32 +old=state['embed.0.weight'].reshape(d,2,32);state['embed.0.weight']=(old[:,:,:16]+old[:,:,16:]).reshape(d,32) +old=state['query.0.weight'].reshape(d,32,9);state['query.0.weight']=(old[:,:16]+old[:,16:]).reshape(d,16*9) +state['head.weight']=state['head.weight'].reshape(32,18,d)[:16].reshape(16*18,d).clone() +state['head.bias']=state['head.bias'].reshape(32,18)[:16].reshape(16*18).clone() +ck['config']['patch']=16 +ck['conversion']={'from_checkpoint':str(Path(a.input).resolve()),'from_sha256':hashlib.sha256(Path(a.input).read_bytes()).hexdigest(),'method':'fold input/query halves by summation; retain first 16 output rows; preserve physical positional units'} +ck['args']={**ck['args'],'initialize_from':str(Path(a.input).resolve()),'converted':True} +torch.save(ck,a.output) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/evaluate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..05f086d4d84def4a48165f9e65d2948877675e56 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/evaluate.py @@ -0,0 +1,16 @@ +import sys,json,argparse,time,hashlib +from pathlib import Path +import torch +from predict import load_model,run +sys.path.insert(0,'/workspace/evaluation') +from score import score,json_safe + +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);ap.add_argument('--valid',default='/workspace/research/valid_screen');ap.add_argument('--baseline',default='/workspace/research/valid_screen/baseline.json');a=ap.parse_args() +torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cuda.matmul.allow_tf32=False +t0=time.time();out=Path(a.out);v=Path(a.valid) +run(load_model(a.weights),v/'input',out) +base=json.loads(Path(a.baseline).read_text())['configs'] +rep=score(v/'truth',out,base) +rep['checkpoint_sha256']=hashlib.sha256(Path(a.weights).read_bytes()).hexdigest();rep['eval_seconds']=time.time()-t0 +(out/'report.json').write_text(json.dumps(json_safe(rep),indent=1)) +print(json.dumps({k:rep[k] for k in ('skill_score','rel_mase_gmean','rel_wql_gmean','n_failed','groups','eval_seconds')},indent=1)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/model.py new file mode 100644 index 0000000000000000000000000000000000000000..06cce56e2ce671b6683f0246900abfcac06bb3c0 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/model.py @@ -0,0 +1,154 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..e20c6630475d6b4fa6906eb4ed9454b7b5aeec2c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/predict.py @@ -0,0 +1,43 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):q=model.predict(x,p,h).float().cpu().numpy() + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf95c9aec5936076b881c340edb960786f2d40d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/publish.py @@ -0,0 +1,31 @@ +"""Assemble a relocatable package, then atomically exchange complete directories.""" +import json,os,shutil,ctypes,hashlib,argparse +from pathlib import Path +import torch +HERE=Path(__file__).resolve().parent + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',default='/workspace/submission');ap.add_argument('--report',required=True);ap.add_argument('--experiments',default=str(HERE/'EXPERIMENTS.md'));a=ap.parse_args() + final=Path(a.out);staging=final.parent/f'.{final.name}-staging-{os.getpid()}' + shutil.rmtree(staging,ignore_errors=True);staging.mkdir(parents=True) + for file in ('model.py','predict.py','infer.sh','ts_io.py'): + shutil.copy(HERE/file,staging/file) + shutil.copy(a.weights,staging/'weights.pt');shutil.copy('/opt/runtime/requirements.txt',staging/'requirements.txt') + ck=torch.load(a.weights,map_location='cpu',weights_only=False);digest=hashlib.sha256((staging/'weights.pt').read_bytes()).hexdigest() + sources=json.loads(Path('/workspace/research/packed_sample/meta.json').read_text())['dirs'] + manifest={'name':'direct-seasonal-quantile-v1','contract':'timeseries-forecast/v1','parameters':sum(x.numel() for x in ck['model'].values()),'pretrained_assets':[],'sources_used':[f'gifteval_pretrain/{d}' for d in sources]+['synthetic:direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; data.py generator seed 17'],'weights_sha256':digest,'training_step':ck['step'],'config':ck['config'],'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.'} + (staging/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') + (staging/'config.json').write_text(json.dumps(ck['config'],indent=2)+'\n') + shutil.copy(a.experiments,staging/'EXPERIMENTS.md');shutil.copy(a.report,staging/'validation_report.json') + # Include generator/sampler provenance, which is not imported by inference. + (staging/'provenance').mkdir() + for file in ('pack.py','data.py','train.py'):shutil.copy(HERE/file,staging/'provenance'/file) + (staging/'README.md').write_text('# Direct seasonal quantile foundation forecaster\n\nRun `bash infer.sh INPUT_DIR OUTPUT_DIR`. This package contains all inference assets and uses only its supplied input directory. The 6.76M 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.\n\nThe 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.\n') + if final.exists(): + libc=ctypes.CDLL(None,use_errno=True) + if libc.renameat2(-100,os.fsencode(staging),-100,os.fsencode(final),2):raise OSError(ctypes.get_errno(),os.strerror(ctypes.get_errno())) + shutil.rmtree(staging) + else:os.replace(staging,final) + print(json.dumps(manifest,indent=1)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/record.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/record.py new file mode 100644 index 0000000000000000000000000000000000000000..1850a33f46fa3ee4d78cac4a5d6152404801a131 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/record.py @@ -0,0 +1,9 @@ +import argparse,json,math +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('report');ap.add_argument('--label',required=True);ap.add_argument('--outcome',default='Screened for model selection.');a=ap.parse_args() +r=json.loads(Path(a.report).read_text());p=Path(__file__).with_name('EXPERIMENTS.md') +lines=[f'\n## {a.label}',f'- Checkpoint SHA-256: `{r.get("checkpoint_sha256","see model_manifest.json")}`.',f'- Evaluation: {r["n_configs"]} configurations, {r["n_instances"]} instances, {r["n_failed"]} failed configurations; {r.get("eval_seconds","not separately timed")} seconds.',f'- Overall skill {r["skill_score"]:.6f}; relative MASE {r["rel_mase_gmean"]:.6f}; relative WQL {r["rel_wql_gmean"]:.6f}.'] +for group,entries in r['groups'].items(): + lines.append(f'- {group} skill: '+', '.join(f'{k}={1-math.sqrt(v["rel_mase_gmean"]*v["rel_wql_gmean"]):.4f}' for k,v in entries.items())+'.') +lines.append('- Outcome: '+a.outcome) +with p.open('a') as f:f.write('\n'.join(lines)+'\n') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/train.py new file mode 100644 index 0000000000000000000000000000000000000000..3cdc106980371c99d81c71d6746943c47206be83 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/train.py @@ -0,0 +1,71 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(3);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/validation_subset.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..4df83e69c4f9a3365955e5d17ffcfc0af71372b7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch16/validation_subset.py @@ -0,0 +1,18 @@ +"""Model-selection-only subset spanning all 97 configurations, seed 2026.""" +import sys,json,copy +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +import ts_io + +root=Path('/workspace/data/valid');out=Path('/workspace/research/valid_screen') +idx=json.loads((root/'input/index.json').read_text());new=copy.deepcopy(idx);rng=np.random.default_rng(2026) +for cfg in new['configs']: + cid=cfg['config_id'];case=ts_io.CaseFile(root/'input/cases'/f'{cid}.h5') + ids=np.sort(rng.choice(case.n,min(case.n,192),replace=False)) + ts_io.write_case_subset(case,ids,out/'input/cases'/f'{cid}.h5') + lab,se,meta=ts_io.read_truth_file(root/'truth/cases'/f'{cid}.h5') + ts_io.write_truth_file(out/'truth/cases'/f'{cid}.h5',lab[ids],se[ids],meta) + cfg['n_instances']=len(ids);case.close() +for kind in ('input','truth'):(out/kind/'index.json').write_text(json.dumps(new,indent=1)) +print('screen instances',sum(c['n_instances'] for c in new['configs'])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch8/convert.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch8/convert.py new file mode 100644 index 0000000000000000000000000000000000000000..f758dcbc0d48b531889b71dc758a7d2fb9a3afb7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch8/convert.py @@ -0,0 +1,44 @@ +"""Convert our own 16-point model to 8-point patches, without external assets.""" +import argparse +import hashlib +import json +import time +from pathlib import Path + +import torch + +ap=argparse.ArgumentParser() +ap.add_argument('--input',required=True) +ap.add_argument('--output',required=True) +a=ap.parse_args() +torch.set_num_threads(2) +started=time.monotonic() +ck=torch.load(a.input,map_location='cpu',weights_only=False) +state=ck['model']; d=ck['config']['d'] +assert ck['config']['patch']==16 +old=state['embed.0.weight'].reshape(d,2,16) +state['embed.0.weight']=(old[:,:,:8]+old[:,:,8:]).reshape(d,16) +old=state['query.0.weight'].reshape(d,16,9) +state['query.0.weight']=(old[:,:8]+old[:,8:]).reshape(d,8*9) +if 'recency.weight' in state: + old=state['recency.weight'].reshape(d,16,4) + state['recency.weight']=(old[:,:8]+old[:,8:]).reshape(d,8*4) +state['head.weight']=state['head.weight'].reshape(16,18,d)[:8].reshape(8*18,d).clone() +state['head.bias']=state['head.bias'].reshape(16,18)[:8].reshape(8*18).clone() +ck['config']['patch']=8 +ck['config']['partial_target_lengths']=True +ck['conversion']={ + 'from_checkpoint':str(Path(a.input).resolve()), + 'from_sha256':hashlib.sha256(Path(a.input).read_bytes()).hexdigest(), + 'method':'fold input/query/recency halves by summation; retain first8 output rows; preserve physical position units', + 'exact_function_preservation':False} +ck['args']={**ck['args'],'initialize_from':str(Path(a.input).resolve()),'converted':True} +ck['parent_checkpoints']=[str(Path(a.input).resolve())] +torch.save(ck,a.output) +receipt=dict(input_sha256=ck['conversion']['from_sha256'], + checkpoint_sha256=hashlib.sha256(Path(a.output).read_bytes()).hexdigest(), + parameters=sum(v.numel() for v in state.values()), + cpu_seconds=time.monotonic()-started, + optimizer_updates=0,conversion=ck['conversion']) +Path(a.output).with_suffix('.json').write_text(json.dumps(receipt,indent=2)) +print(json.dumps(receipt)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch8/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch8/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch8/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch8/memory_check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch8/memory_check.py new file mode 100644 index 0000000000000000000000000000000000000000..d55bebeab8c6ff393f89b7ad031763f49531f56b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch8/memory_check.py @@ -0,0 +1,23 @@ +"""Maximum training-shape memory fixture, serialized with validation jobs.""" +import fcntl,json,sys,time +from pathlib import Path +import torch + +r=Path('/workspace/research');sys.path.insert(0,str(r/'patch8')) +from model import DirectForecaster,loss_fn +from data import Sampler +with open(r/'.evaluation.lock','a') as lock: + fcntl.flock(lock,fcntl.LOCK_EX) + torch.set_num_threads(1);torch.manual_seed(277);torch.backends.cuda.matmul.allow_tf32=True + started=time.monotonic() + ck=torch.load(r/'patch8_initial.pt',map_location='cpu',weights_only=False) + m=DirectForecaster(**ck['config']).cuda();m.load_state_dict(ck['model']) + x,y,p=[torch.from_numpy(a).cuda() for a in Sampler(r/'packed_sample',277).sample(64,4096,1024)] + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(m,x,y,p,paired=True) + loss.backward();torch.cuda.synchronize() + assert all(v.grad is not None and torch.isfinite(v.grad).all() for v in m.parameters()) + result={'seed':277,'batch':64,'signed_rows':128,'context':4096,'horizon':1024, + 'optimizer_updates':0,'loss':float(loss.detach()),'seconds':time.monotonic()-started, + 'peak_allocated_mib':torch.cuda.max_memory_allocated()/2**20, + 'peak_reserved_mib':torch.cuda.max_memory_reserved()/2**20} + (r/'patch8_memory_check.json').write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch8/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch8/model.py new file mode 100644 index 0000000000000000000000000000000000000000..dedcdff4698028a8ba655865f8425d0dc3ef0dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/patch8/model.py @@ -0,0 +1,204 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/recency_features/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/recency_features/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/recency_features/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/recency_features/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/recency_features/model.py new file mode 100644 index 0000000000000000000000000000000000000000..f8271c5b0bf9a5edb961e1c7839761fe50a2e40b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/recency_features/model.py @@ -0,0 +1,171 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024,recency_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + if self.recency is not None: + pos=torch.arange(c,device=z.device)[None,:];extras=[] + for j in range(2): + period=periods[:,j:j+1] + recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/recency_features/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/recency_features/train.py new file mode 100644 index 0000000000000000000000000000000000000000..3bfb8b90f1a6656881b7598f864becaa737a76f4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/recency_features/train.py @@ -0,0 +1,73 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(3);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/recovery/capacity_curves.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/recovery/capacity_curves.py new file mode 100644 index 0000000000000000000000000000000000000000..c89a28a84243dc16ae52a1215c182a00f15dbc4e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/recovery/capacity_curves.py @@ -0,0 +1,50 @@ +"""Summarize completed validation checkpoints and measured shared-GPU training time.""" +import csv +import json +import time +from pathlib import Path + +R = Path('/workspace/research') +started = time.monotonic() +names = ['random_capacity_512', 'random_capacity_1024', 'random_capacity_1024_halflr', + 'random_capacity_full', 'distill_ensemble', 'random_capacity_512_anneal'] +rows = [] +for name in names: + log = R/(name+'_train.log') + records = {} + if log.exists(): + for line in log.read_text().splitlines(): + try: + item = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(item,dict) and 'step' in item and 'seconds' in item: + records[item['step']] = item + config_path = R/'runs'/name/'config.json' + config = json.loads(config_path.read_text()) if config_path.exists() else {} + for report in sorted((R/'evals').glob(name+'_ema*/report.json')): + result = json.loads(report.read_text()) + step = int(report.parent.name.rsplit('ema',1)[1]) + if result['n_failed']: + continue + record = records.get(step,{}) + rows.append(dict(run=name,step=step,parameters=config.get('parameters'), + seed=config.get('seed'),batch=config.get('batch'),learning_rate=config.get('lr'), + packed=config.get('packed'),skill=result['skill_score'], + rel_mase=result['rel_mase_gmean'],rel_wql=result['rel_wql_gmean'], + checkpoint_sha256=result['checkpoint_sha256'], + training_phase_loop_seconds=record.get('seconds'), + evaluation_seconds=result.get('eval_seconds'),report=str(report))) +rows.sort(key=lambda item:(names.index(item['run']),item['step'])) +output = dict(generated_utc=time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()), + note='Validation selection only. Time is logged process wall on the shared single H100, not isolated GPU time. The cooldown arm starts from the same saved24000state; its phase clock resets. No missing log time is inferred.', + rows=rows,analysis_seconds=time.monotonic()-started,no_training_or_new_inference=True) +(R/'capacity_learning_curves.json').write_text(json.dumps(output,indent=2)) +with (R/'capacity_learning_curves.csv').open('w',newline='') as handle: + writer = csv.DictWriter(handle,fieldnames=list(rows[0]) if rows else ['run']) + writer.writeheader() + writer.writerows(rows) +for name in names: + selected = [r for r in rows if r['run']==name] + if selected: + print(json.dumps(selected[-1])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/recovery/exposure_audit.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/recovery/exposure_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..fb67738bc9ed77f87173feda2430365e66c75966 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/recovery/exposure_audit.py @@ -0,0 +1,46 @@ +"""Describe sampled observation exposure and training invested in selected ancestry.""" +import json +import sys +import time +from pathlib import Path +import numpy as np + +R=Path('/workspace/research') +sys.path.insert(0,str(R/'random_capacity')) +from data import Sampler + +started=time.monotonic() +seed=521 +sampler=Sampler(R/'packed_sample',seed=seed,source_weights_from=R/'packed_sample') +rng=np.random.default_rng(seed) +rows=context_points=target_points=0 +for _ in range(320): + 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])) + x,y,p=sampler.sample(64,c,h) + rows+=len(x) + context_points+=int(np.isfinite(x).sum()) + target_points+=int(np.isfinite(y).sum()) +manifest=json.loads(Path('/workspace/submission/model_manifest.json').read_text()) +runs={} +for item in manifest['training_lineage']: + path=Path(item['checkpoint']) + batch=item.get('training_settings',{}).get('batch') + if path.parts[0]!='runs' or not batch: + continue + run=path.parts[1] + step=item.get('step',0) + if step>runs.get(run,{}).get('step',0): + runs[run]=dict(step=step,batch=batch,rows=step*batch,checkpoint=item['checkpoint']) +ancestral_rows=sum(v['rows'] for v in runs.values()) +mean_points=(context_points+target_points)/rows +result=dict(seed=seed,seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False, + sampled_rows=rows,mean_finite_context_points=context_points/rows, + mean_finite_target_points=target_points/rows,mean_finite_points=mean_points, + selected_descriptor=manifest['checkpoint_sha256'],ancestral_runs=runs, + selected_ancestral_rows_before_sign_pairing=ancestral_rows, + fresh96000_batch48_rows=96000*48, + fresh96000_batch48_gross_observation_presentations_estimate=96000*48*mean_points, + note='Gross sampled presentations include overlapping/resampled windows and synthetic values, not unique observations. Ancestral run maxima count compute invested in different branches, including subtracted controls; they are not an equivalent single-model training trajectory. Sign pairing duplicates compute but not distinct sampled rows. No future training recipe is inferred from this audit alone.') +(R/'training_exposure_audit.json').write_text(json.dumps(result,indent=2)) +print(json.dumps({k:v for k,v in result.items() if k!='ancestral_runs'})) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/recovery/relaunch_20261022b.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/recovery/relaunch_20261022b.py new file mode 100644 index 0000000000000000000000000000000000000000..d16fc19cbbb86dba2ff53b445e368b8bbd2ca218 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/recovery/relaunch_20261022b.py @@ -0,0 +1,105 @@ +"""Resume interrupted research jobs and preserve phase-specific recovery receipts.""" +import datetime +import json +import os +from pathlib import Path +import shutil +import subprocess +import time + +R = Path('/workspace/research') +TAG = 'recovery2' +env = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1') +receipt = {'recovery_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(), + 'remaining_research_seconds_at_operator_recovery': 152594, + 'jobs': {}, 'queues': {}} +children = {} + +def launch(name, command, phase=TAG): + log = R / f'{name}_{phase}.log' + assert not log.exists(), log + with log.open('w') as f: + child = subprocess.Popen(command, stdout=f, stderr=subprocess.STDOUT, env=env) + children[name] = child + return {'pid': child.pid, 'command': command, 'log': str(log), 'started_monotonic': time.monotonic()} + +def persist(): + path = R / f'{TAG}_launch_receipt.json' + tmp = path.with_suffix('.tmp') + tmp.write_text(json.dumps(receipt, indent=2)); os.replace(tmp, path) + +for name in ['wide_capacity_146m_recovery', 'wide_capacity_control_recovery', + 'long_memory_synth_recovery', 'recent_normalization_recovery', 'wide_graft', 'patch8']: + run = R / 'runs' / name + cfg = json.loads((run / 'config.json').read_text()) + shutil.copy2(run / 'config.json', run / f'config_before_{TAG}.json') + command = ['python3', str(R / 'recovery/train.py')] + for key in ['code_dir', 'packed', 'source_weights_from', 'out', 'initialize_from', + 'initialize_ema', 'start_step', 'steps', 'batch', 'lr', 'seed', 'context', + 'sample_context', 'save_every', 'stop_file', 'reset_at', 'reset_seed', 'loss_mode']: + if cfg.get(key) is not None: + command += ['--' + key.replace('_', '-'), str(cfg[key])] + if (run / 'recovery.pt').exists(): + command += ['--resume', str(run / 'recovery.pt')] + mode = 'complete optimizer/EMA/RNG/prefetched-batch resume' + else: + mode = 'restart saved own initialization; no complete checkpoint existed' + if cfg.get('compile_loss'): + command += ['--compile-loss'] + command = ['env', 'TORCHINDUCTOR_COMPILE_THREADS=2', 'MAX_JOBS=2', + 'PYTHONPATH=/workspace/research/compiler_support', + 'TRITON_CACHE_MANAGER=sibling_cache:SiblingFileCacheManager', + 'TRITON_CACHE_DIR=/tmp/timeseries-triton-cache', + 'TORCHINDUCTOR_CACHE_DIR=/tmp/timeseries-inductor-cache'] + command + assert not Path(cfg['stop_file']).exists(), cfg['stop_file'] + receipt['jobs'][name] = dict(launch(name, command), mode=mode) + persist() + +watch_specs = { + 'wide_capacity_146m_recovery': ('wide_capacity_inference', '24000,32000'), + 'wide_capacity_control_recovery': ('wide_capacity_inference', '24000,32000'), + 'long_memory_synth_recovery': ('partial_targets_inference', '12000'), + 'recent_normalization_recovery': ('recent_normalization_inference', '12000'), + 'wide_graft': ('wide_graft_inference', '4000,8000,12000,16000,24000,32000'), + 'patch8': ('full_paired_inference', '1000,3000,6000,12000'), + 'volatility_synth': ('partial_targets_inference', '3000,6000,12000'), + 'postloss': ('full_paired_inference', '1000,3000,6000,12000'), + 'paired_long_memory': ('full_paired_inference', '1000,3000,6000,12000'), +} +for name, (runtime, steps) in watch_specs.items(): + command = ['python3', str(R / 'watch_evaluate.py'), '--run', str(R / 'runs' / name), + '--evaluator', str(R / runtime / 'evaluate.py'), '--name', name, '--steps', steps] + launch(name + '_watch', command) + +queue_specs = {'volatility_synth': 'long_memory_synth_recovery', + 'postloss': 'recent_normalization_recovery', + 'paired_long_memory': 'wide_capacity_control_recovery'} +for name, dependency in queue_specs.items(): + old = json.loads((R / (name + '_queue.json')).read_text()) + shutil.copy2(R / (name + '_queue.json'), R / (name + '_queue_before_' + TAG + '.json')) + receipt['queues'][name] = dict(old, dependency=dependency, status='waiting', + wait_pids=[children[dependency].pid]) +persist() + +while True: + for name, job in receipt['jobs'].items(): + if 'returncode' not in job and children[name].poll() is not None: + job.update(returncode=children[name].returncode, + phase_seconds=time.monotonic() - job['started_monotonic']) + persist() + for name, queue in receipt['queues'].items(): + if queue['status'] == 'waiting' and children[queue['dependency']].poll() is not None: + if children[queue['dependency']].returncode != 0 or not all(Path(p).exists() for p in queue['required_checkpoints']): + queue['status'] = 'blocked_by_incomplete_dependency' + else: + receipt['jobs'][name] = launch(name, queue['command']) + queue.update(status='running', pid=children[name].pid, + started_utc=datetime.datetime.now(datetime.timezone.utc).isoformat()) + with (R / 'direct_v1/EXPERIMENTS.md').open('a') as f: + f.write(f'\n{name} started {queue["started_utc"]} after {queue["dependency"]} completed. Original predeclared settings and seed retained.\n') + (R / (name + '_queue.json')).write_text(json.dumps(queue, indent=2)) + persist() + if all(p.poll() is not None for n,p in children.items() if not n.endswith('_watch')) and all(q['status'] != 'waiting' for q in receipt['queues'].values()): + break + time.sleep(5) +persist() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/recovery/relaunch_20261023.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/recovery/relaunch_20261023.py new file mode 100644 index 0000000000000000000000000000000000000000..5f35a9cfcbe7ea66c8837b6d4ada8b84be36b934 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/recovery/relaunch_20261023.py @@ -0,0 +1,104 @@ +"""Resume interrupted research jobs and preserve phase-specific recovery receipts.""" +import datetime +import json +import os +from pathlib import Path +import shutil +import subprocess +import time + +R = Path('/workspace/research') +TAG = 'recovery3' +env = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1') +receipt = {'recovery_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(), + 'remaining_research_seconds_at_operator_recovery': 151596, + 'jobs': {}, 'queues': {}} +children = {} + +def launch(name, command, phase=TAG): + log = R / f'{name}_{phase}.log' + assert not log.exists(), log + with log.open('w') as f: + child = subprocess.Popen(command, stdout=f, stderr=subprocess.STDOUT, env=env) + children[name] = child + return {'pid': child.pid, 'command': command, 'log': str(log), 'started_monotonic': time.monotonic()} + +def persist(): + path = R / f'{TAG}_launch_receipt.json' + tmp = path.with_suffix('.tmp') + tmp.write_text(json.dumps(receipt, indent=2)); os.replace(tmp, path) + +for name in ['wide_capacity_146m_recovery', 'wide_capacity_control_recovery', + 'long_memory_synth_recovery', 'wide_graft', 'patch8']: + run = R / 'runs' / name + cfg = json.loads((run / 'config.json').read_text()) + shutil.copy2(run / 'config.json', run / f'config_before_{TAG}.json') + command = ['python3', str(R / 'recovery/train.py')] + for key in ['code_dir', 'packed', 'source_weights_from', 'out', 'initialize_from', + 'initialize_ema', 'start_step', 'steps', 'batch', 'lr', 'seed', 'context', + 'sample_context', 'save_every', 'stop_file', 'reset_at', 'reset_seed', 'loss_mode']: + if cfg.get(key) is not None: + command += ['--' + key.replace('_', '-'), str(cfg[key])] + if (run / 'recovery.pt').exists(): + command += ['--resume', str(run / 'recovery.pt')] + mode = 'complete optimizer/EMA/RNG/prefetched-batch resume' + else: + mode = 'restart saved own initialization; no complete checkpoint existed' + if cfg.get('compile_loss'): + command += ['--compile-loss'] + command = ['env', 'TORCHINDUCTOR_COMPILE_THREADS=2', 'MAX_JOBS=2', + 'PYTHONPATH=/workspace/research/compiler_support', + 'TRITON_CACHE_MANAGER=sibling_cache:SiblingFileCacheManager', + 'TRITON_CACHE_DIR=/tmp/timeseries-triton-cache', + 'TORCHINDUCTOR_CACHE_DIR=/tmp/timeseries-inductor-cache'] + command + assert not Path(cfg['stop_file']).exists(), cfg['stop_file'] + receipt['jobs'][name] = dict(launch(name, command), mode=mode) + persist() + +watch_specs = { + 'wide_capacity_146m_recovery': ('wide_capacity_inference', '24000,32000'), + 'wide_capacity_control_recovery': ('wide_capacity_inference', '24000,32000'), + 'long_memory_synth_recovery': ('partial_targets_inference', '12000'), + 'recent_normalization_recovery': ('recent_normalization_inference', '12000'), + 'wide_graft': ('wide_graft_inference', '4000,8000,12000,16000,24000,32000'), + 'patch8': ('full_paired_inference', '1000,3000,6000,12000'), + 'volatility_synth': ('partial_targets_inference', '3000,6000,12000'), + 'postloss': ('full_paired_inference', '1000,3000,6000,12000'), + 'paired_long_memory': ('full_paired_inference', '1000,3000,6000,12000'), +} +for name, (runtime, steps) in watch_specs.items(): + command = ['python3', str(R / 'watch_evaluate.py'), '--run', str(R / 'runs' / name), + '--evaluator', str(R / runtime / 'evaluate.py'), '--name', name, '--steps', steps] + launch(name + '_watch', command) + +queue_specs = {'volatility_synth': 'long_memory_synth_recovery', + 'paired_long_memory': 'wide_capacity_control_recovery'} +for name, dependency in queue_specs.items(): + old = json.loads((R / (name + '_queue.json')).read_text()) + shutil.copy2(R / (name + '_queue.json'), R / (name + '_queue_before_' + TAG + '.json')) + receipt['queues'][name] = dict(old, dependency=dependency, status='waiting', + wait_pids=[children[dependency].pid]) +persist() + +while True: + for name, job in receipt['jobs'].items(): + if 'returncode' not in job and children[name].poll() is not None: + job.update(returncode=children[name].returncode, + phase_seconds=time.monotonic() - job['started_monotonic']) + persist() + for name, queue in receipt['queues'].items(): + if queue['status'] == 'waiting' and children[queue['dependency']].poll() is not None: + if children[queue['dependency']].returncode != 0 or not all(Path(p).exists() for p in queue['required_checkpoints']): + queue['status'] = 'blocked_by_incomplete_dependency' + else: + receipt['jobs'][name] = launch(name, queue['command']) + queue.update(status='running', pid=children[name].pid, + started_utc=datetime.datetime.now(datetime.timezone.utc).isoformat()) + with (R / 'direct_v1/EXPERIMENTS.md').open('a') as f: + f.write(f'\n{name} started {queue["started_utc"]} after {queue["dependency"]} completed. Original predeclared settings and seed retained.\n') + (R / (name + '_queue.json')).write_text(json.dumps(queue, indent=2)) + persist() + if all(p.poll() is not None for n,p in children.items() if not n.endswith('_watch')) and all(q['status'] != 'waiting' for q in receipt['queues'].values()): + break + time.sleep(5) +persist() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/recovery/schedules.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/recovery/schedules.py new file mode 100644 index 0000000000000000000000000000000000000000..4c8378f374144b802d2cd5a98afd71efc1ba0a4c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/recovery/schedules.py @@ -0,0 +1,13 @@ +"""Explicit training-only learning-rate schedules; default arithmetic unchanged.""" +import math + + +def learning_rate(step, steps, peak, reset_at=-1, anneal_from_step=None, + anneal_from_lr=None, anneal_final_lr=None): + if anneal_from_step is not None: + assert steps > anneal_from_step + assert 0 < anneal_final_lr <= anneal_from_lr + progress=max(0.,min(1.,(step-anneal_from_step)/(steps-anneal_from_step))) + return anneal_final_lr+.5*(anneal_from_lr-anneal_final_lr)*(1+math.cos(math.pi*progress)) + warm_step=step-reset_at if reset_at>=0 and step>reset_at else step + return peak*min(1,warm_step/400)*(.2+.4*(1+math.cos(math.pi*step/steps))) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/recovery/snapshot.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/recovery/snapshot.py new file mode 100644 index 0000000000000000000000000000000000000000..11ce27e43477f9c685cefeaa5f36e53c59634505 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/recovery/snapshot.py @@ -0,0 +1,99 @@ +"""Write a compact authoritative research recovery index without touching training state.""" +import datetime +import json +import os +from pathlib import Path + +R=Path('/workspace/research');p=R/'CURRENT_RESEARCH_STATE.json' +s=json.loads(p.read_text()) +s['snapshot_utc']=datetime.datetime.now(datetime.timezone.utc).isoformat() +receipt=json.loads((R/'recovery3_launch_receipt.json').read_text()) +s['runs']={} +for name,job in receipt['jobs'].items(): + run=R/'runs'/name + log=Path(job['log']) + records=[] + for line in log.read_text().splitlines(): + try: + record=json.loads(line) + if 'step' in record or 'completed_step' in record:records.append(record) + except json.JSONDecodeError:pass + s['runs'][name]={'config':json.loads((run/'config.json').read_text()) if (run/'config.json').exists() else None, + 'last_phase_record':records[-1] if records else None, + 'phase_log':str(log),'supervisor_receipt':str(R/'recovery3_launch_receipt.json'), + 'latest_saved_ema':str(max(run.glob('ema*.pt'))) if list(run.glob('ema*.pt')) else None, + 'complete_recovery_checkpoint':str(run/'recovery.pt') if (run/'recovery.pt').exists() else None, + 'pid_at_snapshot':job['pid'],'returncode':job.get('returncode'), + 'note':'Check actual live process and checkpoint state before resuming; this is only a snapshot.'} +s['queues']={name:{'status':q['status'],'dependency':q['dependency'],'command':q['command'], + 'required_checkpoints':q['required_checkpoints']} + for name,q in receipt['queues'].items()} +s.pop('prepared_not_launched',None) +s['deferred_unqueued']={'E72':'temporal_mixup, prepared and checked but not queued','ideas':'RESEARCH_IDEAS.md, no jobs attached'} +s['completed_since_previous_recovery']={ + 'E67_control12000':{'skill':.37724286394256845,'training_loop_seconds':2794.8358458959847}, + 'E67_paired12000':{'skill':.377427077277383,'training_loop_seconds':2794.867385860998}, + 'E63_expanded146M':'Stopped8501, complete recovery retained; allocation moved to E73; inconclusive data scaling', + 'E61_slowAR':'Complete12000; E76 used6000 correction, final transfer rejected', + 'E65_recent_normalization':'Complete12000; E81 equal ensemble rejected', + 'E58_small_control':'Complete32000', + 'E58_wide146M':'Complete32000; no gain over37Mcontrol; do not resume', + 'E71_patch8':'Complete12000; selected6000 used in E87/E96/E102 ensembles', + 'E69_volatility':'Complete12000; final below matched control; no transfer', + 'E89_patch8_control':'Complete12000; final0.380847096,loop2729.052105s; selected starting E71parent remains stronger', + 'E89_fullpatch4':'Complete12000,main0.381640078; E96 used6000, E103final cached alternative mixed; loop5066.016522s', + 'E93_split_patch':'Complete12000,main0.381711986; selected final is E102 published thirdmember; loop3153.565149s', + 'E92_robust_normalization':'Complete12000,final0.377099312 belowcontrol; rejected;E97started', + 'E90_metric_scale':'Complete12000; final0.377373344 ties/slightly trailsE80; no selection; loop2702.166704s', + 'E84_coarse':'Complete12000; daily gain but weekly regression; not selected', + 'E88_late_patch8_slowAR':'Complete12000; small9k gain lost atfinal; rejected', + 'E80_overflow':'Complete12000; finaltiesoriginal; selected3k compositeE91rejected', + 'E78_multiscaleAR':'Complete12000; no gain over single slowAR', + 'E86_protected_graft':'Complete8000; below own initialization; no publication', + 'E75_postloss':'Stopped3653 deliberately; immutable snapshot retained; E98 separately declared completion active in another output, original stopfile remains', + 'E73_independent_graft':'Stopped8683 after negative8000; replaced by E86; stopfile remains', + 'E95_stratified_corpus':'Complete12000,final0.377983250,earliermixed; E105collision destroyed only1000weights and optimizer recovery;2k..12k preserved; do not resume', + 'E97_weekly_synth':'Complete12000,final0.380439539; E112final weekly correction now published; loop2600.472750s', + 'E105_stratified_volume':'Complete12000,final0.377529200,earlier0.336713522/0.359535697/0.390349158 mixed; corrected continuationloop2013.982814s plus original incident phase', + 'E106_spectral_synth':'Complete12000,final0.377641399,earlier0.337647555/0.361626447/0.385497870, average matched gap negligible; loop2206.272278s; E114fixed6000transfers in selection', + 'E98_postloss_completion':'Complete12000,final0.376034254 below3000 andcontrol; rejected,loop1995.386513s', + 'E99_early_cooldown':'Complete36000,final0.363306598 trails original36k0.364859034; rejected,loop1603.635706s', + 'E77_pairedslowAR':'Complete12000;6000 strongest main/earlier comparison'} +s['external_receipts']=[str(R/'postloss_recovery3_receipt.json'),str(R/'random_capacity_512_queue.json'),str(R/'random_capacity_1024_queue.json'),str(R/'multiscale_ar_queue.json'),str(R/'overflow_control_queue.json'),str(R/'coarse_aggregate_queue.json'),str(R/'patch8_long_memory_queue.json'),str(R/'wide_graft_frozen_queue.json'),str(R/'patch4_candidate_queue.json'),str(R/'patch4_control_queue.json'),str(R/'metric_scale_queue.json'),str(R/'robust_normalization_queue.json'),str(R/'split_patch_queue.json'),str(R/'random_capacity_1024_halflr_queue.json'),str(R/'stratified_corpus_queue.json'),str(R/'weekly_synth_queue.json'),str(R/'postloss_completion_queue.json'),str(R/'random_capacity_512_anneal_queue.json'),str(R/'distill_ensemble_queue.json'),str(R/'stratified_volume_queue.json'),str(R/'spectral_synth_queue.json'),str(R/'long_seasonal_queue.json'),str(R/'random_capacity_full_queue.json'),str(R/'weekly_replication_control_queue.json'),str(R/'weekly_replication_candidate_queue.json'),str(R/'lowfreq_windows_queue.json'),str(R/'phase_joint_queue.json')] +queue_pids={'random_capacity_512_queue.json':965,'random_capacity_1024_queue.json':967, + 'multiscale_ar_queue.json':1678,'overflow_control_queue.json':1676, + 'coarse_aggregate_queue.json':3086,'patch8_long_memory_queue.json':3739, + 'wide_graft_frozen_queue.json':3931,'patch4_candidate_queue.json':4078, + 'patch4_control_queue.json':4080} +s['external_jobs']={} +for receipt_name in s['external_receipts']: + receipt_path=Path(receipt_name) + if not receipt_path.exists():continue + item=json.loads(receipt_path.read_text());command=item.get('command',[]) + if '--out' not in command:continue + run=Path(command[command.index('--out')+1]);log=Path(item.get('log',str(receipt_path).replace('_queue.json','_train.log'))) + last=None + if log.exists(): + for line in log.read_text().splitlines(): + try: + record=json.loads(line) + if isinstance(record,dict) and ('step' in record or 'completed_step' in record):last=record + except json.JSONDecodeError:pass + queue_pid=item.get('launcher_pid',queue_pids.get(receipt_path.name)) + children_file=Path(f'/proc/{queue_pid}/task/{queue_pid}/children') if queue_pid else None + children=list(map(int,children_file.read_text().split())) if children_file and children_file.exists() else [] + checkpoints=list(run.glob('ema*.pt')) + s['external_jobs'][run.name]={'receipt':str(receipt_path),'status':item.get('status'), + 'queue_pid_at_snapshot':queue_pid,'child_pids_at_snapshot':children, + 'last_phase_record':last,'log':str(log), + 'latest_saved_ema':str(max(checkpoints)) if checkpoints else None, + 'complete_recovery_checkpoint':str(run/'recovery.pt') if (run/'recovery.pt').exists() else None, + 'command':command,'note':'PIDs are only a snapshot; check actual processes and serialized state before recovery.'} +s['compiler_environment']={'OPENBLAS_NUM_THREADS':'1','OMP_NUM_THREADS':'1','TORCHINDUCTOR_COMPILE_THREADS':'2','MAX_JOBS':'2','PYTHONPATH':str(R/'compiler_support'),'TRITON_CACHE_MANAGER':'sibling_cache:SiblingFileCacheManager','TRITON_CACHE_DIR':'/tmp/timeseries-triton-cache','TORCHINDUCTOR_CACHE_DIR':'/tmp/timeseries-inductor-cache'} +for job in s['external_jobs'].values(): + job['environment']=s['compiler_environment'] if '--compile-loss' in job['command'] else {'OPENBLAS_NUM_THREADS':'1','OMP_NUM_THREADS':'1'} +s['compiler_cache_backup']=str(R/'compiler_cache_backup') +for stale in ['pending','pending_actions','active_experiments','next_experiments','prepared_experiments']: + s.pop(stale,None) +tmp=p.with_suffix('.tmp');tmp.write_text(json.dumps(s,indent=2));os.replace(tmp,p) +print(s['snapshot_utc']) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/recovery/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/recovery/train.py new file mode 100644 index 0000000000000000000000000000000000000000..536677ab542342e8e9b56298e5ddb7cb2983a258 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member1/training/recovery/train.py @@ -0,0 +1,201 @@ +"""Resumable continuation of our existing permitted-corpus experiments.""" +import argparse,copy,fcntl,inspect,json,math,os,sys,time +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import numpy as np +import torch + +ap=argparse.ArgumentParser() +ap.add_argument('--code-dir',required=True);ap.add_argument('--packed',required=True) +ap.add_argument('--source-weights-from');ap.add_argument('--out',required=True) +ap.add_argument('--initialize-from',required=True);ap.add_argument('--initialize-ema') +ap.add_argument('--start-step',type=int,default=0);ap.add_argument('--resume') +ap.add_argument('--steps',type=int,required=True);ap.add_argument('--batch',type=int,required=True) +ap.add_argument('--lr',type=float,required=True);ap.add_argument('--seed',type=int,required=True) +ap.add_argument('--context',type=int);ap.add_argument('--sample-context',type=int,default=4096) +ap.add_argument('--save-every',type=int,default=1000);ap.add_argument('--stop-file') +ap.add_argument('--recovery-every',type=int,default=250) +ap.add_argument('--halt-after',type=int) +ap.add_argument('--loss-mode',choices=['individual','paired']) +ap.add_argument('--compile-loss',action='store_true') +ap.add_argument('--reset-at',type=int,default=-1);ap.add_argument('--reset-seed',type=int,default=179) +ap.add_argument('--anneal-from-step',type=int);ap.add_argument('--anneal-from-lr',type=float) +ap.add_argument('--anneal-final-lr',type=float) +ap.add_argument('--teacher-package');ap.add_argument('--teacher-coefficient',type=float) +a=ap.parse_args() +# Hold a process-lifetime lock before loading a model or touching GPU state. +_run_out=Path(a.out);_run_out.mkdir(parents=True,exist_ok=True) +_run_lock=open(_run_out/'.training.lock','a') +try:fcntl.flock(_run_lock,fcntl.LOCK_EX|fcntl.LOCK_NB) +except BlockingIOError:raise SystemExit('Another trainer already owns this output directory: '+str(_run_out)) +if not a.resume: + _saved=list(_run_out.glob('ema*.pt'))+list(_run_out.glob('step*.pt')) + if (_run_out/'recovery.pt').exists():_saved.append(_run_out/'recovery.pt') + if _saved: + raise SystemExit('Refusing fresh training into an output with saved checkpoints; use a new directory or explicit --resume: '+str(_run_out)) +sys.path.insert(0,a.code_dir) +from model import DirectForecaster,loss_fn +from data import Sampler +from schedules import learning_rate +torch.set_num_threads(2);torch.manual_seed(a.seed);torch.backends.cuda.matmul.allow_tf32=True +out=Path(a.out);out.mkdir(parents=True,exist_ok=True);a.trainable_scope='all' +if Path(a.code_dir).name in ('long_memory_synth','paired_long_memory','multiscale_ar','random_capacity','patch8_long_memory','distill_ensemble'):a.synthetic_ar_time_constants=[1,10000] +if Path(a.code_dir).name in ('full_paired','patch8','temporal_mixup','postloss','paired_long_memory','multiscale_ar','random_capacity','overflow_control','coarse_aggregate','patch8_long_memory','patch4','metric_scale','robust_normalization','split_patch','weekly_synth','distill_ensemble'):a.requested_horizon_seed=a.seed+300003 +if Path(a.code_dir).name=='multiscale_ar': + a.synthetic_ar_components=4;a.multiscale_ar_seed=a.seed+700003 +if Path(a.code_dir).name=='volatility_synth':a.stochastic_volatility_seed=a.seed+500003 +if Path(a.code_dir).name=='coarse_aggregate': + a.coarse_aggregation_seed=a.seed+900003;a.coarse_aggregation_probability=.2;a.coarse_aggregation_frequencies=['D','W'] +if Path(a.code_dir).name=='temporal_mixup':a.temporal_mixup_seed=a.seed+600003 +if Path(a.code_dir).name=='postloss': + a.fixed_postprocessing_loss=True;a.normalization_overflow_fallback=True +if Path(a.code_dir).name in ('overflow_control','metric_scale','random_capacity','weekly_synth','distill_ensemble'):a.normalization_overflow_fallback=True +if Path(a.code_dir).name=='weekly_synth': + a.weekly_synthetic_seed=a.seed+1000003;a.weekly_replacement_probability=1/11 +if Path(a.code_dir).name=='spectral_synth': + a.spectral_synthetic_seed=a.seed+1100003;a.spectral_replacement_probability=.5 + a.spectral_length_scale=[1,10000];a.spectral_families=['Matern0.5','Matern1.5','Matern2.5','RBF'] + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True +if Path(a.code_dir).name in ('long_seasonal','phase_joint'): + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True +if Path(a.code_dir).name=='lowfreq_windows': + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True + a.lowfreq_window_seed=a.seed+1200003;a.lowfreq_window_probability=.5 + a.lowfreq_window_rule='period2=1,period1<=52;finite-target endpoint;log-uniform horizon4..min(H,max(8,2p),span-8) with available-length fallback;context cap min(C,max(64,32p));at least4finite history' +if Path(a.code_dir).name=='metric_scale':a.loss_seasonality='lag1 for exact daily[7,365] and weekly[52,1] period pairs; unchanged otherwise' +if Path(a.code_dir).name=='robust_normalization':a.normalization_kind='finite median plus/minus6 mean absolute deviations winsorized mean/RMS, float64; original normalized history clipped30' +if Path(a.code_dir).name=='wide_graft_frozen':a.trainable_scope='new feature stream and cross-stream blocks; inherited parameter blocks frozen' +ck=torch.load(a.resume or a.initialize_from,map_location='cpu',weights_only=False) +# Keep immutable branch ancestry across a later restart from this run's own recovery. +lineage_parents=list(ck.get('parent_checkpoints',[])) +if a.initialize_ema:lineage_parents.append(a.initialize_ema) +if a.resume and Path(a.resume).parent.resolve()!=out.resolve():lineage_parents.append(a.resume) +previous_args=ck.get('args',{}) +previous_resume=previous_args.get('resume') +if previous_resume and Path(previous_resume).parent.resolve()!=Path(previous_args.get('out',a.out)).resolve(): + lineage_parents.append(previous_resume) +lineage_parents=list(dict.fromkeys(lineage_parents)) +config=dict(ck['config']) +if a.context:config['max_context']=a.context +model=DirectForecaster(**config).cuda();model.load_state_dict(ck['model']) +teacher=None +if Path(a.code_dir).name=='distill_ensemble': + assert a.teacher_package and a.teacher_coefficient is not None +if a.teacher_package: + assert Path(a.code_dir).name=='distill_ensemble' + from teacher import OwnEnsembleTeacher + with torch.random.fork_rng(devices=[torch.cuda.current_device()]): + teacher=OwnEnsembleTeacher(a.teacher_package) + if ck.get('args',{}).get('teacher_descriptor_sha256'): + assert ck['args']['teacher_descriptor_sha256']==teacher.descriptor_sha256 + assert ck['args']['teacher_coefficient']==a.teacher_coefficient + a.teacher_descriptor_sha256=teacher.descriptor_sha256 + a.teacher_checkpoint_sha256=teacher.member_hashes + a.teacher_target_kind='equal average of own frozen E96 raw normalized sign-paired neural quantiles, before postprocessing' + +protector=None +if Path(a.code_dir).name=='wide_graft_frozen': + from frozen import FreezeInherited + protector=FreezeInherited(model) + a.protected_parameters=protector.inherited_numel +if a.compile_loss: + torch._dynamo.config.recompile_limit=64 + objective=torch.compile(loss_fn,fullgraph=True,dynamic=False) +else:objective=loss_fn +multipliers=ck.get('lr_multipliers',{}) +def optimizer(): + groups=[] + for mult in sorted(set(multipliers.values())|{1.}): + params=[p for n,p in model.named_parameters() if multipliers.get(n,1.)==mult] + if params:groups.append({'params':params,'lr':a.lr*mult,'lr_multiplier':mult,'weight_decay':.05/mult}) + return torch.optim.AdamW(groups,betas=(.9,.95),fused=True) +opt=optimizer() +if a.resume: + start_step=ck['step'];opt.load_state_dict(ck['optimizer']) + ema={k:v.cuda() for k,v in ck['ema_state'].items()} +else: + start_step=a.start_step + ema_ck=torch.load(a.initialize_ema,map_location='cpu',weights_only=False) if a.initialize_ema else ck + ema={k:v.cuda().clone() for k,v in ema_ck['model'].items()} +del ck +def make_sampler(seed): + kwargs={'seed':seed} + if 'source_weights_from' in inspect.signature(Sampler).parameters:kwargs['source_weights_from']=a.source_weights_from + return Sampler(a.packed,**kwargs),np.random.default_rng(seed) +stream_seed=a.reset_seed if a.reset_at>=0 and start_step>=a.reset_at else a.seed +sampler,rng=make_sampler(stream_seed) +def next_batch(): + c=int(rng.choice([512,1024,2048,a.sample_context],p=[.1,.15,.35,.4])) + h=int(rng.choice([32,128,512,1024],p=[.1,.2,.2,.5])) + x,y,p=sampler.sample(a.batch,c,h) + return x[:,-model.max_context:].copy(),y,p +pool=ThreadPoolExecutor(1) +if a.resume: + recovery=torch.load(a.resume,map_location='cpu',weights_only=False) + rng.bit_generator.state=recovery['batch_rng_state'];sampler.rng.bit_generator.state=recovery['sampler_rng_state'] + for name,state in recovery.get('sampler_rng_states',{}).items():getattr(sampler,name).bit_generator.state=state + torch.set_rng_state(recovery['torch_rng_state']);torch.cuda.set_rng_state_all(recovery['cuda_rng_state']) + pending=recovery['prefetched_batch'];del recovery + future=pool.submit(lambda:pending) +else:future=pool.submit(next_batch) +parameters=sum(p.numel() for p in model.parameters()) +(out/'config.json').write_text(json.dumps({**vars(a),'model':model.config,'parameters':parameters},indent=2)) +print(json.dumps({'parameters':parameters,'starting_step':start_step,'stream_seed':stream_seed,'restored_complete_training_state':bool(a.resume)}),flush=True) +started=time.monotonic();losses=[] +def atomic_save(obj,path): + torch.save(obj,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) +def save(step,include_selection_weights=True): + global future + pending_batch=future.result() + common={'config':model.config,'step':step,'args':vars(a),'lr_multipliers':multipliers, + 'parent_checkpoints':list(dict.fromkeys(lineage_parents+(teacher.checkpoints if teacher else [])))} + if include_selection_weights: + for prefix,state in [('step',model.state_dict()),('ema',ema)]: + atomic_save({**common,'model':state,'ema':prefix=='ema'},out/f'{prefix}{step:06d}.pt') + atomic_save({**common,'model':model.state_dict(),'optimizer':opt.state_dict(),'ema_state':ema, + 'prefetched_batch':pending_batch,'batch_rng_state':copy.deepcopy(rng.bit_generator.state), + 'sampler_rng_state':copy.deepcopy(sampler.rng.bit_generator.state), + 'sampler_rng_states':{name:copy.deepcopy(value.bit_generator.state) for name,value in vars(sampler).items() if isinstance(value,np.random.Generator)}, + 'torch_rng_state':torch.get_rng_state(),'cuda_rng_state':torch.cuda.get_rng_state_all()},out/'recovery.pt') + future=pool.submit(lambda:pending_batch) +for step in range(start_step+1,a.steps+1): + if a.reset_at>=0 and step==a.reset_at+1 and start_step=a.halt_after) + selection_checkpoint=step%a.save_every==0 or step==a.steps or stop + # Persist a complete state before a fresh/resumed job warms its remaining compiled shapes. + if selection_checkpoint or step%a.recovery_every==0 or step==start_step+1: + save(step,include_selection_weights=selection_checkpoint) + if stop:break +pool.shutdown() +print(json.dumps({'completed_step':step,'training_process_loop_seconds':time.monotonic()-started}),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/model_manifest.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/model_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..267b9cd31e3dcddf8fb57320edcd08e8bba1d9bb --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/model_manifest.json @@ -0,0 +1,744 @@ +{ + "name": "direct-seasonal-foundation", + "contract": "timeseries-forecast/v1", + "parameters": 36601928, + "pretrained_assets": [], + "sources_used": [ + "gifteval_pretrain/BEIJING_SUBWAY_30MIN", + "gifteval_pretrain/HZMETRO", + "gifteval_pretrain/LOS_LOOP", + "gifteval_pretrain/PEMS03", + "gifteval_pretrain/PEMS04", + "gifteval_pretrain/PEMS07", + "gifteval_pretrain/PEMS08", + "gifteval_pretrain/PEMS_BAY", + "gifteval_pretrain/Q-TRAFFIC", + "gifteval_pretrain/SHMETRO", + "gifteval_pretrain/alibaba_cluster_trace_2018", + "gifteval_pretrain/australian_electricity_demand", + "gifteval_pretrain/azure_vm_traces_2017", + "gifteval_pretrain/bdg-2_bear", + "gifteval_pretrain/bdg-2_fox", + "gifteval_pretrain/bdg-2_panther", + "gifteval_pretrain/bdg-2_rat", + "gifteval_pretrain/bitcoin_with_missing", + "gifteval_pretrain/borealis", + "gifteval_pretrain/borg_cluster_data_2011", + "gifteval_pretrain/buildings_900k", + "gifteval_pretrain/bull", + "gifteval_pretrain/cdc_fluview_ilinet", + "gifteval_pretrain/cdc_fluview_who_nrevss", + "gifteval_pretrain/china_air_quality", + "gifteval_pretrain/cif_2016_12", + "gifteval_pretrain/cif_2016_6", + "gifteval_pretrain/cmip6_2000", + "gifteval_pretrain/cmip6_2005", + "gifteval_pretrain/cmip6_2010", + "gifteval_pretrain/cockatoo", + "gifteval_pretrain/covid19_energy", + "gifteval_pretrain/covid_mobility", + "gifteval_pretrain/elecdemand", + "gifteval_pretrain/elf", + "gifteval_pretrain/era5_2010", + "gifteval_pretrain/era5_2011", + "gifteval_pretrain/era5_2012", + "gifteval_pretrain/era5_2013", + "gifteval_pretrain/era5_2014", + "gifteval_pretrain/era5_2015", + "gifteval_pretrain/era5_2016", + "gifteval_pretrain/era5_2017", + "gifteval_pretrain/era5_2018", + "gifteval_pretrain/extended_web_traffic_with_missing", + "gifteval_pretrain/favorita_sales", + "gifteval_pretrain/favorita_transactions", + "gifteval_pretrain/gfc12_load", + "gifteval_pretrain/gfc14_load", + "gifteval_pretrain/gfc17_load", + "gifteval_pretrain/godaddy", + "gifteval_pretrain/hog", + "gifteval_pretrain/ideal", + "gifteval_pretrain/kaggle_web_traffic_weekly", + "gifteval_pretrain/kdd2022", + "gifteval_pretrain/largest_2017", + "gifteval_pretrain/largest_2018", + "gifteval_pretrain/largest_2019", + "gifteval_pretrain/largest_2020", + "gifteval_pretrain/largest_2021", + "gifteval_pretrain/lcl", + "gifteval_pretrain/london_smart_meters_with_missing", + "gifteval_pretrain/m1_monthly", + "gifteval_pretrain/m1_quarterly", + "gifteval_pretrain/m1_yearly", + "gifteval_pretrain/m5", + "gifteval_pretrain/monash_m3_monthly", + "gifteval_pretrain/monash_m3_other", + "gifteval_pretrain/monash_m3_quarterly", + "gifteval_pretrain/nn5_daily_with_missing", + "gifteval_pretrain/nn5_weekly", + "gifteval_pretrain/oikolab_weather", + "gifteval_pretrain/pdb", + "gifteval_pretrain/project_tycho", + "gifteval_pretrain/residential_load_power", + "gifteval_pretrain/residential_pv_power", + "gifteval_pretrain/rideshare_with_missing", + "gifteval_pretrain/sceaux", + "gifteval_pretrain/smart", + "gifteval_pretrain/solar_power", + "gifteval_pretrain/spain", + "gifteval_pretrain/subseasonal", + "gifteval_pretrain/subseasonal_precip", + "gifteval_pretrain/sunspot_with_missing", + "gifteval_pretrain/taxi_30min", + "gifteval_pretrain/tourism_quarterly", + "gifteval_pretrain/tourism_yearly", + "gifteval_pretrain/traffic_hourly", + "gifteval_pretrain/traffic_weekly", + "gifteval_pretrain/uber_tlc_daily", + "gifteval_pretrain/uber_tlc_hourly", + "gifteval_pretrain/vehicle_trips_with_missing", + "gifteval_pretrain/wiki-rolling_nips", + "gifteval_pretrain/wind_farms_with_missing", + "gifteval_pretrain/wind_power", + "synthetic:both original and sign-reflected orientations of each sampled allowed or locally generated window; paired quantile loss, seed 197", + "synthetic:both original and sign-reflected orientations of each sampled allowed or locally generated window; paired quantile loss, seed 401", + "synthetic:both original and sign-reflected orientations of each sampled window, seed 197", + "synthetic:independent sign reflection of sampled allowed-corpus and locally generated windows; seeds 43,47,59,79,89,197", + "synthetic:own direct_v1 Fourier seasons, damped trends, AR noise, changepoints and intermittent demand; seeds 23,43,47,59,79,89,197,401", + "synthetic:own random requested-horizon prefixes, half of rows retain the full horizon and half use a patch-rounded prefix between one-quarter and the full horizon; independent seed 300200", + "synthetic:own random requested-horizon prefixes, half of rows retain the full horizon and half use a patch-rounded prefix between one-quarter and the full horizon; independent seed 300404" + ], + "weights_sha256": "1a2fb20a9fb5cae6526f2e36ea47559626bece78fd9c284899836505030ae9fe", + "config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 4, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "input_patch": 8 + }, + "training_lineage": [ + { + "checkpoint": "runs/split_patch/ema012000.pt", + "sha256": "1a2fb20a9fb5cae6526f2e36ea47559626bece78fd9c284899836505030ae9fe", + "step": 12000, + "seed": 401, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 32, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300404 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 4, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "input_patch": 8 + }, + "parents": [ + "split_patch_initial.pt" + ] + }, + { + "checkpoint": "split_patch_initial.pt", + "sha256": "0719b4dce554764ef69181d8b19d8da11849ef32b35391ffee6700e639a73114", + "step": 0, + "seed": null, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 4, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "input_patch": 8 + }, + "conversion": { + "method": "retain input8; sum query/recency halves and keep first4 output rows; same physical position coordinates", + "exact_function_preservation": false, + "parent_sha256": "308389b7217c080af9eb185559d4ee3cafa0f3e0f8c4dd8f5526b68198c89988" + }, + "parents": [ + "runs/patch8/ema006000.pt", + "runs/patch8/ema006000.pt" + ] + }, + { + "checkpoint": "runs/patch8/ema006000.pt", + "sha256": "308389b7217c080af9eb185559d4ee3cafa0f3e0f8c4dd8f5526b68198c89988", + "step": 6000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "patch8_initial.pt" + ] + }, + { + "checkpoint": "patch8_initial.pt", + "sha256": "e7da4d47a9cc984a9423296679d7c9127ef2d679be950b9e8d3758e6fca074cc", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "from_checkpoint": "/run-state/workspace/research/horizon_delta12k.pt", + "from_sha256": "22c08571978be31ba57368eb983089a40a44d56d4ae5e17da41afd2a761a258c", + "method": "fold input/query/recency halves by summation; retain first8 output rows; preserve physical position units", + "exact_function_preservation": false + }, + "parents": [ + "horizon_delta12k.pt", + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "horizon_delta12k.pt", + "sha256": "22c08571978be31ba57368eb983089a40a44d56d4ae5e17da41afd2a761a258c", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/runs/confidence_query/ema006000.pt": "0bad97e8994aac49ea173443db0a4fa8d72d33f9eb9e2660f06de75f7f1403eb", + "/workspace/research/runs/horizon_jitter/ema012000.pt": "830179d763916a1065fc615d2c5e22f4a3b5b19390dde707ab0f057e13cadff6", + "/workspace/research/runs/large_corpus_control/ema012000.pt": "7f9ba5e01ac59c51a3b63d3067b442e23e15d0abc51ddbcccdd04d6083ae4add" + }, + "seconds": 1.2663014469435439 + }, + "parents": [ + "runs/confidence_query/ema006000.pt", + "runs/horizon_jitter/ema012000.pt", + "runs/large_corpus_control/ema012000.pt" + ] + }, + { + "checkpoint": "runs/confidence_query/ema006000.pt", + "sha256": "0bad97e8994aac49ea173443db0a4fa8d72d33f9eb9e2660f06de75f7f1403eb", + "step": 6000, + "seed": 89, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 0.0002, + "steps": 6000 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true + }, + "parents": [ + "runs/recency_features/ema024000.pt" + ] + }, + { + "checkpoint": "runs/horizon_jitter/ema012000.pt", + "sha256": "830179d763916a1065fc615d2c5e22f4a3b5b19390dde707ab0f057e13cadff6", + "step": 12000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "partial_target_lengths": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/large_corpus_control/ema012000.pt", + "sha256": "7f9ba5e01ac59c51a3b63d3067b442e23e15d0abc51ddbcccdd04d6083ae4add", + "step": 12000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/recency_features/ema024000.pt", + "sha256": "1530fbb577a87ca4eb39da83d6fee9b8ee5bc924202e021e3a7b56493112f564", + "step": 24000, + "seed": 59, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/patch16_trial/ema006000.pt" + ] + }, + { + "checkpoint": "runs/recency_features/ema012000.pt", + "sha256": "8ccb6870a025e1097331a3a288b1183741a413f3460fbf3352d0c589c6a4394c", + "step": 12000, + "seed": 59, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/patch16_trial/ema006000.pt" + ] + }, + { + "checkpoint": "runs/patch16_trial/ema006000.pt", + "sha256": "0ff54447074e0271d2e331c7d3e6e9e0fdd73353e4d8cef0175ff627385f71c3", + "step": 6000, + "seed": 47, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024 + }, + "parents": [ + "patch16_init.pt" + ] + }, + { + "checkpoint": "patch16_init.pt", + "sha256": "d69531bfde5bf801e7f36c515bf15fd0cae0bd84f7d1479d35f4a7b67f26b508", + "step": 6000, + "seed": 43, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024 + }, + "conversion": { + "from_checkpoint": "/run-state/workspace/research/runs/large_sign/ema006000.pt", + "from_sha256": "96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547", + "method": "fold input/query halves by summation; retain first 16 output rows; preserve physical positional units" + }, + "parents": [ + "runs/large_sign/ema006000.pt" + ] + }, + { + "checkpoint": "runs/large_sign/ema006000.pt", + "sha256": "96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547", + "step": 6000, + "seed": 43, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 32, + "max_context": 4096, + "max_horizon": 1024 + }, + "parents": [ + "runs/direct_large/step024000.pt" + ] + }, + { + "checkpoint": "runs/direct_large/step024000.pt", + "sha256": "b7e4f38aebcd2cf38ce484edaad8d19851317fb3b8df485e2faa0d0423cbcb48", + "step": 24000, + "seed": 23, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 128, + "lr": 0.0002, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 32, + "max_context": 4096, + "max_horizon": 1024 + }, + "initialization": "random initialization in this workspace" + } + ], + "symmetric_averaging": true, + "seasonal_gate": { + "variance_ratio_threshold": 0.25, + "maximum_weight": 0.98, + "cycles_averaged": 4, + "template_mode": "aligned", + "amplitude_ratio_clip": [ + 0.5, + 2.0 + ], + "latest_cycle_minimum_coverage": 0.75, + "variance_noise_correction": "mean squared seasonal differences / 2" + }, + "continuity": { + "decay_steps": 24, + "variance_ratio_threshold": 0.5, + "maximum_weight": 0.95, + "lookback": 512, + "slope_median_differences": 8 + }, + "notes": "All training lineage originates from random initialization here, using only the declared corpus and locally generated series. Validation was used only for selection and diagnostics. Context transformations are fixed formulas; there is no inference-time fitting or parameter adaptation.", + "runtime_code_sha256": { + "infer.sh": "5fe66b4fe9a4787285d830cfd96975701e97286a75ba7c3687bd8891475edf68", + "predict.py": "9bde896945a2cd8f892e7eeb6328ed2dfda09293532f3a4a64d929c9943614ef", + "zero_mass.py": "f079d509009bcda409b80eb64467c869b838cfbab11b2bd4c660c2875b6642fe", + "continuity.py": "dbb08d2229ad80ad00f638b0b9f2f6ca13c663e0fd6730058e5fee8ff54545d5", + "seasonal.py": "b946e63048196ab5ea8b249137d48c80d8510943caccd0f180e4fb86d9b24b37", + "model.py": "89bb87b2501b117ac02daf001a68f389ec488931ce18905445d15874760685be", + "ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436" + }, + "final_training_stage": { + "trainable_scope": "all parameters", + "sign_loss": "paired", + "learning_rate_multipliers": {} + }, + "trend_summary": { + "fixed_averaging_width": 128, + "matches_all_pretraining_context_widths": true, + "independent_of_batch_padding": true + }, + "zero_mass_projection": { + "threshold_in_context_standard_deviations": 0.4, + "nonnegative_context_required": true, + "minimum_exact_zeros": 4, + "minimum_zero_fraction": 0.1, + "context_cap": 4096 + }, + "recency_features": { + "query_projection_parameters": 8192, + "latest_vs_four_cycle_level": true, + "amplitude_ratio_clip": [ + 0.5, + 2.0 + ], + "minimum_observed_cycles": 3 + }, + "confidence_features": { + "query_projection_parameters": 3072, + "backbone_frozen_during_projection_training": true, + "training_objective": "weighted quantile and median loss after averaging both sign orientations", + "statistics": [ + "mean absolute difference", + "root mean square difference" + ], + "lags": "one and the two frequency-derived periods", + "lookback": "512 for lag one; eight cycles for seasonal lags", + "minimum_valid_pairs": 8, + "insufficient_pair_defaults": [ + 1, + 1.4142135623730951 + ], + "statistic_clip": 10, + "transform": "log1p", + "stage_scope": "Frozen-backbone details refer to projection introduction; subsequent updates are recorded in training_lineage.training_settings." + }, + "partial_target_training": { + "available_horizon": "last finite training-label position rounded up to the patch boundary", + "decoder_future_key_mask": true, + "per_row_horizon_metadata": true, + "inference_uses_requested_horizon_only": true + }, + "training_provenance_code_sha256": { + "confidence_query/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "confidence_query/model.py": "b4f11ba2018e2b50879cdc33acf0138301548971508b58035a7c96a29aaa6f2d", + "confidence_query/train.py": "fc8a7555a5a6b0a6f91e80ac8cc9cbbfddaa2b26468c57f49dfb17671b22ce93", + "direct_large/data.py": "6e6db217936f8dd79380d2ceff3eaa8598a44f1b60b17acae7bfde2363116847", + "direct_large/evaluate.py": "eaea99e8cd44c9f7c70a45fa9abf51354ae5449dbad273fcb55e48ad02652223", + "direct_large/model.py": "146d93a3f95b13bda8b1b437bc36621b91356cf946e94f62999f89e7fb348071", + "direct_large/pack.py": "3bcc4ce9eb3361ad741ceebd7efce7a2fb86fb49543f52c72aabd0e3e8cd17ce", + "direct_large/predict.py": "930a9f18f9f5da47c03859698c9d2f5567d1e1c73fd61edac1ed20b3a6f9bb50", + "direct_large/publish.py": "3c167f33e8571731c26f1cb70168eda54ef9cb4c76423dfd374240b75ca5f106", + "direct_large/record.py": "b3b00b0ed14bc3af00c7b1ad97195238ecb8f06e96bc41f0c07913bc3f6ed949", + "direct_large/train.py": "b9ad6b2adddeaf12961b529d6535dd33f6d044a31979b5c9e49dceafbadd3ac0", + "direct_large/ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "direct_large/validation_subset.py": "8d3eb9d3f3aa124368761ef402ff066935c0be31a62b25b8551a45dcb922e28d", + "full_paired/check.py": "90ac1c78846439d51ab8acd62a19bd536c7c394bd02e94f6d5ff17c0af8bd116", + "full_paired/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "full_paired/model.py": "c27748fa4b1186b513f76eca26052753b8dcd1794994e5989addaf371ca70f2e", + "horizon_jitter/data.py": "5044cf648323420095ed6058d29f837c07ff5559b606df8b00cc8d1e95c8b58e", + "horizon_jitter/model.py": "186bb282236f23cc665a012194d26e58f51004c680393352ec053f5308f1240f", + "horizon_jitter/train.py": "4e9cbca1293f18f7eea2c72dba127815c0934a13c86e8f6cc881a749676d41a6", + "large_corpus/data.py": "27c078cb0ed085717a364f556b5ff976fd803d5af37612cf3a03a0a3ca12a678", + "large_corpus/model.py": "e3a1bc01e89a0d6d750ede2cc969272ad01e1ca580b174af7dee00db029f1cf7", + "large_corpus/train.py": "3baca16c3945e6ef241ccbc9c13644539e3c265f71095cbbaa61a3d338e4fafe", + "large_sign/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "large_sign/evaluate.py": "eaea99e8cd44c9f7c70a45fa9abf51354ae5449dbad273fcb55e48ad02652223", + "large_sign/model.py": "3fff6445a1982a1b3c92f06a9b5f1bb627dda6a291b0b2364bcfb1a6457830d7", + "large_sign/pack.py": "3bcc4ce9eb3361ad741ceebd7efce7a2fb86fb49543f52c72aabd0e3e8cd17ce", + "large_sign/predict.py": "930a9f18f9f5da47c03859698c9d2f5567d1e1c73fd61edac1ed20b3a6f9bb50", + "large_sign/publish.py": "3c167f33e8571731c26f1cb70168eda54ef9cb4c76423dfd374240b75ca5f106", + "large_sign/record.py": "b3b00b0ed14bc3af00c7b1ad97195238ecb8f06e96bc41f0c07913bc3f6ed949", + "large_sign/train.py": "a597f40ab87cce04e96dc654d12e56cdf40ffd87f00034d8bc4d56dff4eb7c68", + "large_sign/ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "large_sign/validation_subset.py": "8d3eb9d3f3aa124368761ef402ff066935c0be31a62b25b8551a45dcb922e28d", + "partial_delta/merge.py": "63984a0f46f7d48817037f5bf5a1c9319e45a9b1924cde62c667ac49ce47532e", + "partial_targets/data.py": "27c078cb0ed085717a364f556b5ff976fd803d5af37612cf3a03a0a3ca12a678", + "partial_targets/model.py": "186bb282236f23cc665a012194d26e58f51004c680393352ec053f5308f1240f", + "partial_targets/train.py": "3baca16c3945e6ef241ccbc9c13644539e3c265f71095cbbaa61a3d338e4fafe", + "patch16/convert.py": "11e1d30100ab25311020ac1f4ab8227ec66156836df5de613300867977091c45", + "patch16/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "patch16/evaluate.py": "eaea99e8cd44c9f7c70a45fa9abf51354ae5449dbad273fcb55e48ad02652223", + "patch16/model.py": "8031c597b354eb2cf464140bee40c3ec8dff86c775b5c55c5ce910302b443582", + "patch16/pack.py": "3bcc4ce9eb3361ad741ceebd7efce7a2fb86fb49543f52c72aabd0e3e8cd17ce", + "patch16/predict.py": "930a9f18f9f5da47c03859698c9d2f5567d1e1c73fd61edac1ed20b3a6f9bb50", + "patch16/publish.py": "3c167f33e8571731c26f1cb70168eda54ef9cb4c76423dfd374240b75ca5f106", + "patch16/record.py": "b3b00b0ed14bc3af00c7b1ad97195238ecb8f06e96bc41f0c07913bc3f6ed949", + "patch16/train.py": "3156710f76111a31447cbe638ee27fe2811d060917aa083aab0b5134d98accf8", + "patch16/ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "patch16/validation_subset.py": "8d3eb9d3f3aa124368761ef402ff066935c0be31a62b25b8551a45dcb922e28d", + "patch8/convert.py": "9edaa0c8349310b7419d649fb4f21dd3ddb9067ebe984d5df3701a234be73780", + "patch8/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "patch8/memory_check.py": "78e8e5cca960bf1225ec0104980363c82f4c3c13c2d77ed154cea37a5b6f3fd1", + "patch8/model.py": "c27748fa4b1186b513f76eca26052753b8dcd1794994e5989addaf371ca70f2e", + "recency_features/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "recency_features/model.py": "e3a1bc01e89a0d6d750ede2cc969272ad01e1ca580b174af7dee00db029f1cf7", + "recency_features/train.py": "a654b9a27b6c27141e1d4e517ab28fcae3f2c23d061742fa2f6c01e3d23c8a00", + "recovery/capacity_curves.py": "2bdc6635705b70a868e115cd13eb529563acacf6f47c71f250a50dce8e943be4", + "recovery/exposure_audit.py": "54c194a626b8876ece84686b39b22360155c9fada7248a393ca9b7d6ee38002b", + "recovery/relaunch_20261022b.py": "f90ddd77928a793c8e151ba74cfa9cc84c8aefad0c0d943a833c74bc07b79313", + "recovery/relaunch_20261023.py": "a4c40c5674b0d05cfe9bb1fffe907f02dec16c53cbddb8b86efbba1b96649097", + "recovery/schedules.py": "7748fd6b2bbbe64037472faf7e6583d03cf339138d2f3c07b1bac9e65bf2d4f5", + "recovery/snapshot.py": "0f241a7e139e47ffff7efea40572205fd84c12efe6fb3c2dccd87c50d678a6c3", + "recovery/train.py": "63bee736565af670877b4cd7c75015fab06a18c66bbe132b0bb3faff5ebd80c7", + "split_patch/check.py": "2e0917eec4b70741da84f62ba19d709229fefa29fd46a8b85dd91976952560f9", + "split_patch/convert.py": "115b3f518a2157529a3c26143dabd736abc8494b7f20cdd9bea57d569d77c36e", + "split_patch/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "split_patch/launch.py": "014b171e8b8dc1f4b84242a02813af1ee8b26c3b4dc839148718caf36d77ae77", + "split_patch/memory_check.py": "8a6f6af761ac37fb5118f71e38bba0ca5c446e5c1203b9e156657e7d68a5d3e9", + "split_patch/model.py": "89bb87b2501b117ac02daf001a68f389ec488931ce18905445d15874760685be" + } +} diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/confidence_query/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/confidence_query/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/confidence_query/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/confidence_query/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/confidence_query/model.py new file mode 100644 index 0000000000000000000000000000000000000000..b881039b3752b3396e06415a8d01d24956fa29a7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/confidence_query/model.py @@ -0,0 +1,190 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + if self.recency is not None: + pos=torch.arange(c,device=z.device)[None,:];extras=[] + for j in range(2): + period=periods[:,j:j+1] + recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + n=ctx.shape[0] + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1]) + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/confidence_query/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/confidence_query/train.py new file mode 100644 index 0000000000000000000000000000000000000000..fd9d2a3a0502cee1a67c41c832266c7f87cc5a80 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/confidence_query/train.py @@ -0,0 +1,54 @@ +"""Train only confidence-query features on a frozen model, using paired-sign forecast loss.""" +import argparse,json,math,time,os +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) +ap.add_argument('--initialize-from',required=True);ap.add_argument('--steps',type=int,default=6000) +ap.add_argument('--batch',type=int,default=128);ap.add_argument('--lr',type=float,default=2e-4) +ap.add_argument('--seed',type=int,default=89);ap.add_argument('--save-every',type=int,default=1000);a=ap.parse_args() +torch.set_num_threads(1);torch.manual_seed(a.seed);torch.backends.cuda.matmul.allow_tf32=True +out=Path(a.out);out.mkdir(parents=True,exist_ok=True) +ck=torch.load(a.initialize_from,map_location='cpu',weights_only=False) +config={**ck['config'],'confidence_features':True};model=DirectForecaster(**config).cuda() +missing,unexpected=model.load_state_dict(ck['model'],strict=False) +assert not unexpected and all(k.startswith('confidence.') for k in missing) +for name,param in model.named_parameters():param.requires_grad_(name.startswith('confidence.')) +params=[p for p in model.parameters() if p.requires_grad] +opt=torch.optim.AdamW(params,lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) +ema={k:v.detach().clone() for k,v in model.state_dict().items()};sampler=Sampler(a.packed,seed=a.seed) +(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)) +rng=np.random.default_rng(a.seed) +def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) +def save(step): + for prefix,weights in [('step',model.state_dict()),('ema',ema)]: + state={'model':weights,'config':model.config,'step':step,'args':vars(a),'ema':prefix=='ema'} + path=out/f'{prefix}{step:06d}.pt';torch.save(state,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) +save(0);pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] +for step in range(1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch);x,y,p=[torch.from_numpy(x).cuda() for x in arrays] + lr=a.lr*min(1,step/200)*(.2+.8*.5*(1+math.cos(math.pi*step/a.steps))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(params,1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items(): + if k.startswith('confidence.'):ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + if step%a.save_every==0 or step==a.steps:save(step) +pool.shutdown() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/direct_large/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/direct_large/data.py new file mode 100644 index 0000000000000000000000000000000000000000..2378e33d7352ba5ad97d566148782e63e64b367c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/direct_large/data.py @@ -0,0 +1,71 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + return ctx,tgt,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/direct_large/evaluate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/direct_large/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..05f086d4d84def4a48165f9e65d2948877675e56 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/direct_large/evaluate.py @@ -0,0 +1,16 @@ +import sys,json,argparse,time,hashlib +from pathlib import Path +import torch +from predict import load_model,run +sys.path.insert(0,'/workspace/evaluation') +from score import score,json_safe + +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);ap.add_argument('--valid',default='/workspace/research/valid_screen');ap.add_argument('--baseline',default='/workspace/research/valid_screen/baseline.json');a=ap.parse_args() +torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cuda.matmul.allow_tf32=False +t0=time.time();out=Path(a.out);v=Path(a.valid) +run(load_model(a.weights),v/'input',out) +base=json.loads(Path(a.baseline).read_text())['configs'] +rep=score(v/'truth',out,base) +rep['checkpoint_sha256']=hashlib.sha256(Path(a.weights).read_bytes()).hexdigest();rep['eval_seconds']=time.time()-t0 +(out/'report.json').write_text(json.dumps(json_safe(rep),indent=1)) +print(json.dumps({k:rep[k] for k in ('skill_score','rel_mase_gmean','rel_wql_gmean','n_failed','groups','eval_seconds')},indent=1)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/direct_large/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/direct_large/model.py new file mode 100644 index 0000000000000000000000000000000000000000..7a224cc12a159446a1e427b2052b53d1d1f7e83e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/direct_large/model.py @@ -0,0 +1,142 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional(torch.arange(-nt,0,device=z.device),self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + q=self.query(base.reshape(b,h//p,p*9))+positional(torch.arange(h//p,device=z.device),self.d)[None]+emb + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + pin=torch.maximum(levels*err,(levels-1)*err).mean(-1) + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + return per.mean() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/direct_large/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/direct_large/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/direct_large/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/direct_large/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/direct_large/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..e20c6630475d6b4fa6906eb4ed9454b7b5aeec2c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/direct_large/predict.py @@ -0,0 +1,43 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):q=model.predict(x,p,h).float().cpu().numpy() + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/direct_large/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/direct_large/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf95c9aec5936076b881c340edb960786f2d40d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/direct_large/publish.py @@ -0,0 +1,31 @@ +"""Assemble a relocatable package, then atomically exchange complete directories.""" +import json,os,shutil,ctypes,hashlib,argparse +from pathlib import Path +import torch +HERE=Path(__file__).resolve().parent + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',default='/workspace/submission');ap.add_argument('--report',required=True);ap.add_argument('--experiments',default=str(HERE/'EXPERIMENTS.md'));a=ap.parse_args() + final=Path(a.out);staging=final.parent/f'.{final.name}-staging-{os.getpid()}' + shutil.rmtree(staging,ignore_errors=True);staging.mkdir(parents=True) + for file in ('model.py','predict.py','infer.sh','ts_io.py'): + shutil.copy(HERE/file,staging/file) + shutil.copy(a.weights,staging/'weights.pt');shutil.copy('/opt/runtime/requirements.txt',staging/'requirements.txt') + ck=torch.load(a.weights,map_location='cpu',weights_only=False);digest=hashlib.sha256((staging/'weights.pt').read_bytes()).hexdigest() + sources=json.loads(Path('/workspace/research/packed_sample/meta.json').read_text())['dirs'] + manifest={'name':'direct-seasonal-quantile-v1','contract':'timeseries-forecast/v1','parameters':sum(x.numel() for x in ck['model'].values()),'pretrained_assets':[],'sources_used':[f'gifteval_pretrain/{d}' for d in sources]+['synthetic:direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; data.py generator seed 17'],'weights_sha256':digest,'training_step':ck['step'],'config':ck['config'],'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.'} + (staging/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') + (staging/'config.json').write_text(json.dumps(ck['config'],indent=2)+'\n') + shutil.copy(a.experiments,staging/'EXPERIMENTS.md');shutil.copy(a.report,staging/'validation_report.json') + # Include generator/sampler provenance, which is not imported by inference. + (staging/'provenance').mkdir() + for file in ('pack.py','data.py','train.py'):shutil.copy(HERE/file,staging/'provenance'/file) + (staging/'README.md').write_text('# Direct seasonal quantile foundation forecaster\n\nRun `bash infer.sh INPUT_DIR OUTPUT_DIR`. This package contains all inference assets and uses only its supplied input directory. The 6.76M 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.\n\nThe 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.\n') + if final.exists(): + libc=ctypes.CDLL(None,use_errno=True) + if libc.renameat2(-100,os.fsencode(staging),-100,os.fsencode(final),2):raise OSError(ctypes.get_errno(),os.strerror(ctypes.get_errno())) + shutil.rmtree(staging) + else:os.replace(staging,final) + print(json.dumps(manifest,indent=1)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/direct_large/record.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/direct_large/record.py new file mode 100644 index 0000000000000000000000000000000000000000..1850a33f46fa3ee4d78cac4a5d6152404801a131 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/direct_large/record.py @@ -0,0 +1,9 @@ +import argparse,json,math +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('report');ap.add_argument('--label',required=True);ap.add_argument('--outcome',default='Screened for model selection.');a=ap.parse_args() +r=json.loads(Path(a.report).read_text());p=Path(__file__).with_name('EXPERIMENTS.md') +lines=[f'\n## {a.label}',f'- Checkpoint SHA-256: `{r.get("checkpoint_sha256","see model_manifest.json")}`.',f'- Evaluation: {r["n_configs"]} configurations, {r["n_instances"]} instances, {r["n_failed"]} failed configurations; {r.get("eval_seconds","not separately timed")} seconds.',f'- Overall skill {r["skill_score"]:.6f}; relative MASE {r["rel_mase_gmean"]:.6f}; relative WQL {r["rel_wql_gmean"]:.6f}.'] +for group,entries in r['groups'].items(): + lines.append(f'- {group} skill: '+', '.join(f'{k}={1-math.sqrt(v["rel_mase_gmean"]*v["rel_wql_gmean"]):.4f}' for k,v in entries.items())+'.') +lines.append('- Outcome: '+a.outcome) +with p.open('a') as f:f.write('\n'.join(lines)+'\n') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/direct_large/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/direct_large/train.py new file mode 100644 index 0000000000000000000000000000000000000000..a2ccc736bfef804259199a2dd315347d9854b680 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/direct_large/train.py @@ -0,0 +1,67 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(6);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/direct_large/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/direct_large/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/direct_large/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/direct_large/validation_subset.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/direct_large/validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..4df83e69c4f9a3365955e5d17ffcfc0af71372b7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/direct_large/validation_subset.py @@ -0,0 +1,18 @@ +"""Model-selection-only subset spanning all 97 configurations, seed 2026.""" +import sys,json,copy +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +import ts_io + +root=Path('/workspace/data/valid');out=Path('/workspace/research/valid_screen') +idx=json.loads((root/'input/index.json').read_text());new=copy.deepcopy(idx);rng=np.random.default_rng(2026) +for cfg in new['configs']: + cid=cfg['config_id'];case=ts_io.CaseFile(root/'input/cases'/f'{cid}.h5') + ids=np.sort(rng.choice(case.n,min(case.n,192),replace=False)) + ts_io.write_case_subset(case,ids,out/'input/cases'/f'{cid}.h5') + lab,se,meta=ts_io.read_truth_file(root/'truth/cases'/f'{cid}.h5') + ts_io.write_truth_file(out/'truth/cases'/f'{cid}.h5',lab[ids],se[ids],meta) + cfg['n_instances']=len(ids);case.close() +for kind in ('input','truth'):(out/kind/'index.json').write_text(json.dumps(new,indent=1)) +print('screen instances',sum(c['n_instances'] for c in new['configs'])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/full_paired/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/full_paired/check.py new file mode 100644 index 0000000000000000000000000000000000000000..fda928e16338305fd9912f7bc08cacff58bd8aa4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/full_paired/check.py @@ -0,0 +1,34 @@ +import importlib.util,json,time +from pathlib import Path +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +r=Path('/workspace/research');torch.set_num_threads(1);torch.manual_seed(197);start=time.monotonic() +ck=torch.load(r/'horizon_delta12k.pt',map_location='cpu',weights_only=False) +spec=importlib.util.spec_from_file_location('parent_model',r/'confidence_inference/model.py') +old=importlib.util.module_from_spec(spec);spec.loader.exec_module(old) +parent=old.DirectForecaster(**ck['config']);parent.load_state_dict(ck['model']) +m=DirectForecaster(**ck['config']);m.load_state_dict(ck['model']) +x=torch.randn(4,512);x[0,:50]=float('nan');p=torch.tensor([[24,168]]*4);y=torch.randn(4,128);y[0,32:]=float('nan') +with torch.inference_mode(): + assert all(torch.equal(a,b) for a,b in zip(m(x,p,48),parent(x,p,48))) + short=m(x,p,32)[0];long=m(x,p,128,forecast_lengths=torch.full((4,),32))[0][:,:32] + assert torch.allclose(short,long,atol=3e-6,rtol=1e-6),(short-long).abs().max() + paired=float(loss_fn(m,x,y,p,paired=True));reverse=float(loss_fn(m,-x,-y,p,paired=True)) + assert abs(paired-reverse)<1e-7,(paired,reverse) +a=Sampler(r/'packed_sample',197);b=Sampler(r/'packed_sample',197) +for c,h in [(512,32),(4096,1024)]: + assert all(np.array_equal(v,w,equal_nan=True) for v,w in zip(a.sample(16,c,h),b.sample(16,c,h))) +assert a.rng.bit_generator.state==b.rng.bit_generator.state and a.horizon_rng.bit_generator.state==b.horizon_rng.bit_generator.state +cpu=time.monotonic()-start;del parent,ck,a,b +m=m.cuda();ema={k:v.detach().clone() for k,v in m.state_dict().items()} +moments=[torch.zeros_like(v) for v in m.parameters() for _ in range(2)] +torch.backends.cuda.matmul.allow_tf32=True;torch.cuda.reset_peak_memory_stats();start=time.monotonic() +x=torch.randn(64,4096,device='cuda');y=torch.randn(64,1024,device='cuda');p=torch.tensor([[24,168]]*64,device='cuda') +with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(m,x,y,p,paired=True) +loss.backward();torch.cuda.synchronize() +assert torch.isfinite(loss) and all(v.grad is not None and torch.isfinite(v.grad).all() for v in m.parameters()) +z={'cpu_seconds':cpu,'initial_forecast_bitwise_parent':True,'unused_future_tokens_do_not_change_requested_prefix':True,'paired_loss_sign_symmetric':True,'matched_sampler_main_and_horizon_rng':True,'gpu_fixture_seconds':time.monotonic()-start,'allocated_mib':torch.cuda.max_memory_allocated()/2**20,'reserved_mib':torch.cuda.max_memory_reserved()/2**20,'optimizer_updates':0} +(r/'full_paired_checks.json').write_text(json.dumps(z,indent=2));print(json.dumps(z),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/full_paired/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/full_paired/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/full_paired/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/full_paired/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/full_paired/model.py new file mode 100644 index 0000000000000000000000000000000000000000..dedcdff4698028a8ba655865f8425d0dc3ef0dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/full_paired/model.py @@ -0,0 +1,204 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/horizon_jitter/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/horizon_jitter/data.py new file mode 100644 index 0000000000000000000000000000000000000000..3d632af7e96a71f30b7964a2b3fd73bc1c3f3f3e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/horizon_jitter/data.py @@ -0,0 +1,86 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/horizon_jitter/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/horizon_jitter/model.py new file mode 100644 index 0000000000000000000000000000000000000000..4ffe50d9aadf21d73949e2052ceb7f3642bf65d3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/horizon_jitter/model.py @@ -0,0 +1,180 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(ctx,periods,target.shape[-1],forecast_lengths=lengths) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/horizon_jitter/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/horizon_jitter/train.py new file mode 100644 index 0000000000000000000000000000000000000000..768d33da4421b24bd760d7d9680d0c2cd9bd84e4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/horizon_jitter/train.py @@ -0,0 +1,74 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler,truncate_targets + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + horizon_rng=np.random.default_rng(a.seed+startstep+300003) + def nextbatch(): + 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])) + return truncate_targets(sampler.sample(a.batch,c,h),horizon_rng,a.patch) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_corpus/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_corpus/data.py new file mode 100644 index 0000000000000000000000000000000000000000..a51e912d3c4b63a3ec0cd85133bf0e7aa3429569 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_corpus/data.py @@ -0,0 +1,73 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_corpus/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_corpus/model.py new file mode 100644 index 0000000000000000000000000000000000000000..f8271c5b0bf9a5edb961e1c7839761fe50a2e40b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_corpus/model.py @@ -0,0 +1,171 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024,recency_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + if self.recency is not None: + pos=torch.arange(c,device=z.device)[None,:];extras=[] + for j in range(2): + period=periods[:,j:j+1] + recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_corpus/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_corpus/train.py new file mode 100644 index 0000000000000000000000000000000000000000..2e77612e443d78dd80bcb6a0cc6d01169f61a3a4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_corpus/train.py @@ -0,0 +1,73 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_sign/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_sign/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_sign/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_sign/evaluate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_sign/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..05f086d4d84def4a48165f9e65d2948877675e56 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_sign/evaluate.py @@ -0,0 +1,16 @@ +import sys,json,argparse,time,hashlib +from pathlib import Path +import torch +from predict import load_model,run +sys.path.insert(0,'/workspace/evaluation') +from score import score,json_safe + +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);ap.add_argument('--valid',default='/workspace/research/valid_screen');ap.add_argument('--baseline',default='/workspace/research/valid_screen/baseline.json');a=ap.parse_args() +torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cuda.matmul.allow_tf32=False +t0=time.time();out=Path(a.out);v=Path(a.valid) +run(load_model(a.weights),v/'input',out) +base=json.loads(Path(a.baseline).read_text())['configs'] +rep=score(v/'truth',out,base) +rep['checkpoint_sha256']=hashlib.sha256(Path(a.weights).read_bytes()).hexdigest();rep['eval_seconds']=time.time()-t0 +(out/'report.json').write_text(json.dumps(json_safe(rep),indent=1)) +print(json.dumps({k:rep[k] for k in ('skill_score','rel_mase_gmean','rel_wql_gmean','n_failed','groups','eval_seconds')},indent=1)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_sign/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_sign/model.py new file mode 100644 index 0000000000000000000000000000000000000000..60aeb14b5f4fa298521ddce8a3276d076c1bb631 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_sign/model.py @@ -0,0 +1,154 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional(torch.arange(-nt,0,device=z.device),self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + q=self.query(base.reshape(b,h//p,p*9))+positional(torch.arange(h//p,device=z.device),self.d)[None]+emb + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_sign/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_sign/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_sign/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_sign/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_sign/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..e20c6630475d6b4fa6906eb4ed9454b7b5aeec2c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_sign/predict.py @@ -0,0 +1,43 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):q=model.predict(x,p,h).float().cpu().numpy() + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_sign/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_sign/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf95c9aec5936076b881c340edb960786f2d40d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_sign/publish.py @@ -0,0 +1,31 @@ +"""Assemble a relocatable package, then atomically exchange complete directories.""" +import json,os,shutil,ctypes,hashlib,argparse +from pathlib import Path +import torch +HERE=Path(__file__).resolve().parent + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',default='/workspace/submission');ap.add_argument('--report',required=True);ap.add_argument('--experiments',default=str(HERE/'EXPERIMENTS.md'));a=ap.parse_args() + final=Path(a.out);staging=final.parent/f'.{final.name}-staging-{os.getpid()}' + shutil.rmtree(staging,ignore_errors=True);staging.mkdir(parents=True) + for file in ('model.py','predict.py','infer.sh','ts_io.py'): + shutil.copy(HERE/file,staging/file) + shutil.copy(a.weights,staging/'weights.pt');shutil.copy('/opt/runtime/requirements.txt',staging/'requirements.txt') + ck=torch.load(a.weights,map_location='cpu',weights_only=False);digest=hashlib.sha256((staging/'weights.pt').read_bytes()).hexdigest() + sources=json.loads(Path('/workspace/research/packed_sample/meta.json').read_text())['dirs'] + manifest={'name':'direct-seasonal-quantile-v1','contract':'timeseries-forecast/v1','parameters':sum(x.numel() for x in ck['model'].values()),'pretrained_assets':[],'sources_used':[f'gifteval_pretrain/{d}' for d in sources]+['synthetic:direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; data.py generator seed 17'],'weights_sha256':digest,'training_step':ck['step'],'config':ck['config'],'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.'} + (staging/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') + (staging/'config.json').write_text(json.dumps(ck['config'],indent=2)+'\n') + shutil.copy(a.experiments,staging/'EXPERIMENTS.md');shutil.copy(a.report,staging/'validation_report.json') + # Include generator/sampler provenance, which is not imported by inference. + (staging/'provenance').mkdir() + for file in ('pack.py','data.py','train.py'):shutil.copy(HERE/file,staging/'provenance'/file) + (staging/'README.md').write_text('# Direct seasonal quantile foundation forecaster\n\nRun `bash infer.sh INPUT_DIR OUTPUT_DIR`. This package contains all inference assets and uses only its supplied input directory. The 6.76M 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.\n\nThe 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.\n') + if final.exists(): + libc=ctypes.CDLL(None,use_errno=True) + if libc.renameat2(-100,os.fsencode(staging),-100,os.fsencode(final),2):raise OSError(ctypes.get_errno(),os.strerror(ctypes.get_errno())) + shutil.rmtree(staging) + else:os.replace(staging,final) + print(json.dumps(manifest,indent=1)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_sign/record.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_sign/record.py new file mode 100644 index 0000000000000000000000000000000000000000..1850a33f46fa3ee4d78cac4a5d6152404801a131 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_sign/record.py @@ -0,0 +1,9 @@ +import argparse,json,math +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('report');ap.add_argument('--label',required=True);ap.add_argument('--outcome',default='Screened for model selection.');a=ap.parse_args() +r=json.loads(Path(a.report).read_text());p=Path(__file__).with_name('EXPERIMENTS.md') +lines=[f'\n## {a.label}',f'- Checkpoint SHA-256: `{r.get("checkpoint_sha256","see model_manifest.json")}`.',f'- Evaluation: {r["n_configs"]} configurations, {r["n_instances"]} instances, {r["n_failed"]} failed configurations; {r.get("eval_seconds","not separately timed")} seconds.',f'- Overall skill {r["skill_score"]:.6f}; relative MASE {r["rel_mase_gmean"]:.6f}; relative WQL {r["rel_wql_gmean"]:.6f}.'] +for group,entries in r['groups'].items(): + lines.append(f'- {group} skill: '+', '.join(f'{k}={1-math.sqrt(v["rel_mase_gmean"]*v["rel_wql_gmean"]):.4f}' for k,v in entries.items())+'.') +lines.append('- Outcome: '+a.outcome) +with p.open('a') as f:f.write('\n'.join(lines)+'\n') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_sign/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_sign/train.py new file mode 100644 index 0000000000000000000000000000000000000000..d089166fb1612ddf4955fcd2f096cb0b33624dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_sign/train.py @@ -0,0 +1,70 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(3);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_sign/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_sign/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_sign/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_sign/validation_subset.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_sign/validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..4df83e69c4f9a3365955e5d17ffcfc0af71372b7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/large_sign/validation_subset.py @@ -0,0 +1,18 @@ +"""Model-selection-only subset spanning all 97 configurations, seed 2026.""" +import sys,json,copy +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +import ts_io + +root=Path('/workspace/data/valid');out=Path('/workspace/research/valid_screen') +idx=json.loads((root/'input/index.json').read_text());new=copy.deepcopy(idx);rng=np.random.default_rng(2026) +for cfg in new['configs']: + cid=cfg['config_id'];case=ts_io.CaseFile(root/'input/cases'/f'{cid}.h5') + ids=np.sort(rng.choice(case.n,min(case.n,192),replace=False)) + ts_io.write_case_subset(case,ids,out/'input/cases'/f'{cid}.h5') + lab,se,meta=ts_io.read_truth_file(root/'truth/cases'/f'{cid}.h5') + ts_io.write_truth_file(out/'truth/cases'/f'{cid}.h5',lab[ids],se[ids],meta) + cfg['n_instances']=len(ids);case.close() +for kind in ('input','truth'):(out/kind/'index.json').write_text(json.dumps(new,indent=1)) +print('screen instances',sum(c['n_instances'] for c in new['configs'])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/partial_delta/merge.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/partial_delta/merge.py new file mode 100644 index 0000000000000000000000000000000000000000..3dde47d52d25ed2b013942b3887f1bf686e42ed8 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/partial_delta/merge.py @@ -0,0 +1,16 @@ +"""Apply the difference of two matched, locally trained checkpoints to our selected model.""" +import argparse,torch,hashlib,json,time +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('--base',required=True);ap.add_argument('--candidate',required=True);ap.add_argument('--control',required=True);ap.add_argument('--out',required=True);a=ap.parse_args() +torch.set_num_threads(1);start=time.monotonic() +base=torch.load(a.base,map_location='cpu',weights_only=False);candidate=torch.load(a.candidate,map_location='cpu',weights_only=False);control=torch.load(a.control,map_location='cpu',weights_only=False) +assert set(candidate['model'])==set(control['model']) +weights={k:v.clone() for k,v in base['model'].items()} +for k in candidate['model']: + assert k in weights and weights[k].shape==candidate['model'][k].shape==control['model'][k].shape + weights[k].add_(candidate['model'][k]-control['model'][k]) +assert all(torch.isfinite(v).all() for v in weights.values()) +parents=[a.base,a.candidate,a.control] +conversion={'method':'matched training delta','formula':'base + candidate - control','coefficient':1.0,'parent_hashes':{p:hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in parents},'seconds':time.monotonic()-start} +ck={'model':weights,'config':base['config'],'step':0,'args':{'packed':base['args']['packed']},'parent_checkpoints':parents,'conversion':conversion} +torch.save(ck,a.out);print(json.dumps(conversion)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/partial_targets/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/partial_targets/data.py new file mode 100644 index 0000000000000000000000000000000000000000..a51e912d3c4b63a3ec0cd85133bf0e7aa3429569 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/partial_targets/data.py @@ -0,0 +1,73 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/partial_targets/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/partial_targets/model.py new file mode 100644 index 0000000000000000000000000000000000000000..4ffe50d9aadf21d73949e2052ceb7f3642bf65d3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/partial_targets/model.py @@ -0,0 +1,180 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(ctx,periods,target.shape[-1],forecast_lengths=lengths) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/partial_targets/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/partial_targets/train.py new file mode 100644 index 0000000000000000000000000000000000000000..2e77612e443d78dd80bcb6a0cc6d01169f61a3a4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/partial_targets/train.py @@ -0,0 +1,73 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/convert.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/convert.py new file mode 100644 index 0000000000000000000000000000000000000000..b2cbc8fc919be6a77eca9ab19c4faa06060a2e0d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/convert.py @@ -0,0 +1,18 @@ +"""Convert only our own trained checkpoint from 32- to 16-point patches. + +Context/query projections fold the two halves by summation, preserving the +embedding of constant features. The output projection keeps the first half. +Attention/MLP weights are inherited unchanged; position units remain 32 points. +""" +import argparse,torch,hashlib +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('--input',required=True);ap.add_argument('--output',required=True);a=ap.parse_args() +ck=torch.load(a.input,map_location='cpu',weights_only=False);state=ck['model'];d=ck['config']['d'];assert ck['config']['patch']==32 +old=state['embed.0.weight'].reshape(d,2,32);state['embed.0.weight']=(old[:,:,:16]+old[:,:,16:]).reshape(d,32) +old=state['query.0.weight'].reshape(d,32,9);state['query.0.weight']=(old[:,:16]+old[:,16:]).reshape(d,16*9) +state['head.weight']=state['head.weight'].reshape(32,18,d)[:16].reshape(16*18,d).clone() +state['head.bias']=state['head.bias'].reshape(32,18)[:16].reshape(16*18).clone() +ck['config']['patch']=16 +ck['conversion']={'from_checkpoint':str(Path(a.input).resolve()),'from_sha256':hashlib.sha256(Path(a.input).read_bytes()).hexdigest(),'method':'fold input/query halves by summation; retain first 16 output rows; preserve physical positional units'} +ck['args']={**ck['args'],'initialize_from':str(Path(a.input).resolve()),'converted':True} +torch.save(ck,a.output) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/evaluate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..05f086d4d84def4a48165f9e65d2948877675e56 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/evaluate.py @@ -0,0 +1,16 @@ +import sys,json,argparse,time,hashlib +from pathlib import Path +import torch +from predict import load_model,run +sys.path.insert(0,'/workspace/evaluation') +from score import score,json_safe + +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);ap.add_argument('--valid',default='/workspace/research/valid_screen');ap.add_argument('--baseline',default='/workspace/research/valid_screen/baseline.json');a=ap.parse_args() +torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cuda.matmul.allow_tf32=False +t0=time.time();out=Path(a.out);v=Path(a.valid) +run(load_model(a.weights),v/'input',out) +base=json.loads(Path(a.baseline).read_text())['configs'] +rep=score(v/'truth',out,base) +rep['checkpoint_sha256']=hashlib.sha256(Path(a.weights).read_bytes()).hexdigest();rep['eval_seconds']=time.time()-t0 +(out/'report.json').write_text(json.dumps(json_safe(rep),indent=1)) +print(json.dumps({k:rep[k] for k in ('skill_score','rel_mase_gmean','rel_wql_gmean','n_failed','groups','eval_seconds')},indent=1)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/model.py new file mode 100644 index 0000000000000000000000000000000000000000..06cce56e2ce671b6683f0246900abfcac06bb3c0 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/model.py @@ -0,0 +1,154 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..e20c6630475d6b4fa6906eb4ed9454b7b5aeec2c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/predict.py @@ -0,0 +1,43 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):q=model.predict(x,p,h).float().cpu().numpy() + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf95c9aec5936076b881c340edb960786f2d40d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/publish.py @@ -0,0 +1,31 @@ +"""Assemble a relocatable package, then atomically exchange complete directories.""" +import json,os,shutil,ctypes,hashlib,argparse +from pathlib import Path +import torch +HERE=Path(__file__).resolve().parent + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',default='/workspace/submission');ap.add_argument('--report',required=True);ap.add_argument('--experiments',default=str(HERE/'EXPERIMENTS.md'));a=ap.parse_args() + final=Path(a.out);staging=final.parent/f'.{final.name}-staging-{os.getpid()}' + shutil.rmtree(staging,ignore_errors=True);staging.mkdir(parents=True) + for file in ('model.py','predict.py','infer.sh','ts_io.py'): + shutil.copy(HERE/file,staging/file) + shutil.copy(a.weights,staging/'weights.pt');shutil.copy('/opt/runtime/requirements.txt',staging/'requirements.txt') + ck=torch.load(a.weights,map_location='cpu',weights_only=False);digest=hashlib.sha256((staging/'weights.pt').read_bytes()).hexdigest() + sources=json.loads(Path('/workspace/research/packed_sample/meta.json').read_text())['dirs'] + manifest={'name':'direct-seasonal-quantile-v1','contract':'timeseries-forecast/v1','parameters':sum(x.numel() for x in ck['model'].values()),'pretrained_assets':[],'sources_used':[f'gifteval_pretrain/{d}' for d in sources]+['synthetic:direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; data.py generator seed 17'],'weights_sha256':digest,'training_step':ck['step'],'config':ck['config'],'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.'} + (staging/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') + (staging/'config.json').write_text(json.dumps(ck['config'],indent=2)+'\n') + shutil.copy(a.experiments,staging/'EXPERIMENTS.md');shutil.copy(a.report,staging/'validation_report.json') + # Include generator/sampler provenance, which is not imported by inference. + (staging/'provenance').mkdir() + for file in ('pack.py','data.py','train.py'):shutil.copy(HERE/file,staging/'provenance'/file) + (staging/'README.md').write_text('# Direct seasonal quantile foundation forecaster\n\nRun `bash infer.sh INPUT_DIR OUTPUT_DIR`. This package contains all inference assets and uses only its supplied input directory. The 6.76M 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.\n\nThe 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.\n') + if final.exists(): + libc=ctypes.CDLL(None,use_errno=True) + if libc.renameat2(-100,os.fsencode(staging),-100,os.fsencode(final),2):raise OSError(ctypes.get_errno(),os.strerror(ctypes.get_errno())) + shutil.rmtree(staging) + else:os.replace(staging,final) + print(json.dumps(manifest,indent=1)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/record.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/record.py new file mode 100644 index 0000000000000000000000000000000000000000..1850a33f46fa3ee4d78cac4a5d6152404801a131 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/record.py @@ -0,0 +1,9 @@ +import argparse,json,math +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('report');ap.add_argument('--label',required=True);ap.add_argument('--outcome',default='Screened for model selection.');a=ap.parse_args() +r=json.loads(Path(a.report).read_text());p=Path(__file__).with_name('EXPERIMENTS.md') +lines=[f'\n## {a.label}',f'- Checkpoint SHA-256: `{r.get("checkpoint_sha256","see model_manifest.json")}`.',f'- Evaluation: {r["n_configs"]} configurations, {r["n_instances"]} instances, {r["n_failed"]} failed configurations; {r.get("eval_seconds","not separately timed")} seconds.',f'- Overall skill {r["skill_score"]:.6f}; relative MASE {r["rel_mase_gmean"]:.6f}; relative WQL {r["rel_wql_gmean"]:.6f}.'] +for group,entries in r['groups'].items(): + lines.append(f'- {group} skill: '+', '.join(f'{k}={1-math.sqrt(v["rel_mase_gmean"]*v["rel_wql_gmean"]):.4f}' for k,v in entries.items())+'.') +lines.append('- Outcome: '+a.outcome) +with p.open('a') as f:f.write('\n'.join(lines)+'\n') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/train.py new file mode 100644 index 0000000000000000000000000000000000000000..3cdc106980371c99d81c71d6746943c47206be83 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/train.py @@ -0,0 +1,71 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(3);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/validation_subset.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..4df83e69c4f9a3365955e5d17ffcfc0af71372b7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch16/validation_subset.py @@ -0,0 +1,18 @@ +"""Model-selection-only subset spanning all 97 configurations, seed 2026.""" +import sys,json,copy +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +import ts_io + +root=Path('/workspace/data/valid');out=Path('/workspace/research/valid_screen') +idx=json.loads((root/'input/index.json').read_text());new=copy.deepcopy(idx);rng=np.random.default_rng(2026) +for cfg in new['configs']: + cid=cfg['config_id'];case=ts_io.CaseFile(root/'input/cases'/f'{cid}.h5') + ids=np.sort(rng.choice(case.n,min(case.n,192),replace=False)) + ts_io.write_case_subset(case,ids,out/'input/cases'/f'{cid}.h5') + lab,se,meta=ts_io.read_truth_file(root/'truth/cases'/f'{cid}.h5') + ts_io.write_truth_file(out/'truth/cases'/f'{cid}.h5',lab[ids],se[ids],meta) + cfg['n_instances']=len(ids);case.close() +for kind in ('input','truth'):(out/kind/'index.json').write_text(json.dumps(new,indent=1)) +print('screen instances',sum(c['n_instances'] for c in new['configs'])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch8/convert.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch8/convert.py new file mode 100644 index 0000000000000000000000000000000000000000..f758dcbc0d48b531889b71dc758a7d2fb9a3afb7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch8/convert.py @@ -0,0 +1,44 @@ +"""Convert our own 16-point model to 8-point patches, without external assets.""" +import argparse +import hashlib +import json +import time +from pathlib import Path + +import torch + +ap=argparse.ArgumentParser() +ap.add_argument('--input',required=True) +ap.add_argument('--output',required=True) +a=ap.parse_args() +torch.set_num_threads(2) +started=time.monotonic() +ck=torch.load(a.input,map_location='cpu',weights_only=False) +state=ck['model']; d=ck['config']['d'] +assert ck['config']['patch']==16 +old=state['embed.0.weight'].reshape(d,2,16) +state['embed.0.weight']=(old[:,:,:8]+old[:,:,8:]).reshape(d,16) +old=state['query.0.weight'].reshape(d,16,9) +state['query.0.weight']=(old[:,:8]+old[:,8:]).reshape(d,8*9) +if 'recency.weight' in state: + old=state['recency.weight'].reshape(d,16,4) + state['recency.weight']=(old[:,:8]+old[:,8:]).reshape(d,8*4) +state['head.weight']=state['head.weight'].reshape(16,18,d)[:8].reshape(8*18,d).clone() +state['head.bias']=state['head.bias'].reshape(16,18)[:8].reshape(8*18).clone() +ck['config']['patch']=8 +ck['config']['partial_target_lengths']=True +ck['conversion']={ + 'from_checkpoint':str(Path(a.input).resolve()), + 'from_sha256':hashlib.sha256(Path(a.input).read_bytes()).hexdigest(), + 'method':'fold input/query/recency halves by summation; retain first8 output rows; preserve physical position units', + 'exact_function_preservation':False} +ck['args']={**ck['args'],'initialize_from':str(Path(a.input).resolve()),'converted':True} +ck['parent_checkpoints']=[str(Path(a.input).resolve())] +torch.save(ck,a.output) +receipt=dict(input_sha256=ck['conversion']['from_sha256'], + checkpoint_sha256=hashlib.sha256(Path(a.output).read_bytes()).hexdigest(), + parameters=sum(v.numel() for v in state.values()), + cpu_seconds=time.monotonic()-started, + optimizer_updates=0,conversion=ck['conversion']) +Path(a.output).with_suffix('.json').write_text(json.dumps(receipt,indent=2)) +print(json.dumps(receipt)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch8/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch8/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch8/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch8/memory_check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch8/memory_check.py new file mode 100644 index 0000000000000000000000000000000000000000..d55bebeab8c6ff393f89b7ad031763f49531f56b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch8/memory_check.py @@ -0,0 +1,23 @@ +"""Maximum training-shape memory fixture, serialized with validation jobs.""" +import fcntl,json,sys,time +from pathlib import Path +import torch + +r=Path('/workspace/research');sys.path.insert(0,str(r/'patch8')) +from model import DirectForecaster,loss_fn +from data import Sampler +with open(r/'.evaluation.lock','a') as lock: + fcntl.flock(lock,fcntl.LOCK_EX) + torch.set_num_threads(1);torch.manual_seed(277);torch.backends.cuda.matmul.allow_tf32=True + started=time.monotonic() + ck=torch.load(r/'patch8_initial.pt',map_location='cpu',weights_only=False) + m=DirectForecaster(**ck['config']).cuda();m.load_state_dict(ck['model']) + x,y,p=[torch.from_numpy(a).cuda() for a in Sampler(r/'packed_sample',277).sample(64,4096,1024)] + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(m,x,y,p,paired=True) + loss.backward();torch.cuda.synchronize() + assert all(v.grad is not None and torch.isfinite(v.grad).all() for v in m.parameters()) + result={'seed':277,'batch':64,'signed_rows':128,'context':4096,'horizon':1024, + 'optimizer_updates':0,'loss':float(loss.detach()),'seconds':time.monotonic()-started, + 'peak_allocated_mib':torch.cuda.max_memory_allocated()/2**20, + 'peak_reserved_mib':torch.cuda.max_memory_reserved()/2**20} + (r/'patch8_memory_check.json').write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch8/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch8/model.py new file mode 100644 index 0000000000000000000000000000000000000000..dedcdff4698028a8ba655865f8425d0dc3ef0dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/patch8/model.py @@ -0,0 +1,204 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/recency_features/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/recency_features/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/recency_features/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/recency_features/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/recency_features/model.py new file mode 100644 index 0000000000000000000000000000000000000000..f8271c5b0bf9a5edb961e1c7839761fe50a2e40b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/recency_features/model.py @@ -0,0 +1,171 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024,recency_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + if self.recency is not None: + pos=torch.arange(c,device=z.device)[None,:];extras=[] + for j in range(2): + period=periods[:,j:j+1] + recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/recency_features/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/recency_features/train.py new file mode 100644 index 0000000000000000000000000000000000000000..3bfb8b90f1a6656881b7598f864becaa737a76f4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/recency_features/train.py @@ -0,0 +1,73 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(3);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/recovery/capacity_curves.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/recovery/capacity_curves.py new file mode 100644 index 0000000000000000000000000000000000000000..c89a28a84243dc16ae52a1215c182a00f15dbc4e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/recovery/capacity_curves.py @@ -0,0 +1,50 @@ +"""Summarize completed validation checkpoints and measured shared-GPU training time.""" +import csv +import json +import time +from pathlib import Path + +R = Path('/workspace/research') +started = time.monotonic() +names = ['random_capacity_512', 'random_capacity_1024', 'random_capacity_1024_halflr', + 'random_capacity_full', 'distill_ensemble', 'random_capacity_512_anneal'] +rows = [] +for name in names: + log = R/(name+'_train.log') + records = {} + if log.exists(): + for line in log.read_text().splitlines(): + try: + item = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(item,dict) and 'step' in item and 'seconds' in item: + records[item['step']] = item + config_path = R/'runs'/name/'config.json' + config = json.loads(config_path.read_text()) if config_path.exists() else {} + for report in sorted((R/'evals').glob(name+'_ema*/report.json')): + result = json.loads(report.read_text()) + step = int(report.parent.name.rsplit('ema',1)[1]) + if result['n_failed']: + continue + record = records.get(step,{}) + rows.append(dict(run=name,step=step,parameters=config.get('parameters'), + seed=config.get('seed'),batch=config.get('batch'),learning_rate=config.get('lr'), + packed=config.get('packed'),skill=result['skill_score'], + rel_mase=result['rel_mase_gmean'],rel_wql=result['rel_wql_gmean'], + checkpoint_sha256=result['checkpoint_sha256'], + training_phase_loop_seconds=record.get('seconds'), + evaluation_seconds=result.get('eval_seconds'),report=str(report))) +rows.sort(key=lambda item:(names.index(item['run']),item['step'])) +output = dict(generated_utc=time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()), + note='Validation selection only. Time is logged process wall on the shared single H100, not isolated GPU time. The cooldown arm starts from the same saved24000state; its phase clock resets. No missing log time is inferred.', + rows=rows,analysis_seconds=time.monotonic()-started,no_training_or_new_inference=True) +(R/'capacity_learning_curves.json').write_text(json.dumps(output,indent=2)) +with (R/'capacity_learning_curves.csv').open('w',newline='') as handle: + writer = csv.DictWriter(handle,fieldnames=list(rows[0]) if rows else ['run']) + writer.writeheader() + writer.writerows(rows) +for name in names: + selected = [r for r in rows if r['run']==name] + if selected: + print(json.dumps(selected[-1])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/recovery/exposure_audit.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/recovery/exposure_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..fb67738bc9ed77f87173feda2430365e66c75966 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/recovery/exposure_audit.py @@ -0,0 +1,46 @@ +"""Describe sampled observation exposure and training invested in selected ancestry.""" +import json +import sys +import time +from pathlib import Path +import numpy as np + +R=Path('/workspace/research') +sys.path.insert(0,str(R/'random_capacity')) +from data import Sampler + +started=time.monotonic() +seed=521 +sampler=Sampler(R/'packed_sample',seed=seed,source_weights_from=R/'packed_sample') +rng=np.random.default_rng(seed) +rows=context_points=target_points=0 +for _ in range(320): + 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])) + x,y,p=sampler.sample(64,c,h) + rows+=len(x) + context_points+=int(np.isfinite(x).sum()) + target_points+=int(np.isfinite(y).sum()) +manifest=json.loads(Path('/workspace/submission/model_manifest.json').read_text()) +runs={} +for item in manifest['training_lineage']: + path=Path(item['checkpoint']) + batch=item.get('training_settings',{}).get('batch') + if path.parts[0]!='runs' or not batch: + continue + run=path.parts[1] + step=item.get('step',0) + if step>runs.get(run,{}).get('step',0): + runs[run]=dict(step=step,batch=batch,rows=step*batch,checkpoint=item['checkpoint']) +ancestral_rows=sum(v['rows'] for v in runs.values()) +mean_points=(context_points+target_points)/rows +result=dict(seed=seed,seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False, + sampled_rows=rows,mean_finite_context_points=context_points/rows, + mean_finite_target_points=target_points/rows,mean_finite_points=mean_points, + selected_descriptor=manifest['checkpoint_sha256'],ancestral_runs=runs, + selected_ancestral_rows_before_sign_pairing=ancestral_rows, + fresh96000_batch48_rows=96000*48, + fresh96000_batch48_gross_observation_presentations_estimate=96000*48*mean_points, + note='Gross sampled presentations include overlapping/resampled windows and synthetic values, not unique observations. Ancestral run maxima count compute invested in different branches, including subtracted controls; they are not an equivalent single-model training trajectory. Sign pairing duplicates compute but not distinct sampled rows. No future training recipe is inferred from this audit alone.') +(R/'training_exposure_audit.json').write_text(json.dumps(result,indent=2)) +print(json.dumps({k:v for k,v in result.items() if k!='ancestral_runs'})) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/recovery/relaunch_20261022b.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/recovery/relaunch_20261022b.py new file mode 100644 index 0000000000000000000000000000000000000000..d16fc19cbbb86dba2ff53b445e368b8bbd2ca218 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/recovery/relaunch_20261022b.py @@ -0,0 +1,105 @@ +"""Resume interrupted research jobs and preserve phase-specific recovery receipts.""" +import datetime +import json +import os +from pathlib import Path +import shutil +import subprocess +import time + +R = Path('/workspace/research') +TAG = 'recovery2' +env = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1') +receipt = {'recovery_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(), + 'remaining_research_seconds_at_operator_recovery': 152594, + 'jobs': {}, 'queues': {}} +children = {} + +def launch(name, command, phase=TAG): + log = R / f'{name}_{phase}.log' + assert not log.exists(), log + with log.open('w') as f: + child = subprocess.Popen(command, stdout=f, stderr=subprocess.STDOUT, env=env) + children[name] = child + return {'pid': child.pid, 'command': command, 'log': str(log), 'started_monotonic': time.monotonic()} + +def persist(): + path = R / f'{TAG}_launch_receipt.json' + tmp = path.with_suffix('.tmp') + tmp.write_text(json.dumps(receipt, indent=2)); os.replace(tmp, path) + +for name in ['wide_capacity_146m_recovery', 'wide_capacity_control_recovery', + 'long_memory_synth_recovery', 'recent_normalization_recovery', 'wide_graft', 'patch8']: + run = R / 'runs' / name + cfg = json.loads((run / 'config.json').read_text()) + shutil.copy2(run / 'config.json', run / f'config_before_{TAG}.json') + command = ['python3', str(R / 'recovery/train.py')] + for key in ['code_dir', 'packed', 'source_weights_from', 'out', 'initialize_from', + 'initialize_ema', 'start_step', 'steps', 'batch', 'lr', 'seed', 'context', + 'sample_context', 'save_every', 'stop_file', 'reset_at', 'reset_seed', 'loss_mode']: + if cfg.get(key) is not None: + command += ['--' + key.replace('_', '-'), str(cfg[key])] + if (run / 'recovery.pt').exists(): + command += ['--resume', str(run / 'recovery.pt')] + mode = 'complete optimizer/EMA/RNG/prefetched-batch resume' + else: + mode = 'restart saved own initialization; no complete checkpoint existed' + if cfg.get('compile_loss'): + command += ['--compile-loss'] + command = ['env', 'TORCHINDUCTOR_COMPILE_THREADS=2', 'MAX_JOBS=2', + 'PYTHONPATH=/workspace/research/compiler_support', + 'TRITON_CACHE_MANAGER=sibling_cache:SiblingFileCacheManager', + 'TRITON_CACHE_DIR=/tmp/timeseries-triton-cache', + 'TORCHINDUCTOR_CACHE_DIR=/tmp/timeseries-inductor-cache'] + command + assert not Path(cfg['stop_file']).exists(), cfg['stop_file'] + receipt['jobs'][name] = dict(launch(name, command), mode=mode) + persist() + +watch_specs = { + 'wide_capacity_146m_recovery': ('wide_capacity_inference', '24000,32000'), + 'wide_capacity_control_recovery': ('wide_capacity_inference', '24000,32000'), + 'long_memory_synth_recovery': ('partial_targets_inference', '12000'), + 'recent_normalization_recovery': ('recent_normalization_inference', '12000'), + 'wide_graft': ('wide_graft_inference', '4000,8000,12000,16000,24000,32000'), + 'patch8': ('full_paired_inference', '1000,3000,6000,12000'), + 'volatility_synth': ('partial_targets_inference', '3000,6000,12000'), + 'postloss': ('full_paired_inference', '1000,3000,6000,12000'), + 'paired_long_memory': ('full_paired_inference', '1000,3000,6000,12000'), +} +for name, (runtime, steps) in watch_specs.items(): + command = ['python3', str(R / 'watch_evaluate.py'), '--run', str(R / 'runs' / name), + '--evaluator', str(R / runtime / 'evaluate.py'), '--name', name, '--steps', steps] + launch(name + '_watch', command) + +queue_specs = {'volatility_synth': 'long_memory_synth_recovery', + 'postloss': 'recent_normalization_recovery', + 'paired_long_memory': 'wide_capacity_control_recovery'} +for name, dependency in queue_specs.items(): + old = json.loads((R / (name + '_queue.json')).read_text()) + shutil.copy2(R / (name + '_queue.json'), R / (name + '_queue_before_' + TAG + '.json')) + receipt['queues'][name] = dict(old, dependency=dependency, status='waiting', + wait_pids=[children[dependency].pid]) +persist() + +while True: + for name, job in receipt['jobs'].items(): + if 'returncode' not in job and children[name].poll() is not None: + job.update(returncode=children[name].returncode, + phase_seconds=time.monotonic() - job['started_monotonic']) + persist() + for name, queue in receipt['queues'].items(): + if queue['status'] == 'waiting' and children[queue['dependency']].poll() is not None: + if children[queue['dependency']].returncode != 0 or not all(Path(p).exists() for p in queue['required_checkpoints']): + queue['status'] = 'blocked_by_incomplete_dependency' + else: + receipt['jobs'][name] = launch(name, queue['command']) + queue.update(status='running', pid=children[name].pid, + started_utc=datetime.datetime.now(datetime.timezone.utc).isoformat()) + with (R / 'direct_v1/EXPERIMENTS.md').open('a') as f: + f.write(f'\n{name} started {queue["started_utc"]} after {queue["dependency"]} completed. Original predeclared settings and seed retained.\n') + (R / (name + '_queue.json')).write_text(json.dumps(queue, indent=2)) + persist() + if all(p.poll() is not None for n,p in children.items() if not n.endswith('_watch')) and all(q['status'] != 'waiting' for q in receipt['queues'].values()): + break + time.sleep(5) +persist() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/recovery/relaunch_20261023.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/recovery/relaunch_20261023.py new file mode 100644 index 0000000000000000000000000000000000000000..5f35a9cfcbe7ea66c8837b6d4ada8b84be36b934 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/recovery/relaunch_20261023.py @@ -0,0 +1,104 @@ +"""Resume interrupted research jobs and preserve phase-specific recovery receipts.""" +import datetime +import json +import os +from pathlib import Path +import shutil +import subprocess +import time + +R = Path('/workspace/research') +TAG = 'recovery3' +env = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1') +receipt = {'recovery_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(), + 'remaining_research_seconds_at_operator_recovery': 151596, + 'jobs': {}, 'queues': {}} +children = {} + +def launch(name, command, phase=TAG): + log = R / f'{name}_{phase}.log' + assert not log.exists(), log + with log.open('w') as f: + child = subprocess.Popen(command, stdout=f, stderr=subprocess.STDOUT, env=env) + children[name] = child + return {'pid': child.pid, 'command': command, 'log': str(log), 'started_monotonic': time.monotonic()} + +def persist(): + path = R / f'{TAG}_launch_receipt.json' + tmp = path.with_suffix('.tmp') + tmp.write_text(json.dumps(receipt, indent=2)); os.replace(tmp, path) + +for name in ['wide_capacity_146m_recovery', 'wide_capacity_control_recovery', + 'long_memory_synth_recovery', 'wide_graft', 'patch8']: + run = R / 'runs' / name + cfg = json.loads((run / 'config.json').read_text()) + shutil.copy2(run / 'config.json', run / f'config_before_{TAG}.json') + command = ['python3', str(R / 'recovery/train.py')] + for key in ['code_dir', 'packed', 'source_weights_from', 'out', 'initialize_from', + 'initialize_ema', 'start_step', 'steps', 'batch', 'lr', 'seed', 'context', + 'sample_context', 'save_every', 'stop_file', 'reset_at', 'reset_seed', 'loss_mode']: + if cfg.get(key) is not None: + command += ['--' + key.replace('_', '-'), str(cfg[key])] + if (run / 'recovery.pt').exists(): + command += ['--resume', str(run / 'recovery.pt')] + mode = 'complete optimizer/EMA/RNG/prefetched-batch resume' + else: + mode = 'restart saved own initialization; no complete checkpoint existed' + if cfg.get('compile_loss'): + command += ['--compile-loss'] + command = ['env', 'TORCHINDUCTOR_COMPILE_THREADS=2', 'MAX_JOBS=2', + 'PYTHONPATH=/workspace/research/compiler_support', + 'TRITON_CACHE_MANAGER=sibling_cache:SiblingFileCacheManager', + 'TRITON_CACHE_DIR=/tmp/timeseries-triton-cache', + 'TORCHINDUCTOR_CACHE_DIR=/tmp/timeseries-inductor-cache'] + command + assert not Path(cfg['stop_file']).exists(), cfg['stop_file'] + receipt['jobs'][name] = dict(launch(name, command), mode=mode) + persist() + +watch_specs = { + 'wide_capacity_146m_recovery': ('wide_capacity_inference', '24000,32000'), + 'wide_capacity_control_recovery': ('wide_capacity_inference', '24000,32000'), + 'long_memory_synth_recovery': ('partial_targets_inference', '12000'), + 'recent_normalization_recovery': ('recent_normalization_inference', '12000'), + 'wide_graft': ('wide_graft_inference', '4000,8000,12000,16000,24000,32000'), + 'patch8': ('full_paired_inference', '1000,3000,6000,12000'), + 'volatility_synth': ('partial_targets_inference', '3000,6000,12000'), + 'postloss': ('full_paired_inference', '1000,3000,6000,12000'), + 'paired_long_memory': ('full_paired_inference', '1000,3000,6000,12000'), +} +for name, (runtime, steps) in watch_specs.items(): + command = ['python3', str(R / 'watch_evaluate.py'), '--run', str(R / 'runs' / name), + '--evaluator', str(R / runtime / 'evaluate.py'), '--name', name, '--steps', steps] + launch(name + '_watch', command) + +queue_specs = {'volatility_synth': 'long_memory_synth_recovery', + 'paired_long_memory': 'wide_capacity_control_recovery'} +for name, dependency in queue_specs.items(): + old = json.loads((R / (name + '_queue.json')).read_text()) + shutil.copy2(R / (name + '_queue.json'), R / (name + '_queue_before_' + TAG + '.json')) + receipt['queues'][name] = dict(old, dependency=dependency, status='waiting', + wait_pids=[children[dependency].pid]) +persist() + +while True: + for name, job in receipt['jobs'].items(): + if 'returncode' not in job and children[name].poll() is not None: + job.update(returncode=children[name].returncode, + phase_seconds=time.monotonic() - job['started_monotonic']) + persist() + for name, queue in receipt['queues'].items(): + if queue['status'] == 'waiting' and children[queue['dependency']].poll() is not None: + if children[queue['dependency']].returncode != 0 or not all(Path(p).exists() for p in queue['required_checkpoints']): + queue['status'] = 'blocked_by_incomplete_dependency' + else: + receipt['jobs'][name] = launch(name, queue['command']) + queue.update(status='running', pid=children[name].pid, + started_utc=datetime.datetime.now(datetime.timezone.utc).isoformat()) + with (R / 'direct_v1/EXPERIMENTS.md').open('a') as f: + f.write(f'\n{name} started {queue["started_utc"]} after {queue["dependency"]} completed. Original predeclared settings and seed retained.\n') + (R / (name + '_queue.json')).write_text(json.dumps(queue, indent=2)) + persist() + if all(p.poll() is not None for n,p in children.items() if not n.endswith('_watch')) and all(q['status'] != 'waiting' for q in receipt['queues'].values()): + break + time.sleep(5) +persist() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/recovery/schedules.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/recovery/schedules.py new file mode 100644 index 0000000000000000000000000000000000000000..4c8378f374144b802d2cd5a98afd71efc1ba0a4c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/recovery/schedules.py @@ -0,0 +1,13 @@ +"""Explicit training-only learning-rate schedules; default arithmetic unchanged.""" +import math + + +def learning_rate(step, steps, peak, reset_at=-1, anneal_from_step=None, + anneal_from_lr=None, anneal_final_lr=None): + if anneal_from_step is not None: + assert steps > anneal_from_step + assert 0 < anneal_final_lr <= anneal_from_lr + progress=max(0.,min(1.,(step-anneal_from_step)/(steps-anneal_from_step))) + return anneal_final_lr+.5*(anneal_from_lr-anneal_final_lr)*(1+math.cos(math.pi*progress)) + warm_step=step-reset_at if reset_at>=0 and step>reset_at else step + return peak*min(1,warm_step/400)*(.2+.4*(1+math.cos(math.pi*step/steps))) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/recovery/snapshot.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/recovery/snapshot.py new file mode 100644 index 0000000000000000000000000000000000000000..11ce27e43477f9c685cefeaa5f36e53c59634505 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/recovery/snapshot.py @@ -0,0 +1,99 @@ +"""Write a compact authoritative research recovery index without touching training state.""" +import datetime +import json +import os +from pathlib import Path + +R=Path('/workspace/research');p=R/'CURRENT_RESEARCH_STATE.json' +s=json.loads(p.read_text()) +s['snapshot_utc']=datetime.datetime.now(datetime.timezone.utc).isoformat() +receipt=json.loads((R/'recovery3_launch_receipt.json').read_text()) +s['runs']={} +for name,job in receipt['jobs'].items(): + run=R/'runs'/name + log=Path(job['log']) + records=[] + for line in log.read_text().splitlines(): + try: + record=json.loads(line) + if 'step' in record or 'completed_step' in record:records.append(record) + except json.JSONDecodeError:pass + s['runs'][name]={'config':json.loads((run/'config.json').read_text()) if (run/'config.json').exists() else None, + 'last_phase_record':records[-1] if records else None, + 'phase_log':str(log),'supervisor_receipt':str(R/'recovery3_launch_receipt.json'), + 'latest_saved_ema':str(max(run.glob('ema*.pt'))) if list(run.glob('ema*.pt')) else None, + 'complete_recovery_checkpoint':str(run/'recovery.pt') if (run/'recovery.pt').exists() else None, + 'pid_at_snapshot':job['pid'],'returncode':job.get('returncode'), + 'note':'Check actual live process and checkpoint state before resuming; this is only a snapshot.'} +s['queues']={name:{'status':q['status'],'dependency':q['dependency'],'command':q['command'], + 'required_checkpoints':q['required_checkpoints']} + for name,q in receipt['queues'].items()} +s.pop('prepared_not_launched',None) +s['deferred_unqueued']={'E72':'temporal_mixup, prepared and checked but not queued','ideas':'RESEARCH_IDEAS.md, no jobs attached'} +s['completed_since_previous_recovery']={ + 'E67_control12000':{'skill':.37724286394256845,'training_loop_seconds':2794.8358458959847}, + 'E67_paired12000':{'skill':.377427077277383,'training_loop_seconds':2794.867385860998}, + 'E63_expanded146M':'Stopped8501, complete recovery retained; allocation moved to E73; inconclusive data scaling', + 'E61_slowAR':'Complete12000; E76 used6000 correction, final transfer rejected', + 'E65_recent_normalization':'Complete12000; E81 equal ensemble rejected', + 'E58_small_control':'Complete32000', + 'E58_wide146M':'Complete32000; no gain over37Mcontrol; do not resume', + 'E71_patch8':'Complete12000; selected6000 used in E87/E96/E102 ensembles', + 'E69_volatility':'Complete12000; final below matched control; no transfer', + 'E89_patch8_control':'Complete12000; final0.380847096,loop2729.052105s; selected starting E71parent remains stronger', + 'E89_fullpatch4':'Complete12000,main0.381640078; E96 used6000, E103final cached alternative mixed; loop5066.016522s', + 'E93_split_patch':'Complete12000,main0.381711986; selected final is E102 published thirdmember; loop3153.565149s', + 'E92_robust_normalization':'Complete12000,final0.377099312 belowcontrol; rejected;E97started', + 'E90_metric_scale':'Complete12000; final0.377373344 ties/slightly trailsE80; no selection; loop2702.166704s', + 'E84_coarse':'Complete12000; daily gain but weekly regression; not selected', + 'E88_late_patch8_slowAR':'Complete12000; small9k gain lost atfinal; rejected', + 'E80_overflow':'Complete12000; finaltiesoriginal; selected3k compositeE91rejected', + 'E78_multiscaleAR':'Complete12000; no gain over single slowAR', + 'E86_protected_graft':'Complete8000; below own initialization; no publication', + 'E75_postloss':'Stopped3653 deliberately; immutable snapshot retained; E98 separately declared completion active in another output, original stopfile remains', + 'E73_independent_graft':'Stopped8683 after negative8000; replaced by E86; stopfile remains', + 'E95_stratified_corpus':'Complete12000,final0.377983250,earliermixed; E105collision destroyed only1000weights and optimizer recovery;2k..12k preserved; do not resume', + 'E97_weekly_synth':'Complete12000,final0.380439539; E112final weekly correction now published; loop2600.472750s', + 'E105_stratified_volume':'Complete12000,final0.377529200,earlier0.336713522/0.359535697/0.390349158 mixed; corrected continuationloop2013.982814s plus original incident phase', + 'E106_spectral_synth':'Complete12000,final0.377641399,earlier0.337647555/0.361626447/0.385497870, average matched gap negligible; loop2206.272278s; E114fixed6000transfers in selection', + 'E98_postloss_completion':'Complete12000,final0.376034254 below3000 andcontrol; rejected,loop1995.386513s', + 'E99_early_cooldown':'Complete36000,final0.363306598 trails original36k0.364859034; rejected,loop1603.635706s', + 'E77_pairedslowAR':'Complete12000;6000 strongest main/earlier comparison'} +s['external_receipts']=[str(R/'postloss_recovery3_receipt.json'),str(R/'random_capacity_512_queue.json'),str(R/'random_capacity_1024_queue.json'),str(R/'multiscale_ar_queue.json'),str(R/'overflow_control_queue.json'),str(R/'coarse_aggregate_queue.json'),str(R/'patch8_long_memory_queue.json'),str(R/'wide_graft_frozen_queue.json'),str(R/'patch4_candidate_queue.json'),str(R/'patch4_control_queue.json'),str(R/'metric_scale_queue.json'),str(R/'robust_normalization_queue.json'),str(R/'split_patch_queue.json'),str(R/'random_capacity_1024_halflr_queue.json'),str(R/'stratified_corpus_queue.json'),str(R/'weekly_synth_queue.json'),str(R/'postloss_completion_queue.json'),str(R/'random_capacity_512_anneal_queue.json'),str(R/'distill_ensemble_queue.json'),str(R/'stratified_volume_queue.json'),str(R/'spectral_synth_queue.json'),str(R/'long_seasonal_queue.json'),str(R/'random_capacity_full_queue.json'),str(R/'weekly_replication_control_queue.json'),str(R/'weekly_replication_candidate_queue.json'),str(R/'lowfreq_windows_queue.json'),str(R/'phase_joint_queue.json')] +queue_pids={'random_capacity_512_queue.json':965,'random_capacity_1024_queue.json':967, + 'multiscale_ar_queue.json':1678,'overflow_control_queue.json':1676, + 'coarse_aggregate_queue.json':3086,'patch8_long_memory_queue.json':3739, + 'wide_graft_frozen_queue.json':3931,'patch4_candidate_queue.json':4078, + 'patch4_control_queue.json':4080} +s['external_jobs']={} +for receipt_name in s['external_receipts']: + receipt_path=Path(receipt_name) + if not receipt_path.exists():continue + item=json.loads(receipt_path.read_text());command=item.get('command',[]) + if '--out' not in command:continue + run=Path(command[command.index('--out')+1]);log=Path(item.get('log',str(receipt_path).replace('_queue.json','_train.log'))) + last=None + if log.exists(): + for line in log.read_text().splitlines(): + try: + record=json.loads(line) + if isinstance(record,dict) and ('step' in record or 'completed_step' in record):last=record + except json.JSONDecodeError:pass + queue_pid=item.get('launcher_pid',queue_pids.get(receipt_path.name)) + children_file=Path(f'/proc/{queue_pid}/task/{queue_pid}/children') if queue_pid else None + children=list(map(int,children_file.read_text().split())) if children_file and children_file.exists() else [] + checkpoints=list(run.glob('ema*.pt')) + s['external_jobs'][run.name]={'receipt':str(receipt_path),'status':item.get('status'), + 'queue_pid_at_snapshot':queue_pid,'child_pids_at_snapshot':children, + 'last_phase_record':last,'log':str(log), + 'latest_saved_ema':str(max(checkpoints)) if checkpoints else None, + 'complete_recovery_checkpoint':str(run/'recovery.pt') if (run/'recovery.pt').exists() else None, + 'command':command,'note':'PIDs are only a snapshot; check actual processes and serialized state before recovery.'} +s['compiler_environment']={'OPENBLAS_NUM_THREADS':'1','OMP_NUM_THREADS':'1','TORCHINDUCTOR_COMPILE_THREADS':'2','MAX_JOBS':'2','PYTHONPATH':str(R/'compiler_support'),'TRITON_CACHE_MANAGER':'sibling_cache:SiblingFileCacheManager','TRITON_CACHE_DIR':'/tmp/timeseries-triton-cache','TORCHINDUCTOR_CACHE_DIR':'/tmp/timeseries-inductor-cache'} +for job in s['external_jobs'].values(): + job['environment']=s['compiler_environment'] if '--compile-loss' in job['command'] else {'OPENBLAS_NUM_THREADS':'1','OMP_NUM_THREADS':'1'} +s['compiler_cache_backup']=str(R/'compiler_cache_backup') +for stale in ['pending','pending_actions','active_experiments','next_experiments','prepared_experiments']: + s.pop(stale,None) +tmp=p.with_suffix('.tmp');tmp.write_text(json.dumps(s,indent=2));os.replace(tmp,p) +print(s['snapshot_utc']) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/recovery/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/recovery/train.py new file mode 100644 index 0000000000000000000000000000000000000000..536677ab542342e8e9b56298e5ddb7cb2983a258 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/recovery/train.py @@ -0,0 +1,201 @@ +"""Resumable continuation of our existing permitted-corpus experiments.""" +import argparse,copy,fcntl,inspect,json,math,os,sys,time +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import numpy as np +import torch + +ap=argparse.ArgumentParser() +ap.add_argument('--code-dir',required=True);ap.add_argument('--packed',required=True) +ap.add_argument('--source-weights-from');ap.add_argument('--out',required=True) +ap.add_argument('--initialize-from',required=True);ap.add_argument('--initialize-ema') +ap.add_argument('--start-step',type=int,default=0);ap.add_argument('--resume') +ap.add_argument('--steps',type=int,required=True);ap.add_argument('--batch',type=int,required=True) +ap.add_argument('--lr',type=float,required=True);ap.add_argument('--seed',type=int,required=True) +ap.add_argument('--context',type=int);ap.add_argument('--sample-context',type=int,default=4096) +ap.add_argument('--save-every',type=int,default=1000);ap.add_argument('--stop-file') +ap.add_argument('--recovery-every',type=int,default=250) +ap.add_argument('--halt-after',type=int) +ap.add_argument('--loss-mode',choices=['individual','paired']) +ap.add_argument('--compile-loss',action='store_true') +ap.add_argument('--reset-at',type=int,default=-1);ap.add_argument('--reset-seed',type=int,default=179) +ap.add_argument('--anneal-from-step',type=int);ap.add_argument('--anneal-from-lr',type=float) +ap.add_argument('--anneal-final-lr',type=float) +ap.add_argument('--teacher-package');ap.add_argument('--teacher-coefficient',type=float) +a=ap.parse_args() +# Hold a process-lifetime lock before loading a model or touching GPU state. +_run_out=Path(a.out);_run_out.mkdir(parents=True,exist_ok=True) +_run_lock=open(_run_out/'.training.lock','a') +try:fcntl.flock(_run_lock,fcntl.LOCK_EX|fcntl.LOCK_NB) +except BlockingIOError:raise SystemExit('Another trainer already owns this output directory: '+str(_run_out)) +if not a.resume: + _saved=list(_run_out.glob('ema*.pt'))+list(_run_out.glob('step*.pt')) + if (_run_out/'recovery.pt').exists():_saved.append(_run_out/'recovery.pt') + if _saved: + raise SystemExit('Refusing fresh training into an output with saved checkpoints; use a new directory or explicit --resume: '+str(_run_out)) +sys.path.insert(0,a.code_dir) +from model import DirectForecaster,loss_fn +from data import Sampler +from schedules import learning_rate +torch.set_num_threads(2);torch.manual_seed(a.seed);torch.backends.cuda.matmul.allow_tf32=True +out=Path(a.out);out.mkdir(parents=True,exist_ok=True);a.trainable_scope='all' +if Path(a.code_dir).name in ('long_memory_synth','paired_long_memory','multiscale_ar','random_capacity','patch8_long_memory','distill_ensemble'):a.synthetic_ar_time_constants=[1,10000] +if Path(a.code_dir).name in ('full_paired','patch8','temporal_mixup','postloss','paired_long_memory','multiscale_ar','random_capacity','overflow_control','coarse_aggregate','patch8_long_memory','patch4','metric_scale','robust_normalization','split_patch','weekly_synth','distill_ensemble'):a.requested_horizon_seed=a.seed+300003 +if Path(a.code_dir).name=='multiscale_ar': + a.synthetic_ar_components=4;a.multiscale_ar_seed=a.seed+700003 +if Path(a.code_dir).name=='volatility_synth':a.stochastic_volatility_seed=a.seed+500003 +if Path(a.code_dir).name=='coarse_aggregate': + a.coarse_aggregation_seed=a.seed+900003;a.coarse_aggregation_probability=.2;a.coarse_aggregation_frequencies=['D','W'] +if Path(a.code_dir).name=='temporal_mixup':a.temporal_mixup_seed=a.seed+600003 +if Path(a.code_dir).name=='postloss': + a.fixed_postprocessing_loss=True;a.normalization_overflow_fallback=True +if Path(a.code_dir).name in ('overflow_control','metric_scale','random_capacity','weekly_synth','distill_ensemble'):a.normalization_overflow_fallback=True +if Path(a.code_dir).name=='weekly_synth': + a.weekly_synthetic_seed=a.seed+1000003;a.weekly_replacement_probability=1/11 +if Path(a.code_dir).name=='spectral_synth': + a.spectral_synthetic_seed=a.seed+1100003;a.spectral_replacement_probability=.5 + a.spectral_length_scale=[1,10000];a.spectral_families=['Matern0.5','Matern1.5','Matern2.5','RBF'] + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True +if Path(a.code_dir).name in ('long_seasonal','phase_joint'): + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True +if Path(a.code_dir).name=='lowfreq_windows': + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True + a.lowfreq_window_seed=a.seed+1200003;a.lowfreq_window_probability=.5 + a.lowfreq_window_rule='period2=1,period1<=52;finite-target endpoint;log-uniform horizon4..min(H,max(8,2p),span-8) with available-length fallback;context cap min(C,max(64,32p));at least4finite history' +if Path(a.code_dir).name=='metric_scale':a.loss_seasonality='lag1 for exact daily[7,365] and weekly[52,1] period pairs; unchanged otherwise' +if Path(a.code_dir).name=='robust_normalization':a.normalization_kind='finite median plus/minus6 mean absolute deviations winsorized mean/RMS, float64; original normalized history clipped30' +if Path(a.code_dir).name=='wide_graft_frozen':a.trainable_scope='new feature stream and cross-stream blocks; inherited parameter blocks frozen' +ck=torch.load(a.resume or a.initialize_from,map_location='cpu',weights_only=False) +# Keep immutable branch ancestry across a later restart from this run's own recovery. +lineage_parents=list(ck.get('parent_checkpoints',[])) +if a.initialize_ema:lineage_parents.append(a.initialize_ema) +if a.resume and Path(a.resume).parent.resolve()!=out.resolve():lineage_parents.append(a.resume) +previous_args=ck.get('args',{}) +previous_resume=previous_args.get('resume') +if previous_resume and Path(previous_resume).parent.resolve()!=Path(previous_args.get('out',a.out)).resolve(): + lineage_parents.append(previous_resume) +lineage_parents=list(dict.fromkeys(lineage_parents)) +config=dict(ck['config']) +if a.context:config['max_context']=a.context +model=DirectForecaster(**config).cuda();model.load_state_dict(ck['model']) +teacher=None +if Path(a.code_dir).name=='distill_ensemble': + assert a.teacher_package and a.teacher_coefficient is not None +if a.teacher_package: + assert Path(a.code_dir).name=='distill_ensemble' + from teacher import OwnEnsembleTeacher + with torch.random.fork_rng(devices=[torch.cuda.current_device()]): + teacher=OwnEnsembleTeacher(a.teacher_package) + if ck.get('args',{}).get('teacher_descriptor_sha256'): + assert ck['args']['teacher_descriptor_sha256']==teacher.descriptor_sha256 + assert ck['args']['teacher_coefficient']==a.teacher_coefficient + a.teacher_descriptor_sha256=teacher.descriptor_sha256 + a.teacher_checkpoint_sha256=teacher.member_hashes + a.teacher_target_kind='equal average of own frozen E96 raw normalized sign-paired neural quantiles, before postprocessing' + +protector=None +if Path(a.code_dir).name=='wide_graft_frozen': + from frozen import FreezeInherited + protector=FreezeInherited(model) + a.protected_parameters=protector.inherited_numel +if a.compile_loss: + torch._dynamo.config.recompile_limit=64 + objective=torch.compile(loss_fn,fullgraph=True,dynamic=False) +else:objective=loss_fn +multipliers=ck.get('lr_multipliers',{}) +def optimizer(): + groups=[] + for mult in sorted(set(multipliers.values())|{1.}): + params=[p for n,p in model.named_parameters() if multipliers.get(n,1.)==mult] + if params:groups.append({'params':params,'lr':a.lr*mult,'lr_multiplier':mult,'weight_decay':.05/mult}) + return torch.optim.AdamW(groups,betas=(.9,.95),fused=True) +opt=optimizer() +if a.resume: + start_step=ck['step'];opt.load_state_dict(ck['optimizer']) + ema={k:v.cuda() for k,v in ck['ema_state'].items()} +else: + start_step=a.start_step + ema_ck=torch.load(a.initialize_ema,map_location='cpu',weights_only=False) if a.initialize_ema else ck + ema={k:v.cuda().clone() for k,v in ema_ck['model'].items()} +del ck +def make_sampler(seed): + kwargs={'seed':seed} + if 'source_weights_from' in inspect.signature(Sampler).parameters:kwargs['source_weights_from']=a.source_weights_from + return Sampler(a.packed,**kwargs),np.random.default_rng(seed) +stream_seed=a.reset_seed if a.reset_at>=0 and start_step>=a.reset_at else a.seed +sampler,rng=make_sampler(stream_seed) +def next_batch(): + c=int(rng.choice([512,1024,2048,a.sample_context],p=[.1,.15,.35,.4])) + h=int(rng.choice([32,128,512,1024],p=[.1,.2,.2,.5])) + x,y,p=sampler.sample(a.batch,c,h) + return x[:,-model.max_context:].copy(),y,p +pool=ThreadPoolExecutor(1) +if a.resume: + recovery=torch.load(a.resume,map_location='cpu',weights_only=False) + rng.bit_generator.state=recovery['batch_rng_state'];sampler.rng.bit_generator.state=recovery['sampler_rng_state'] + for name,state in recovery.get('sampler_rng_states',{}).items():getattr(sampler,name).bit_generator.state=state + torch.set_rng_state(recovery['torch_rng_state']);torch.cuda.set_rng_state_all(recovery['cuda_rng_state']) + pending=recovery['prefetched_batch'];del recovery + future=pool.submit(lambda:pending) +else:future=pool.submit(next_batch) +parameters=sum(p.numel() for p in model.parameters()) +(out/'config.json').write_text(json.dumps({**vars(a),'model':model.config,'parameters':parameters},indent=2)) +print(json.dumps({'parameters':parameters,'starting_step':start_step,'stream_seed':stream_seed,'restored_complete_training_state':bool(a.resume)}),flush=True) +started=time.monotonic();losses=[] +def atomic_save(obj,path): + torch.save(obj,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) +def save(step,include_selection_weights=True): + global future + pending_batch=future.result() + common={'config':model.config,'step':step,'args':vars(a),'lr_multipliers':multipliers, + 'parent_checkpoints':list(dict.fromkeys(lineage_parents+(teacher.checkpoints if teacher else [])))} + if include_selection_weights: + for prefix,state in [('step',model.state_dict()),('ema',ema)]: + atomic_save({**common,'model':state,'ema':prefix=='ema'},out/f'{prefix}{step:06d}.pt') + atomic_save({**common,'model':model.state_dict(),'optimizer':opt.state_dict(),'ema_state':ema, + 'prefetched_batch':pending_batch,'batch_rng_state':copy.deepcopy(rng.bit_generator.state), + 'sampler_rng_state':copy.deepcopy(sampler.rng.bit_generator.state), + 'sampler_rng_states':{name:copy.deepcopy(value.bit_generator.state) for name,value in vars(sampler).items() if isinstance(value,np.random.Generator)}, + 'torch_rng_state':torch.get_rng_state(),'cuda_rng_state':torch.cuda.get_rng_state_all()},out/'recovery.pt') + future=pool.submit(lambda:pending_batch) +for step in range(start_step+1,a.steps+1): + if a.reset_at>=0 and step==a.reset_at+1 and start_step=a.halt_after) + selection_checkpoint=step%a.save_every==0 or step==a.steps or stop + # Persist a complete state before a fresh/resumed job warms its remaining compiled shapes. + if selection_checkpoint or step%a.recovery_every==0 or step==start_step+1: + save(step,include_selection_weights=selection_checkpoint) + if stop:break +pool.shutdown() +print(json.dumps({'completed_step':step,'training_process_loop_seconds':time.monotonic()-started}),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/split_patch/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/split_patch/check.py new file mode 100644 index 0000000000000000000000000000000000000000..1f2b82a5b0b0ad5477066245356808138d166400 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/split_patch/check.py @@ -0,0 +1,49 @@ +"""Verify equal input/output patches preserve the old implementation exactly.""" +import importlib.util +import json +import sys +import time +from pathlib import Path +import torch + +R = Path('/workspace/research') +sys.path.insert(0, str(R / 'split_patch')) +from model import DirectForecaster + +started = time.monotonic() +torch.set_num_threads(2) +torch.manual_seed(457) +spec = importlib.util.spec_from_file_location('original_patch_model', R / 'full_paired_inference/model.py') +old = importlib.util.module_from_spec(spec) +spec.loader.exec_module(old) +ck = torch.load(R / 'runs/patch8/ema006000.pt', map_location='cpu', weights_only=False) +control = old.DirectForecaster(**ck['config']) +control.load_state_dict(ck['model']) +same = DirectForecaster(**ck['config'], input_patch=8) +same.load_state_dict(ck['model']) +x = torch.randn(6, 251) +x[0, :90] = float('nan') +x[1, ::7] = float('nan') +p = torch.tensor([[12, 1], [52, 1], [24, 168], [7, 365], [1, 1], [96, 672]]) +with torch.no_grad(): + before = control(x, p, 57) + after = same(x, p, 57) +assert all(torch.equal(a, b) for a, b in zip(before, after)) +candidate = torch.load(R / 'split_patch_initial.pt', map_location='cpu', weights_only=False) +full4 = torch.load(R / 'patch4_initial.pt', map_location='cpu', weights_only=False) +for name, value in candidate['model'].items(): + reference = ck['model'][name] if name == 'embed.0.weight' else full4['model'][name] + assert torch.equal(value, reference), name +net = DirectForecaster(**candidate['config']) +net.load_state_dict(candidate['model']) +with torch.no_grad(): + q = net.predict(x, p, 57) +assert q.shape == (6, 9, 57) +assert torch.isfinite(q).all() and (q[:, 1:] >= q[:, :-1]).all() +receipt = dict(seed=457, cpu_seconds=time.monotonic() - started, + equal_patch_forward_bitwise_unchanged=True, + input_tensor_retained_from_patch8=True, + output_tensors_identical_to_full_patch4_conversion=True, + candidate_finite_ordered=True, optimizer_updates=0) +(R / 'split_patch_checks.json').write_text(json.dumps(receipt, indent=2)) +print(json.dumps(receipt)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/split_patch/convert.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/split_patch/convert.py new file mode 100644 index 0000000000000000000000000000000000000000..9a16c87c0cf45b0efb1b2e56008a821c8391b471 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/split_patch/convert.py @@ -0,0 +1,13 @@ +"""Convert the already locally trained patch8 model to input8/output4 without external assets.""" +import argparse,hashlib,json,time +from pathlib import Path +import torch +ap=argparse.ArgumentParser();ap.add_argument('--input',required=True);ap.add_argument('--output',required=True);a=ap.parse_args() +torch.set_num_threads(1);started=time.monotonic();ck=torch.load(a.input,map_location='cpu',weights_only=False);state=ck['model'];d=ck['config']['d'];assert ck['config']['patch']==8 +x=state['query.0.weight'].reshape(d,8,9);state['query.0.weight']=(x[:,:4]+x[:,4:]).reshape(d,36) +x=state['recency.weight'].reshape(d,8,4);state['recency.weight']=(x[:,:4]+x[:,4:]).reshape(d,16) +state['head.weight']=state['head.weight'].reshape(8,18,d)[:4].reshape(72,d).clone();state['head.bias']=state['head.bias'].reshape(8,18)[:4].reshape(72).clone() +ck['config']['patch']=4;ck['config']['input_patch']=8 +conversion={'method':'retain input8; sum query/recency halves and keep first4 output rows; same physical position coordinates','exact_function_preservation':False,'parent_sha256':hashlib.sha256(Path(a.input).read_bytes()).hexdigest()} +ck.update(step=0,args={'packed':ck['args']['packed'],'initialize_from':str(Path(a.input).resolve()),'converted':True},parent_checkpoints=[str(Path(a.input).resolve())],conversion=conversion) +torch.save(ck,a.output);receipt={**conversion,'checkpoint_sha256':hashlib.sha256(Path(a.output).read_bytes()).hexdigest(),'parameters':sum(v.numel() for v in state.values()),'cpu_seconds':time.monotonic()-started,'optimizer_updates':0};Path(a.output).with_suffix('.json').write_text(json.dumps(receipt,indent=2));print(json.dumps(receipt)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/split_patch/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/split_patch/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/split_patch/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/split_patch/launch.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/split_patch/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..d3156fc48da2d25d324c5fb7cc2a50f7f70738d7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/split_patch/launch.py @@ -0,0 +1,33 @@ +"""Run input8/output4 after late patch8 slowAR releases its allocation.""" +def main(): + import json + import os + import subprocess + from pathlib import Path + R = Path('/workspace/research') + assert json.loads((R / 'split_patch_checks.json').read_text())['equal_patch_forward_bitwise_unchanged'] + assert json.loads((R / 'split_patch_memory_check.json').read_text())['peak_reserved_mib'] < 14000 + env = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1') + command = ['python3', str(R / 'recovery/train.py'), '--code-dir', str(R / 'split_patch'), + '--packed', str(R / 'packed_sample'), '--source-weights-from', str(R / 'packed_sample'), + '--out', str(R / 'runs/split_patch'), '--initialize-from', str(R / 'split_patch_initial.pt'), + '--steps', '12000', '--batch', '32', '--lr', '.00002', '--seed', '401', + '--loss-mode', 'paired', '--stop-file', str(R / 'split_patch.stop')] + with (R / 'split_patch_queue.log').open('w') as qlog, (R / 'split_patch_watch.log').open('w') as wlog: + queued = subprocess.Popen(['python3', str(R / 'queued_train.py'), '--label', 'E93 input8/output4 seed401', + '--log', str(R / 'split_patch_train.log'), '--receipt', str(R / 'split_patch_queue.json'), + '--wait-pid', '7349', '--require-checkpoint', str(R / 'runs/patch8_long_memory/recovery.pt'), + '--', *command], stdout=qlog, stderr=subprocess.STDOUT, env=env) + watch = subprocess.Popen(['python3', str(R / 'watch_evaluate.py'), '--run', str(R / 'runs/split_patch'), + '--evaluator', str(R / 'split_patch_inference/evaluate.py'), + '--name', 'split_patch', '--steps', '1000,3000,6000,12000'], + stdout=wlog, stderr=subprocess.STDOUT, env=env) + print({'queue_pid': queued.pid, 'watch_pid': watch.pid}, flush=True) + result = queued.wait() + if result: + watch.terminate() + watch.wait() + raise SystemExit(result) + +if __name__ == '__main__': + main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/split_patch/memory_check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/split_patch/memory_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7ae2014f738a03f54cbd2208eb9095efe16b009c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/split_patch/memory_check.py @@ -0,0 +1,18 @@ +"""Maximum-shape memory check for the matched patch comparison, including training state.""" +import argparse,fcntl,json,sys,time +from pathlib import Path +import torch +R=Path('/workspace/research');sys.path.insert(0,str(R/'split_patch')) +from model import DirectForecaster,loss_fn +from data import Sampler +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);a=ap.parse_args() +with open(R/'.evaluation.lock','a') as lock: + fcntl.flock(lock,fcntl.LOCK_EX);torch.set_num_threads(1);torch.manual_seed(401);torch.backends.cuda.matmul.allow_tf32=True + started=time.monotonic();ck=torch.load(a.weights,map_location='cpu',weights_only=False);model=DirectForecaster(**ck['config']).cuda();model.load_state_dict(ck['model']) + ema=[p.detach().clone() for p in model.parameters()];moments=[(torch.zeros_like(p),torch.zeros_like(p)) for p in model.parameters()] + x,y,p=[torch.from_numpy(v).cuda() for v in Sampler(R/'packed_sample',seed=401).sample(32,4096,1024)] + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p,paired=True) + loss.backward();torch.cuda.synchronize();assert torch.isfinite(loss) + assert all(v.grad is not None and torch.isfinite(v.grad).all() for v in model.parameters()) + result={'seed':401,'batch':32,'signed_rows':64,'patch':model.patch,'input_patch':model.input_patch,'context':4096,'horizon':1024,'EMA_and_AdamW_moment_storage_present':True,'optimizer_updates':0,'loss':float(loss.detach()),'seconds':time.monotonic()-started,'peak_allocated_mib':torch.cuda.max_memory_allocated()/2**20,'peak_reserved_mib':torch.cuda.max_memory_reserved()/2**20} + Path(a.out).write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/split_patch/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/split_patch/model.py new file mode 100644 index 0000000000000000000000000000000000000000..af1af318784c94a1d9ee75ed377582745bd30136 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/member2/training/split_patch/model.py @@ -0,0 +1,204 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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,input_patch=None): + super().__init__();self.patch=patch;self.input_patch=patch if input_patch is None else input_patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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,input_patch=self.input_patch) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(self.input_patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;ip=self.input_patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%ip,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//ip + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,ip),valid.view(b,nt,ip).float()),-1)) + pmask=valid.view(b,nt,ip).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..4d7a16347c33f78ca3d0de4a6cde649013384018 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/provenance/publish.py @@ -0,0 +1,104 @@ +"""Assemble and atomically publish a complete three-member, fixed-weight package.""" +import argparse +import ctypes +import hashlib +import json +import os +import shutil +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ap = argparse.ArgumentParser() +ap.add_argument('--member', action='append', required=True) +ap.add_argument('--out', required=True) +ap.add_argument('--report') +ap.add_argument('--experiments', default='/workspace/research/direct_v1/EXPERIMENTS.md') +a = ap.parse_args() +assert len(a.member) == 3 +final = Path(a.out) +stage = final.parent / f'.{final.name}-staging-{os.getpid()}' +shutil.rmtree(stage, ignore_errors=True) +stage.mkdir(parents=True) + +def digest(path): + h = hashlib.sha256() + with Path(path).open('rb') as f: + for block in iter(lambda: f.read(8 * 1024 * 1024), b''): + h.update(block) + return h.hexdigest() + +for name in ('infer.sh', 'predict.py', 'model.py', 'seasonal.py', 'continuity.py', + 'zero_mass.py', 'ts_io.py'): + shutil.copy2(HERE / 'runtime' / name, stage / name) +shutil.copy2('/opt/runtime/requirements.txt', stage / 'requirements.txt') +shutil.copy2(a.experiments, stage / 'EXPERIMENTS.md') +members, sources, lineage = [], set(), {} +for i, source in enumerate(map(Path, a.member)): + manifest = json.loads((source / 'model_manifest.json').read_text()) + assert manifest['pretrained_assets'] == [] + for shared in ['seasonal.py','continuity.py','zero_mass.py']: + assert digest(source/shared)==digest(stage/shared),'Members must retain identical fixed postprocessing rules' + name = f'member{i}.pt' + model_code = f'model{i}.py' + shutil.copy2(source / 'model.py', stage / model_code) + assert digest(stage / model_code) == manifest['runtime_code_sha256']['model.py'] + shutil.copy2(source / 'weights.pt', stage / name) + assert digest(stage / name) == manifest['weights_sha256'] + members.append({'weights': name, 'weights_sha256': manifest['weights_sha256'], + 'parameters': manifest['parameters'], 'config': manifest['config'], 'model_code': model_code}) + sources.update(manifest['sources_used']) + for item in manifest['training_lineage']: + lineage.setdefault(item['sha256'], item) + dst = stage / 'provenance' / f'member{i}' + dst.mkdir(parents=True) + shutil.copy2(source / 'model_manifest.json', dst / 'model_manifest.json') + shutil.copytree(source / 'provenance', dst / 'training') +shutil.copy2(__file__, stage / 'provenance' / 'publish.py') +descriptor = {'members': members, 'weights': [1/3]*3, + 'composition': 'mean after each member applies its fixed inference rules'} +(stage / 'config.json').write_text(json.dumps(descriptor, indent=2) + '\n') +identifier = digest(stage / 'config.json') +manifest = { + 'name': 'direct-seasonal-three-patch-foundation', 'contract': 'timeseries-forecast/v1', + 'parameters': sum(m['parameters'] for m in members), 'pretrained_assets': [], + 'sources_used': sorted(sources), 'members': members, + 'checkpoint_sha256': identifier, + 'checkpoint_digest_method': 'SHA-256 of config.json, including ordered member weight hashes', + 'training_lineage': list(lineage.values()), 'ensemble_weights': [1/3]*3, + 'every_member_forecasts_every_instance': True, + 'member_history_caps': [{'input_and_summary': m['config']['max_context'], 'encoder_and_normalization': m['config'].get('encoder_context',m['config']['max_context']), 'fixed_rules': m['config'].get('encoder_context',m['config']['max_context'])} for m in members], + 'postprocessing_order': 'each member: sign averaging, positivity, aligned seasonal rule, continuity, zero0.4, finite-value replacement; then equal quantile average', + 'runtime_code_sha256': {p.name: digest(p) for p in stage.iterdir() if p.suffix in ('.py', '.sh')}, + 'notes': 'All members originate from random initialization in this workspace. Only declared pretraining sources and local generators were used. Validation is selection/diagnostics only. No inference-time fitting or parameter adaptation.', +} +(stage / 'model_manifest.json').write_text(json.dumps(manifest, indent=2) + '\n') +if a.report: + report = json.loads(Path(a.report).read_text()) + assert report['checkpoint_sha256'] == identifier + shutil.copy2(a.report, stage / 'validation_report.json') +else: + report = {'status': 'candidate validation pending'} + (stage / 'validation_report.json').write_text(json.dumps(report) + '\n') +if final.resolve() == Path('/workspace/submission').resolve(): + assert a.report and report['n_configs'] == 97 and report['n_instances'] == 151170 + assert report['n_failed'] == 0 +patch_sizes = ', '.join(str(m['config'].get('input_patch', m['config']['patch'])) + '/' + str(m['config']['patch']) for m in members) +(stage / 'README.md').write_text(f'''# Three-member seasonal foundation forecaster + +Run `bash infer.sh INPUT_DIR OUTPUT_DIR`. All runtime assets are included, with versions pinned in requirements.txt. The package contains three locally trained models totaling {manifest['parameters']:,} parameters. Every member forecasts every instance; their nine ordered quantiles are averaged with fixed equal weights of 1/3 each. + +Each member retains its declared context limits, listed in model_manifest.json under member_history_caps. A model with a separate encoder_context uses longer history only for learned seasonal summaries; its encoder, normalization and fixed forecast rules use the shorter declared limit. Their history/forecast patch sizes are {patch_sizes}, in member order. Each member retains its own original model implementation and normalization; the first has a float64 fallback for nonfinite float32 context statistics. Each member uses finite-history normalization and the same fixed sign averaging, positivity, seasonal, continuity and zero-mass rules. The seasonal template aligns four cycles to the latest cycle's mean and amplitude. The trend summary uses a fixed width of 128 observations. The zero projection threshold is 0.4 context standard deviations. No additional zero projection is applied after averaging. There is no inference-time training, fitting or parameter adaptation. + +model_manifest.json declares every source, member hash and training lineage. config.json contains relative member paths and their hashes. The original member manifests and all trainer/generator code are archived in provenance/. No pretrained assets were used. Normalization uses the supplied context and needs no external statistics. + +EXPERIMENTS.md records hypotheses, negative results, compute, group metrics and hashes. validation_report.json records the package evaluation. Validation and earlier-cutoff scores are not the held-out reward scale. +''') +if final.exists(): + libc = ctypes.CDLL(None, use_errno=True) + if libc.renameat2(-100, os.fsencode(stage), -100, os.fsencode(final), 2): + raise OSError(ctypes.get_errno(), os.strerror(ctypes.get_errno())) + shutil.rmtree(stage) +else: + os.replace(stage, final) +print(json.dumps({'out': str(final), 'checkpoint_sha256': identifier, + 'parameters': manifest['parameters']})) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/requirements.txt b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..ca733199990e5dc8e6a90509cc691f00ab8e9f5d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/requirements.txt @@ -0,0 +1,12 @@ +# Runtime pins recorded from the contributor's working environment on 2026-09-17 (Python 3.11). +# torch comes from the pytorch/pytorch:2.14.0-cuda12.6-cudnn9-runtime base image (cu130 needs driver >= 580). +torch==2.14.0 +numpy==2.4.6 +h5py==3.16.0 +pandas==2.3.3 +scipy==1.17.1 +pyarrow==25.0.1 +huggingface-hub==0.36.2 +einops==0.8.2 +safetensors==0.8.0 +pytest==9.1.1 diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/seasonal.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/seasonal.py new file mode 100644 index 0000000000000000000000000000000000000000..cd8d8ebbf65c59c69f3d1c537e8cd5cb024d0330 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/seasonal.py @@ -0,0 +1,51 @@ +"""A fixed confidence gate for highly repeatable history; no fitted parameters.""" +import numpy as np + +def apply_gate(ctx,periods,quant,threshold=.25,strength=1.,cycles=4,mode='aligned'): + # Each row uses only its own context. Quantile blending preserves ordering. + b,_,h=quant.shape + out=quant.copy() + for i in range(b): + x=ctx[i];valid=np.isfinite(x) + if not valid.any():continue + x=x[np.flatnonzero(valid)[0]:] + best=None + for p in periods[i]: + p=int(p) + if p<2 or len(x)<3*p:continue + k=min(len(x)//p,8);history=x[-k*p:] + pairs=np.isfinite(history[p:])&np.isfinite(history[:-p]) + if pairs.sum()0) + if mode in ('centered','aligned'): + mu=mu+np.nanmean(seasons[-1])-np.nanmean(mu) + if mode=='aligned' and np.isfinite(seasons[-1]).sum()>=max(2,.75*p): + noise=float(np.mean(err.astype(np.float64)**2)/2) + target_var=max(0.,float(np.nanvar(seasons[-1]))-noise) + template_var=max(0.,float(np.nanvar(mu))-noise/min(k,cycles)) + ratio=float(np.clip(np.sqrt(target_var/max(template_var,1e-12)),.5,2.)) + center=float(np.nanmean(mu));mu=center+(mu-center)*ratio + if mode=='exponential': + w=.5**np.arange(len(recent)-1,-1,-1,dtype=np.float32) + den=(w[:,None]*np.isfinite(recent)).sum(0) + mu=np.divide((w[:,None]*np.nan_to_num(recent)).sum(0),den,out=np.full(p,np.nan,np.float32),where=den>0) + # Error of a season relative to the previous one, corrected for averaging. + sigma=float(np.sqrt(np.mean(err.astype(np.float64)**2)/2*(1+1/min(k,cycles)))) + idx=np.arange(h)%p;median=mu[idx] + z=np.array([-1.2815515655,-.8416212336,-.5244005127,-.2533471031,0,.2533471031,.5244005127,.8416212336,1.2815515655]) + sq=median[None]+z[:,None]*sigma + sq=np.where(np.isfinite(sq),sq,quant[i]) + if np.nanmin(x)>=0:sq=np.maximum(0,sq) + best=(weight,sq) + if best is not None:out[i]=(1-best[0])*quant[i]+best[0]*best[1] + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/validation_report.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/validation_report.json new file mode 100644 index 0000000000000000000000000000000000000000..0a3ccc71d2635b21514b261ffa83c1edb8bbf598 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/validation_report.json @@ -0,0 +1,4889 @@ +{ + "contract": "timeseries-forecast/v1", + "split": "valid", + "reward": 0.3840414658263811, + "skill_score": 0.3840414658263811, + "rel_mase_gmean": 0.736336204750612, + "rel_wql_gmean": 0.5152604386060482, + "n_configs": 97, + "n_failed": 0, + "n_instances": 151170, + "n_instances_scored": 151170, + "n_partial": 0, + "failures": [], + "groups": { + "term": { + "long": { + "n_configs": 21, + "rel_mase_gmean": 0.7352835272649202, + "rel_wql_gmean": 0.4850713520961255 + }, + "medium": { + "n_configs": 21, + "rel_mase_gmean": 0.7028899568550665, + "rel_wql_gmean": 0.4973761567120901 + }, + "short": { + "n_configs": 55, + "rel_mase_gmean": 0.7499319258482755, + "rel_wql_gmean": 0.5344367465240951 + } + }, + "domain": { + "Econ/Fin": { + "n_configs": 6, + "rel_mase_gmean": 0.8914033840952631, + "rel_wql_gmean": 0.8479605603776146 + }, + "Energy": { + "n_configs": 32, + "rel_mase_gmean": 0.8945111738629334, + "rel_wql_gmean": 0.6443537668951484 + }, + "Healthcare": { + "n_configs": 5, + "rel_mase_gmean": 0.5428131275154696, + "rel_wql_gmean": 0.48709399373367207 + }, + "Nature": { + "n_configs": 15, + "rel_mase_gmean": 0.797466577327002, + "rel_wql_gmean": 0.3867526924380948 + }, + "Sales": { + "n_configs": 4, + "rel_mase_gmean": 0.8194734039990599, + "rel_wql_gmean": 0.5015741614043798 + }, + "Transport": { + "n_configs": 15, + "rel_mase_gmean": 0.6392540755254676, + "rel_wql_gmean": 0.4356914206717418 + }, + "Web/CloudOps": { + "n_configs": 20, + "rel_mase_gmean": 0.5634440276655224, + "rel_wql_gmean": 0.4449270329736839 + } + }, + "frequency": { + "A": { + "n_configs": 1, + "rel_mase_gmean": 0.6815228630665663, + "rel_wql_gmean": 0.7256421859815497 + }, + "D": { + "n_configs": 15, + "rel_mase_gmean": 0.7572886169888661, + "rel_wql_gmean": 0.5159938632320982 + }, + "H": { + "n_configs": 31, + "rel_mase_gmean": 0.7319759967116845, + "rel_wql_gmean": 0.4946727705402397 + }, + "M": { + "n_configs": 5, + "rel_mase_gmean": 0.941241859454276, + "rel_wql_gmean": 0.7763446248815099 + }, + "Q": { + "n_configs": 1, + "rel_mase_gmean": 0.7932702996375327, + "rel_wql_gmean": 0.8289529402464686 + }, + "S": { + "n_configs": 6, + "rel_mase_gmean": 0.6560450245229245, + "rel_wql_gmean": 0.5030226297849075 + }, + "T": { + "n_configs": 30, + "rel_mase_gmean": 0.6843583243727168, + "rel_wql_gmean": 0.45897827189712775 + }, + "W": { + "n_configs": 8, + "rel_mase_gmean": 0.8801737379335511, + "rel_wql_gmean": 0.6607427396681995 + } + }, + "variates": { + "multivariate": { + "n_configs": 43, + "rel_mase_gmean": 0.7095058384149513, + "rel_wql_gmean": 0.5120267718166803 + }, + "univariate": { + "n_configs": 54, + "rel_mase_gmean": 0.7584249215244773, + "rel_wql_gmean": 0.517849994880674 + } + } + }, + "quantile_crossing_fraction_mean": 0.0, + "configs": [ + { + "config_id": "m4_yearly__A__short", + "leaderboard_key": "m4_yearly/A/short", + "dataset": "m4_yearly", + "term": "short", + "freq": "A-DEC", + "prediction_length": 6, + "seasonality": 1, + "n_variates": 1, + "n_instances": 22728, + "domain": "Econ/Fin", + "n_cohorts": 3, + "skipped_series": 235, + "dropped_containers": 11, + "status": "ok", + "baseline": { + "mase": 4.730803330645802, + "wql": 0.15602350647819704 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 22728, + "instances": 22728, + "fraction": 1.0 + }, + "metrics": { + "mase": 3.224150630506575, + "wql": 0.11321723830534539, + "wsql_by_level": [ + 0.06362947603598715, + 0.09794727474831348, + 0.11999136618716168, + 0.1329345597293388, + 0.13839142975881472, + 0.13847661038083722, + 0.1308579321343098, + 0.1139061404376211, + 0.0828203553357246 + ], + "n_valid_labels": 136368, + "n_masked_labels": 0, + "mae_median": 718.3772005568759, + "n_mase_elements": 136356, + "n_seasonal_error_zero": 2, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6815228630665663, + "wql": 0.7256421859815497 + } + }, + { + "config_id": "m4_quarterly__Q__short", + "leaderboard_key": "m4_quarterly/Q/short", + "dataset": "m4_quarterly", + "term": "short", + "freq": "Q-DEC", + "prediction_length": 8, + "seasonality": 4, + "n_variates": 1, + "n_instances": 23905, + "domain": "Econ/Fin", + "n_cohorts": 3, + "dropped_containers": 95, + "status": "ok", + "baseline": { + "mase": 1.5909093331240343, + "wql": 0.0995990835037221 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 23905, + "instances": 23905, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.26202112338345, + "wql": 0.08256295311626398, + "wsql_by_level": [ + 0.04829663580003271, + 0.07321153161004672, + 0.08864660681908518, + 0.09767244133405126, + 0.10165369623980562, + 0.10049275439066489, + 0.0941967833294117, + 0.08100408931802759, + 0.057892039205250136 + ], + "n_valid_labels": 191240, + "n_masked_labels": 0, + "mae_median": 578.8456506521476, + "n_mase_elements": 191232, + "n_seasonal_error_zero": 1, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7932702996375327, + "wql": 0.8289529402464686 + } + }, + { + "config_id": "m4_monthly__M__short", + "leaderboard_key": "m4_monthly/M/short", + "dataset": "m4_monthly", + "term": "short", + "freq": "M", + "prediction_length": 18, + "seasonality": 12, + "n_variates": 1, + "n_instances": 47501, + "domain": "Econ/Fin", + "n_cohorts": 3, + "dropped_containers": 499, + "status": "ok", + "baseline": { + "mase": 1.2366691185612824, + "wql": 0.11781121192744513 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 47501, + "instances": 47501, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9900329334980157, + "wql": 0.09213605284789878, + "wsql_by_level": [ + 0.05359295396776645, + 0.08151048458243851, + 0.09917584403655846, + 0.10960126566015284, + 0.11430231072691316, + 0.11298572417202252, + 0.10511853060865284, + 0.08963431087648957, + 0.06330305100009474 + ], + "n_valid_labels": 855018, + "n_masked_labels": 0, + "mae_median": 541.9857835810466, + "n_mase_elements": 855018, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8005641271691182, + "wql": 0.7820652325064054 + } + }, + { + "config_id": "m4_weekly__W__short", + "leaderboard_key": "m4_weekly/W/short", + "dataset": "m4_weekly", + "term": "short", + "freq": "W-SUN", + "prediction_length": 13, + "seasonality": 1, + "n_variates": 1, + "n_instances": 355, + "domain": "Econ/Fin", + "n_cohorts": 2, + "dropped_containers": 4, + "status": "ok", + "baseline": { + "mase": 2.895128591740639, + "wql": 0.06508715280630521 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 355, + "instances": 355, + "fraction": 1.0 + }, + "metrics": { + "mase": 3.103182537438902, + "wql": 0.0490313031548438, + "wsql_by_level": [ + 0.02551240032527442, + 0.039552688020796783, + 0.05000864652911286, + 0.056850677027657746, + 0.061145233675613635, + 0.06278173295163805, + 0.05946900270058073, + 0.050717023104914764, + 0.03524432405800523 + ], + "n_valid_labels": 4615, + "n_masked_labels": 0, + "mae_median": 318.25216034034736, + "n_mase_elements": 4615, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.0718634558381308, + "wql": 0.7533176831495074 + } + }, + { + "config_id": "m4_daily__D__short", + "leaderboard_key": "m4_daily/D/short", + "dataset": "m4_daily", + "term": "short", + "freq": "D", + "prediction_length": 14, + "seasonality": 1, + "n_variates": 1, + "n_instances": 4204, + "domain": "Econ/Fin", + "n_cohorts": 2, + "dropped_containers": 23, + "status": "ok", + "baseline": { + "mase": 3.2161164077095057, + "wql": 0.02310161661155265 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 4204, + "instances": 4204, + "fraction": 1.0 + }, + "metrics": { + "mase": 3.322360611762378, + "wql": 0.021915176925281464, + "wsql_by_level": [ + 0.013599853580358902, + 0.019807395473452748, + 0.023711896960397317, + 0.02602910815084177, + 0.02699428814969528, + 0.026687550503513093, + 0.02481156177413627, + 0.02097824103647733, + 0.014616696698660487 + ], + "n_valid_labels": 58856, + "n_masked_labels": 0, + "mae_median": 172.95910500721777, + "n_mase_elements": 58842, + "n_seasonal_error_zero": 1, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.0330349373543162, + "wql": 0.948642568776859 + } + }, + { + "config_id": "m4_hourly__H__short", + "leaderboard_key": "m4_hourly/H/short", + "dataset": "m4_hourly", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 414, + "domain": "Econ/Fin", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.22836124915778, + "wql": 0.034474947608819397 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 414, + "instances": 414, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.2859365919197574, + "wql": 0.03812250098895092, + "wsql_by_level": [ + 0.01942216754299224, + 0.032431552528164556, + 0.0413709210480085, + 0.04650889089258361, + 0.04867356525865096, + 0.04815104972516604, + 0.044566598167316014, + 0.03697945526682535, + 0.02499830847085101 + ], + "n_valid_labels": 19872, + "n_masked_labels": 0, + "mae_median": 366.6579959957805, + "n_mase_elements": 19872, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.0468716697156097, + "wql": 1.1058030144532665 + } + }, + { + "config_id": "electricity__T__short", + "leaderboard_key": "electricity/15T/short", + "dataset": "electricity/15T", + "term": "short", + "freq": "15T", + "prediction_length": 48, + "seasonality": 96, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0916823579221513, + "wql": 0.06198863606457304 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9748916598805852, + "wql": 0.0481780134201536, + "wsql_by_level": [ + 0.030674980297594582, + 0.046609292737966414, + 0.056371120605504664, + 0.06150137727679347, + 0.06257588271862419, + 0.059125553704884946, + 0.05117039481053607, + 0.039370226852771466, + 0.02620329177670653 + ], + "n_valid_labels": 17712, + "n_masked_labels": 48, + "mae_median": 63.561615001626464, + "n_mase_elements": 17712, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 0.8930176921940379, + "wql": 0.7772071863295551 + } + }, + { + "config_id": "electricity__T__medium", + "leaderboard_key": "electricity/15T/medium", + "dataset": "electricity/15T", + "term": "medium", + "freq": "15T", + "prediction_length": 480, + "seasonality": 96, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.5099936923797364, + "wql": 0.12054261982000446 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9583491839234712, + "wql": 0.08939755702612769, + "wsql_by_level": [ + 0.04170644315374565, + 0.06675633000927708, + 0.08493141469526783, + 0.09907778140923486, + 0.10937375439032933, + 0.11399628673186689, + 0.1118088633634123, + 0.1008452173923454, + 0.07608192208966988 + ], + "n_valid_labels": 177120, + "n_masked_labels": 480, + "mae_median": 78.66392811559113, + "n_mase_elements": 177120, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 0.634670984892077, + "wql": 0.7416261332267133 + } + }, + { + "config_id": "electricity__T__long", + "leaderboard_key": "electricity/15T/long", + "dataset": "electricity/15T", + "term": "long", + "freq": "15T", + "prediction_length": 720, + "seasonality": 96, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0941077605435365, + "wql": 0.107564338522276 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8807451322002883, + "wql": 0.08598214390050388, + "wsql_by_level": [ + 0.040259513201368675, + 0.06461234459052992, + 0.08172983577559019, + 0.09406231951783589, + 0.10341954611823684, + 0.10794752882890944, + 0.10710808915504563, + 0.09807090094048605, + 0.07662921697653222 + ], + "n_valid_labels": 265680, + "n_masked_labels": 720, + "mae_median": 74.57029837773966, + "n_mase_elements": 265680, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 0.8049893840098046, + "wql": 0.7993554841849135 + } + }, + { + "config_id": "electricity__H__short", + "leaderboard_key": "electricity/H/short", + "dataset": "electricity/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9861593153062442, + "wql": 0.06763119078713985 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0317449086540007, + "wql": 0.0746686866002208, + "wsql_by_level": [ + 0.047452370299832666, + 0.06812530734353674, + 0.0822639453801325, + 0.09003978353076168, + 0.09311272185372324, + 0.09154804884758624, + 0.08464414484601064, + 0.07030217229389585, + 0.044529685006507794 + ], + "n_valid_labels": 17712, + "n_masked_labels": 48, + "mae_median": 282.7861787666564, + "n_mase_elements": 17712, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 1.046225384316935, + "wql": 1.104056955543346 + } + }, + { + "config_id": "electricity__H__medium", + "leaderboard_key": "electricity/H/medium", + "dataset": "electricity/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.2478422873379948, + "wql": 0.12311153060577013 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.97278917310093, + "wql": 0.07825705091209363, + "wsql_by_level": [ + 0.042544088732908894, + 0.06431798659923339, + 0.07792016843810916, + 0.08706308329802485, + 0.09442450462706584, + 0.09726460514513104, + 0.09437573015963893, + 0.08413958327977408, + 0.06226370792895651 + ], + "n_valid_labels": 177120, + "n_masked_labels": 480, + "mae_median": 254.11201438207385, + "n_mase_elements": 177120, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 0.7795770210482033, + "wql": 0.6356597999150032 + } + }, + { + "config_id": "electricity__H__long", + "leaderboard_key": "electricity/H/long", + "dataset": "electricity/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.356699671272273, + "wql": 0.14674885232557194 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.1944749667842463, + "wql": 0.09174926491570988, + "wsql_by_level": [ + 0.04344101909892855, + 0.06914741522944087, + 0.08743433189649588, + 0.1004142203794506, + 0.10884421028129705, + 0.11273745545028171, + 0.11185503521003225, + 0.10524749665826363, + 0.0866222000371983 + ], + "n_valid_labels": 265680, + "n_masked_labels": 720, + "mae_median": 298.3198837211318, + "n_mase_elements": 265680, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 0.8804269596852654, + "wql": 0.6252128276421415 + } + }, + { + "config_id": "electricity__D__short", + "leaderboard_key": "electricity/D/short", + "dataset": "electricity/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.6456666278884469, + "wql": 0.09261378216375024 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.4931981089651991, + "wql": 0.06740212078398382, + "wsql_by_level": [ + 0.028841217712550098, + 0.04699618910212032, + 0.06321633474024704, + 0.07499337255017999, + 0.08316954947337982, + 0.08676969101748531, + 0.08511005835410908, + 0.07761800542685568, + 0.05990466867892702 + ], + "n_valid_labels": 11070, + "n_masked_labels": 30, + "mae_median": 5470.820417611881, + "n_mase_elements": 11070, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 0.907351515586799, + "wql": 0.7277763547633792 + } + }, + { + "config_id": "electricity__W__short", + "leaderboard_key": "electricity/W/short", + "dataset": "electricity/W", + "term": "short", + "freq": "W-FRI", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.316880865245498, + "wql": 0.06523927951573125 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.4370512107366757, + "wql": 0.0668862683282871, + "wsql_by_level": [ + 0.02673437198735206, + 0.04669248832505202, + 0.06400183225131346, + 0.07607907838319355, + 0.08421431052378779, + 0.08712503165409168, + 0.08470561373910604, + 0.07553000059600022, + 0.05689368749468716 + ], + "n_valid_labels": 2952, + "n_masked_labels": 8, + "mae_median": 36265.88392620035, + "n_mase_elements": 2952, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 1.0912537714402701, + "wql": 1.0252453556320884 + } + }, + { + "config_id": "solar__T__short", + "leaderboard_key": "solar/10T/short", + "dataset": "solar/10T", + "term": "short", + "freq": "10T", + "prediction_length": 48, + "seasonality": 144, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.016018364778558773, + "wql": 12.118563297136966 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.017834025888467758, + "wql": 0.4229308021858361, + "wsql_by_level": [ + 0.17532517895443991, + 0.33190044897167426, + 0.42503648042251163, + 0.4835464454310376, + 0.5127838057593059, + 0.5149265509049759, + 0.5139902059133474, + 0.4861624441076431, + 0.3627056592075896 + ], + "n_valid_labels": 6576, + "n_masked_labels": 0, + "mae_median": 0.049555065047444544, + "n_mase_elements": 6576, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.1133487178628445, + "wql": 0.03489941767979661 + } + }, + { + "config_id": "solar__T__medium", + "leaderboard_key": "solar/10T/medium", + "dataset": "solar/10T", + "term": "medium", + "freq": "10T", + "prediction_length": 480, + "seasonality": 144, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.8331425981399365, + "wql": 0.5650432034501303 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7008418829062425, + "wql": 0.28580476533322835, + "wsql_by_level": [ + 0.21424635522576624, + 0.31638564334293595, + 0.3521577338118861, + 0.3523084835765539, + 0.339105795270457, + 0.31982038545900493, + 0.2876942128994181, + 0.23464067775484432, + 0.15588360065818863 + ], + "n_valid_labels": 65760, + "n_masked_labels": 0, + "mae_median": 1.6203148877980649, + "n_mase_elements": 65760, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8412027958610364, + "wql": 0.5058104647363535 + } + }, + { + "config_id": "solar__T__long", + "leaderboard_key": "solar/10T/long", + "dataset": "solar/10T", + "term": "long", + "freq": "10T", + "prediction_length": 720, + "seasonality": 144, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 2.1421153816960863, + "wql": 0.9032285592107642 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6899344074168968, + "wql": 0.22098777399877034, + "wsql_by_level": [ + 0.1657521488689763, + 0.25842004062452606, + 0.2947111501962519, + 0.2966710385302104, + 0.275279406625686, + 0.23919666720394123, + 0.19458630851052228, + 0.15068845745062012, + 0.1135847479781988 + ], + "n_valid_labels": 98640, + "n_masked_labels": 0, + "mae_median": 1.6174656334524975, + "n_mase_elements": 98640, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.3220808801020886, + "wql": 0.2446642898358619 + } + }, + { + "config_id": "solar__H__short", + "leaderboard_key": "solar/H/short", + "dataset": "solar/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0569321595099215, + "wql": 0.602297355940449 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8569317791960304, + "wql": 0.3277015902457833, + "wsql_by_level": [ + 0.21502390229544405, + 0.3587000631259484, + 0.42148079614494965, + 0.42969511720321746, + 0.405319272503219, + 0.3654251281323272, + 0.3156208072999102, + 0.2585449119586868, + 0.17950431354834726 + ], + "n_valid_labels": 6576, + "n_masked_labels": 0, + "mae_median": 11.179412502784695, + "n_mase_elements": 6576, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.810772736438801, + "wql": 0.5440860515386094 + } + }, + { + "config_id": "solar__H__medium", + "leaderboard_key": "solar/H/medium", + "dataset": "solar/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.3782698364748944, + "wql": 0.9679824737641872 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.2020780513264817, + "wql": 0.4439859977484182, + "wsql_by_level": [ + 0.4473541675826956, + 0.5660445326889616, + 0.5901415054107925, + 0.5693369487915313, + 0.5236664779144371, + 0.46043577526595236, + 0.3810627343686365, + 0.28485709507628504, + 0.17297474263647172 + ], + "n_valid_labels": 65760, + "n_masked_labels": 0, + "mae_median": 15.692728716066139, + "n_mase_elements": 65760, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.872164520701515, + "wql": 0.45867152534476446 + } + }, + { + "config_id": "solar__H__long", + "leaderboard_key": "solar/H/long", + "dataset": "solar/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0723400769109404, + "wql": 0.9027882643891623 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0397845461908755, + "wql": 0.35523438265452767, + "wsql_by_level": [ + 0.422251421473756, + 0.463730757803259, + 0.463146631658595, + 0.4410645936938476, + 0.40533455810892366, + 0.35723930825317446, + 0.296248277350808, + 0.22030053466368157, + 0.12779336088470403 + ], + "n_valid_labels": 98640, + "n_masked_labels": 0, + "mae_median": 13.6642168934616, + "n_mase_elements": 98640, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9696406658474924, + "wql": 0.39348582238702856 + } + }, + { + "config_id": "solar__D__short", + "leaderboard_key": "solar/D/short", + "dataset": "solar/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.1670584568457976, + "wql": 0.4714212933677157 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.1384428035006857, + "wql": 0.2874802626377011, + "wsql_by_level": [ + 0.2479490357645409, + 0.35142397274809806, + 0.38441202908878264, + 0.3823772452176032, + 0.3560071066173321, + 0.31369608898390394, + 0.25645786111047036, + 0.18734600235060395, + 0.10765302185797472 + ], + "n_valid_labels": 4110, + "n_masked_labels": 0, + "mae_median": 288.0321882489244, + "n_mase_elements": 4110, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9754805312645167, + "wql": 0.609816032245837 + } + }, + { + "config_id": "solar__W__short", + "leaderboard_key": "solar/W/short", + "dataset": "solar/W", + "term": "short", + "freq": "W-FRI", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0078578333938706, + "wql": 0.13890951079671932 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.02658128299511, + "wql": 0.1207374671853714, + "wsql_by_level": [ + 0.058426444416409595, + 0.11526136855837674, + 0.1458568175780538, + 0.1549356763248177, + 0.15350622436890504, + 0.144585151106723, + 0.12961407265484332, + 0.10824072478291527, + 0.07621072487729809 + ], + "n_valid_labels": 1096, + "n_masked_labels": 0, + "mae_median": 942.6414361661368, + "n_mase_elements": 1096, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.0185774709297937, + "wql": 0.869180709750386 + } + }, + { + "config_id": "hospital__M__short", + "leaderboard_key": "hospital/M/short", + "dataset": "hospital", + "term": "short", + "freq": "M", + "prediction_length": 12, + "seasonality": 12, + "n_variates": 1, + "n_instances": 767, + "domain": "Healthcare", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9326829101839614, + "wql": 0.0633931064425068 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 767, + "instances": 767, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7963294014152847, + "wql": 0.05510020193887981, + "wsql_by_level": [ + 0.030107461302976295, + 0.04680925586000196, + 0.057856660199955307, + 0.065562187393082, + 0.06954994666506457, + 0.06893745595788468, + 0.06425620891843734, + 0.05453308407654765, + 0.03828955707596847 + ], + "n_valid_labels": 9204, + "n_masked_labels": 0, + "mae_median": 19.30993363834992, + "n_mase_elements": 9204, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8538050742864126, + "wql": 0.8691828659453992 + } + }, + { + "config_id": "covid_deaths__D__short", + "leaderboard_key": "covid_deaths/D/short", + "dataset": "covid_deaths", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 266, + "domain": "Healthcare", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 50.55549046119792, + "wql": 0.12549070850235644 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 266, + "instances": 266, + "fraction": 1.0 + }, + "metrics": { + "mase": 43.182272349798495, + "wql": 0.07437405231025364, + "wsql_by_level": [ + 0.06410263383366772, + 0.09224375964408078, + 0.1066992080165267, + 0.10317714690006535, + 0.0870851492389841, + 0.055057340770607276, + 0.04214410584698713, + 0.05561763302770721, + 0.06323949351365658 + ], + "n_valid_labels": 7980, + "n_masked_labels": 0, + "mae_median": 176.91847879909034, + "n_mase_elements": 6810, + "n_seasonal_error_zero": 39, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8541559374830222, + "wql": 0.5926658092687161 + } + }, + { + "config_id": "us_births__D__short", + "leaderboard_key": "us_births/D/short", + "dataset": "us_births/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 1, + "domain": "Healthcare", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 2.328105874599355, + "wql": 0.13056664093780335 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.453634180095643, + "wql": 0.025585137400478436, + "wsql_by_level": [ + 0.011641141483771827, + 0.0169083543722792, + 0.02233929799049746, + 0.024987300628179387, + 0.029439546204677893, + 0.03437628593135311, + 0.03628614413957195, + 0.03244702039597165, + 0.02184114545800345 + ], + "n_valid_labels": 30, + "n_masked_labels": 0, + "mae_median": 299.58369140625, + "n_mase_elements": 30, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.19485118140243907, + "wql": 0.19595462682283568 + } + }, + { + "config_id": "us_births__M__short", + "leaderboard_key": "us_births/M/short", + "dataset": "us_births/M", + "term": "short", + "freq": "M", + "prediction_length": 12, + "seasonality": 12, + "n_variates": 1, + "n_instances": 1, + "domain": "Healthcare", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.3023112362005141, + "wql": 0.011101802850788281 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.2710019605304404, + "wql": 0.007579726298581767, + "wsql_by_level": [ + 0.005187812540316009, + 0.005997213649494016, + 0.005688638570534366, + 0.007594726360816264, + 0.00809740394105408, + 0.00798063517589327, + 0.00961175451552568, + 0.010067760094332157, + 0.00799159183927006 + ], + "n_valid_labels": 12, + "n_masked_labels": 0, + "mae_median": 2541.9869791666665, + "n_mase_elements": 12, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8964336355354414, + "wql": 0.6827473339650929 + } + }, + { + "config_id": "us_births__W__short", + "leaderboard_key": "us_births/W/short", + "dataset": "us_births/W", + "term": "short", + "freq": "W-TUE", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 1, + "n_instances": 1, + "domain": "Healthcare", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 3.858436986096576, + "wql": 0.04221704717157443 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.42740114366871, + "wql": 0.01679635945239705, + "wsql_by_level": [ + 0.00984431737220709, + 0.017292207871314, + 0.020496991798334124, + 0.02121246364196981, + 0.02088097754581826, + 0.019844358855228245, + 0.017733694862238563, + 0.01477076482508658, + 0.009091458299376765 + ], + "n_valid_labels": 8, + "n_masked_labels": 0, + "mae_median": 1553.34375, + "n_mase_elements": 8, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.3699428418326338, + "wql": 0.39785727751481326 + } + }, + { + "config_id": "saugeenday__D__short", + "leaderboard_key": "saugeen/D/short", + "dataset": "saugeenday/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 3.898466092444523, + "wql": 0.5418638069109889 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 3.1688893597531878, + "wql": 0.31701175050370056, + "wsql_by_level": [ + 0.14640959739187023, + 0.2630538418145887, + 0.3554312549558128, + 0.41999526316519276, + 0.4484659570079385, + 0.4191070829504553, + 0.3331573984325169, + 0.2224813007414401, + 0.24500405807348952 + ], + "n_valid_labels": 30, + "n_masked_labels": 0, + "mae_median": 13.932342497507731, + "n_mase_elements": 30, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8128554371409561, + "wql": 0.585039536615103 + } + }, + { + "config_id": "saugeenday__M__short", + "leaderboard_key": "saugeen/M/short", + "dataset": "saugeenday/M", + "term": "short", + "freq": "M", + "prediction_length": 12, + "seasonality": 12, + "n_variates": 1, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.33228103391864, + "wql": 0.2615013833629034 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.44361666109016684, + "wql": 0.23006679849804915, + "wsql_by_level": [ + 0.12150723801188264, + 0.2028643663227103, + 0.25055051899602626, + 0.26819886052915304, + 0.26442695076375017, + 0.24994066901882772, + 0.2537911250998105, + 0.26380825724837625, + 0.19551320049190532 + ], + "n_valid_labels": 12, + "n_masked_labels": 0, + "mae_median": 7.690133094787598, + "n_mase_elements": 12, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.3350646465087974, + "wql": 0.8797918983807809 + } + }, + { + "config_id": "saugeenday__W__short", + "leaderboard_key": "saugeen/W/short", + "dataset": "saugeenday/W", + "term": "short", + "freq": "W-THU", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 1, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.5685710422753978, + "wql": 0.5994091721735982 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7269368181249621, + "wql": 0.2385501032347118, + "wsql_by_level": [ + 0.10437352642944421, + 0.17924443102020504, + 0.2417963278107811, + 0.3098669929277486, + 0.3562788037598706, + 0.361322116894787, + 0.29118766167775284, + 0.13531127310514485, + 0.16756979548667195 + ], + "n_valid_labels": 8, + "n_masked_labels": 0, + "mae_median": 8.712289094924927, + "n_mase_elements": 8, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.2785329608342189, + "wql": 0.3979753969557609 + } + }, + { + "config_id": "temperature_rain_with_missing__D__short", + "leaderboard_key": "temperature_rain/D/short", + "dataset": "temperature_rain_with_missing", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 32072, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 3.2912255413171745, + "wql": 1.099183165150044 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 32072, + "instances": 32072, + "fraction": 1.0 + }, + "metrics": { + "mase": 2.1187948648158197, + "wql": 0.5275344833987082, + "wsql_by_level": [ + 0.18069438826700274, + 0.33987506116636823, + 0.4761158815089989, + 0.5857636479554693, + 0.6625337147748191, + 0.7052519647586281, + 0.7021185857942273, + 0.6330012101636937, + 0.4624558961991657 + ], + "n_valid_labels": 961756, + "n_masked_labels": 404, + "mae_median": 6.656451319518237, + "n_mase_elements": 960736, + "n_seasonal_error_zero": 34, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6437707893965423, + "wql": 0.4799331905039658 + } + }, + { + "config_id": "kdd_cup_2018_with_missing__H__short", + "leaderboard_key": "kdd_cup_2018/H/short", + "dataset": "kdd_cup_2018_with_missing/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 270, + "domain": "Nature", + "n_cohorts": 2, + "status": "ok", + "baseline": { + "mase": 0.6811227593500775, + "wql": 0.6266148384878599 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 270, + "instances": 270, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.5377790301923974, + "wql": 0.38261552292161316, + "wsql_by_level": [ + 0.1495412603623317, + 0.2510778091303381, + 0.34172249286087486, + 0.4207206679871921, + 0.4786534536364155, + 0.502935983035553, + 0.4983766195971858, + 0.4593815463539479, + 0.3411298733306794 + ], + "n_valid_labels": 11685, + "n_masked_labels": 1275, + "mae_median": 12.302581688637375, + "n_mase_elements": 11685, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7895478793067233, + "wql": 0.6106071855000063 + } + }, + { + "config_id": "kdd_cup_2018_with_missing__H__medium", + "leaderboard_key": "kdd_cup_2018/H/medium", + "dataset": "kdd_cup_2018_with_missing/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 1, + "n_instances": 270, + "domain": "Nature", + "n_cohorts": 2, + "status": "ok", + "baseline": { + "mase": 1.2781450805103305, + "wql": 1.049898934007083 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 270, + "instances": 270, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9258810355865157, + "wql": 0.46026254815754847, + "wsql_by_level": [ + 0.18026982743040465, + 0.330540723257441, + 0.45135946430960283, + 0.5419009187470036, + 0.5979733936434599, + 0.6122737827722383, + 0.5807262678060301, + 0.4979724130570594, + 0.34934614239469636 + ], + "n_valid_labels": 116458, + "n_masked_labels": 13142, + "mae_median": 20.04187739709478, + "n_mase_elements": 116458, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7243943193184573, + "wql": 0.4383874802128748 + } + }, + { + "config_id": "kdd_cup_2018_with_missing__H__long", + "leaderboard_key": "kdd_cup_2018/H/long", + "dataset": "kdd_cup_2018_with_missing/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 1, + "n_instances": 270, + "domain": "Nature", + "n_cohorts": 2, + "status": "ok", + "baseline": { + "mase": 0.981050679806651, + "wql": 1.2362237298155803 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 270, + "instances": 270, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8678562075915145, + "wql": 0.4699297869261019, + "wsql_by_level": [ + 0.18280119143537446, + 0.3287834577708812, + 0.4500789304880269, + 0.542557767318925, + 0.6036360476620796, + 0.6265496524201916, + 0.6068241711266946, + 0.5300534008873866, + 0.35808346322535606 + ], + "n_valid_labels": 175906, + "n_masked_labels": 18494, + "mae_median": 18.40978762122815, + "n_mase_elements": 175906, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8846191389037666, + "wql": 0.3801332846087706 + } + }, + { + "config_id": "kdd_cup_2018_with_missing__D__short", + "leaderboard_key": "kdd_cup_2018/D/short", + "dataset": "kdd_cup_2018_with_missing/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 270, + "domain": "Nature", + "n_cohorts": 2, + "status": "ok", + "baseline": { + "mase": 1.2132840958596942, + "wql": 0.8994855622016019 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 270, + "instances": 270, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0170419722258115, + "wql": 0.39191477786951084, + "wsql_by_level": [ + 0.16244390546841828, + 0.28716215024309677, + 0.38011495750580643, + 0.4479568313822988, + 0.49093909833357846, + 0.5088201573892727, + 0.4986868204110766, + 0.4442819154617764, + 0.3068271646302731 + ], + "n_valid_labels": 7581, + "n_masked_labels": 519, + "mae_median": 15.237021001693426, + "n_mase_elements": 7581, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8382554223668185, + "wql": 0.43570991502103834 + } + }, + { + "config_id": "car_parts_with_missing__M__short", + "leaderboard_key": "car_parts/M/short", + "dataset": "car_parts_with_missing", + "term": "short", + "freq": "M", + "prediction_length": 12, + "seasonality": 12, + "n_variates": 1, + "n_instances": 2674, + "domain": "Sales", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.556811831303017, + "wql": 1.6139130745452677 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 2674, + "instances": 2674, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.4059406654776905, + "wql": 1.114702011751438, + "wsql_by_level": [ + 0.2817125391751903, + 0.5485203887835316, + 0.816045755316261, + 1.0749777809204852, + 1.3054839466526742, + 1.4923395266652484, + 1.6079327334395308, + 1.5866894631035593, + 1.318615971706461 + ], + "n_valid_labels": 30108, + "n_masked_labels": 1980, + "mae_median": 0.6177504247363043, + "n_mase_elements": 28068, + "n_seasonal_error_zero": 215, + "n_seasonal_error_nan": 7 + }, + "relative": { + "mase": 0.9030896587553225, + "wql": 0.6906828064860393 + } + }, + { + "config_id": "restaurant__D__short", + "leaderboard_key": "restaurant/D/short", + "dataset": "restaurant", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 806, + "domain": "Sales", + "n_cohorts": 13, + "skipped_series": 1, + "status": "ok", + "baseline": { + "mase": 1.0028179898604987, + "wql": 0.6760963195065456 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 806, + "instances": 806, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.69195741056202, + "wql": 0.2616077056903981, + "wsql_by_level": [ + 0.13248298268715225, + 0.21539348300063232, + 0.2739158316680015, + 0.312393167184629, + 0.3318887188682136, + 0.3320155810986673, + 0.31054906369630747, + 0.2640438168009737, + 0.18178670620900625 + ], + "n_valid_labels": 21222, + "n_masked_labels": 2958, + "mae_median": 7.098558903456678, + "n_mase_elements": 21222, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6900129610342128, + "wql": 0.3869385147390458 + } + }, + { + "config_id": "hierarchical_sales__D__short", + "leaderboard_key": "hierarchical_sales/D/short", + "dataset": "hierarchical_sales/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 118, + "domain": "Sales", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0956340453936162, + "wql": 1.4587792906606432 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 118, + "instances": 118, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9607199343866984, + "wql": 0.6325398079091678, + "wsql_by_level": [ + 0.19937655337300345, + 0.37352712039705727, + 0.5262647610254619, + 0.6594232663830794, + 0.7652255282550072, + 0.8386822122723688, + 0.8728467222819811, + 0.8288055861319179, + 0.628706521062633 + ], + "n_valid_labels": 3304, + "n_masked_labels": 236, + "mae_median": 3.000916213559361, + "n_mase_elements": 3304, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8768620676090357, + "wql": 0.4336089852377236 + } + }, + { + "config_id": "hierarchical_sales__W__short", + "leaderboard_key": "hierarchical_sales/W/short", + "dataset": "hierarchical_sales/W", + "term": "short", + "freq": "W-WED", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 1, + "n_instances": 118, + "domain": "Sales", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9952062817493519, + "wql": 0.7382990422957836 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 118, + "instances": 118, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8213592645240883, + "wql": 0.4032311269195719, + "wsql_by_level": [ + 0.14743766017823828, + 0.2624405134582727, + 0.3536448463832479, + 0.426170829710888, + 0.48357163931439084, + 0.5216761693292482, + 0.5358322421982076, + 0.5074587253520908, + 0.3908475163515633 + ], + "n_valid_labels": 944, + "n_masked_labels": 0, + "mae_median": 11.807549031988039, + "n_mase_elements": 944, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8253155949541645, + "wql": 0.5461623323602065 + } + }, + { + "config_id": "LOOP_SEATTLE__T__short", + "leaderboard_key": "loop_seattle/5T/short", + "dataset": "LOOP_SEATTLE/5T", + "term": "short", + "freq": "5T", + "prediction_length": 48, + "seasonality": 288, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.6088421384511257, + "wql": 0.05736115508602545 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.40853142388036856, + "wql": 0.02984343382461037, + "wsql_by_level": [ + 0.019547871516598817, + 0.0279175814993749, + 0.03315169686506874, + 0.036124192808225465, + 0.03720199734498119, + 0.036272609017324986, + 0.03316277214155729, + 0.02738820887682522, + 0.017823974351536653 + ], + "n_valid_labels": 15504, + "n_masked_labels": 0, + "mae_median": 2.412867829157472, + "n_mase_elements": 15504, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6709972882620429, + "wql": 0.5202725394886782 + } + }, + { + "config_id": "LOOP_SEATTLE__T__medium", + "leaderboard_key": "loop_seattle/5T/medium", + "dataset": "LOOP_SEATTLE/5T", + "term": "medium", + "freq": "5T", + "prediction_length": 480, + "seasonality": 288, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.5924843577520822, + "wql": 0.14109820582939464 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.61012025965996, + "wql": 0.05071583496925595, + "wsql_by_level": [ + 0.040107966676649225, + 0.05379500097891356, + 0.06074510080876187, + 0.06336460408347733, + 0.06261185180815212, + 0.0584695215515482, + 0.05125435717907145, + 0.04054077249130059, + 0.02555333914542926 + ], + "n_valid_labels": 155040, + "n_masked_labels": 0, + "mae_median": 3.803913294893792, + "n_mase_elements": 155040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.3831248053960122, + "wql": 0.35943642706965195 + } + }, + { + "config_id": "LOOP_SEATTLE__T__long", + "leaderboard_key": "loop_seattle/5T/long", + "dataset": "LOOP_SEATTLE/5T", + "term": "long", + "freq": "5T", + "prediction_length": 720, + "seasonality": 288, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.5910237866124803, + "wql": 0.14753926773607257 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6790759423805891, + "wql": 0.05751690116498588, + "wsql_by_level": [ + 0.044820746336101544, + 0.061657311066339024, + 0.06994152396749723, + 0.07274847175390502, + 0.0712048315968146, + 0.06603500072358526, + 0.057505081917163255, + 0.04525971251545086, + 0.028479430608016148 + ], + "n_valid_labels": 232560, + "n_masked_labels": 0, + "mae_median": 4.188771075859158, + "n_mase_elements": 232560, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.42681696407973885, + "wql": 0.3898413083347797 + } + }, + { + "config_id": "LOOP_SEATTLE__H__short", + "leaderboard_key": "loop_seattle/H/short", + "dataset": "LOOP_SEATTLE/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 2.0101473993616685, + "wql": 0.13665681786039896 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6699574943426808, + "wql": 0.043120923562349006, + "wsql_by_level": [ + 0.035440758374860645, + 0.04686945972077065, + 0.051840251795831634, + 0.05342875869672831, + 0.05226448899428686, + 0.04934348911618603, + 0.04371282173615908, + 0.03424550947646148, + 0.02094277414985637 + ], + "n_valid_labels": 15504, + "n_masked_labels": 0, + "mae_median": 3.16576542035591, + "n_mase_elements": 15504, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.3332877452446666, + "wql": 0.3155416922293548 + } + }, + { + "config_id": "LOOP_SEATTLE__H__medium", + "leaderboard_key": "loop_seattle/H/medium", + "dataset": "LOOP_SEATTLE/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.1535310881157237, + "wql": 0.14911283164622935 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.720731571792947, + "wql": 0.051296769944681096, + "wsql_by_level": [ + 0.043254998308312746, + 0.0568259484047454, + 0.06236104789075334, + 0.06328199094656854, + 0.061210043359712606, + 0.05665509181366015, + 0.04997565475362851, + 0.04086562031426876, + 0.027240533710479818 + ], + "n_valid_labels": 155040, + "n_masked_labels": 0, + "mae_median": 3.4149576766379908, + "n_mase_elements": 155040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6248046361457423, + "wql": 0.34401311663360296 + } + }, + { + "config_id": "LOOP_SEATTLE__H__long", + "leaderboard_key": "loop_seattle/H/long", + "dataset": "LOOP_SEATTLE/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.2448539713840052, + "wql": 0.17526380961630228 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7178952385441478, + "wql": 0.05063784307163717, + "wsql_by_level": [ + 0.042605915358572465, + 0.05532482379806189, + 0.060568107763955575, + 0.061668437746708465, + 0.06007925551834963, + 0.056190978439608144, + 0.050086158077303, + 0.04129274212762091, + 0.027924168814554447 + ], + "n_valid_labels": 232560, + "n_masked_labels": 0, + "mae_median": 3.3720579373901103, + "n_mase_elements": 232560, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.5766903227581026, + "wql": 0.2889235557671403 + } + }, + { + "config_id": "LOOP_SEATTLE__D__short", + "leaderboard_key": "loop_seattle/D/short", + "dataset": "LOOP_SEATTLE/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.1854124643746355, + "wql": 0.09281728785965133 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6005748178204637, + "wql": 0.027918309892447448, + "wsql_by_level": [ + 0.020322197852325887, + 0.02879450206720128, + 0.03311475730489969, + 0.03484139987982398, + 0.03451398646638897, + 0.032414193736851005, + 0.02870990892972141, + 0.023273702567926446, + 0.015280140226888355 + ], + "n_valid_labels": 9690, + "n_masked_labels": 0, + "mae_median": 1.9371605222562271, + "n_mase_elements": 9690, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.5066378462093336, + "wql": 0.3007878223576476 + } + }, + { + "config_id": "SZ_TAXI__T__short", + "leaderboard_key": "sz_taxi/15T/short", + "dataset": "SZ_TAXI/15T", + "term": "short", + "freq": "15T", + "prediction_length": 48, + "seasonality": 96, + "n_variates": 1, + "n_instances": 156, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7251090475210906, + "wql": 0.3023498132057821 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 156, + "instances": 156, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.5219186271489245, + "wql": 0.19671704366183634, + "wsql_by_level": [ + 0.10224900476425666, + 0.16690423979329688, + 0.21081165581830955, + 0.23839190361828827, + 0.2503847595783176, + 0.2473544191417603, + 0.22950188639499738, + 0.19321839226157692, + 0.1316371315857237 + ], + "n_valid_labels": 7488, + "n_masked_labels": 0, + "mae_median": 2.8024166060012674, + "n_mase_elements": 7488, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.719779499281098, + "wql": 0.6506273034405644 + } + }, + { + "config_id": "SZ_TAXI__T__medium", + "leaderboard_key": "sz_taxi/15T/medium", + "dataset": "SZ_TAXI/15T", + "term": "medium", + "freq": "15T", + "prediction_length": 480, + "seasonality": 96, + "n_variates": 1, + "n_instances": 156, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.6350051480164337, + "wql": 0.3916041859838231 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 156, + "instances": 156, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.4666392995219143, + "wql": 0.19457188762092745, + "wsql_by_level": [ + 0.10101949898709449, + 0.1608986212508068, + 0.20158369701581114, + 0.22774706666999966, + 0.24109184904445422, + 0.24155471518431174, + 0.22870199539147396, + 0.2005508584079657, + 0.14799868663642943 + ], + "n_valid_labels": 74880, + "n_masked_labels": 0, + "mae_median": 2.668229139311332, + "n_mase_elements": 74880, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7348590810319506, + "wql": 0.4968585489761978 + } + }, + { + "config_id": "SZ_TAXI__T__long", + "leaderboard_key": "sz_taxi/15T/long", + "dataset": "SZ_TAXI/15T", + "term": "long", + "freq": "15T", + "prediction_length": 720, + "seasonality": 96, + "n_variates": 1, + "n_instances": 156, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.6084219160390921, + "wql": 0.45522272202116565 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 156, + "instances": 156, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.4960446977378782, + "wql": 0.21829783639965727, + "wsql_by_level": [ + 0.1146060505529162, + 0.179686456026209, + 0.22269213779031918, + 0.24931314659075315, + 0.2626306858774101, + 0.2647056706021265, + 0.2560695760852541, + 0.23425129841996853, + 0.18072550565195883 + ], + "n_valid_labels": 112320, + "n_masked_labels": 0, + "mae_median": 2.9167029530109945, + "n_mase_elements": 112320, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8152972216503892, + "wql": 0.47954072993199026 + } + }, + { + "config_id": "SZ_TAXI__H__short", + "leaderboard_key": "sz_taxi/H/short", + "dataset": "SZ_TAXI/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 156, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.6087142479652129, + "wql": 0.20653078520030457 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 156, + "instances": 156, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.48164945647002017, + "wql": 0.13124390325116655, + "wsql_by_level": [ + 0.0701048059488322, + 0.10937280806918284, + 0.13555153494371572, + 0.15195584257844155, + 0.15964269216969607, + 0.15929888331483066, + 0.15140611802233836, + 0.13677027136840908, + 0.10709217284505242 + ], + "n_valid_labels": 7488, + "n_masked_labels": 0, + "mae_median": 1.7648730031540518, + "n_mase_elements": 7488, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7912570768304831, + "wql": 0.6354689598641636 + } + }, + { + "config_id": "M_DENSE__H__short", + "leaderboard_key": "m_dense/H/short", + "dataset": "M_DENSE/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 30, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.8744657675879529, + "wql": 0.18983266370122717 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 30, + "instances": 30, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7065080806918564, + "wql": 0.12712407476208118, + "wsql_by_level": [ + 0.09317256650336445, + 0.12655776924319154, + 0.14468594224346903, + 0.15401222960960279, + 0.15563447723545046, + 0.14860324696903382, + 0.13461381130337213, + 0.11192883437040868, + 0.07490779538083782 + ], + "n_valid_labels": 1440, + "n_masked_labels": 0, + "mae_median": 98.02756491369671, + "n_mase_elements": 1440, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8079310899048961, + "wql": 0.6696638622853576 + } + }, + { + "config_id": "M_DENSE__H__medium", + "leaderboard_key": "m_dense/H/medium", + "dataset": "M_DENSE/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 1, + "n_instances": 30, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.171624112893389, + "wql": 0.3497462745339787 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 30, + "instances": 30, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7786089978533002, + "wql": 0.13887773138237128, + "wsql_by_level": [ + 0.08402664012700325, + 0.12199560570172187, + 0.14408705339779465, + 0.15784526815036962, + 0.1663385207971593, + 0.168066448918461, + 0.16066188686304078, + 0.1418572003263864, + 0.10502095815940432 + ], + "n_valid_labels": 14400, + "n_masked_labels": 0, + "mae_median": 97.63414465400908, + "n_mase_elements": 14400, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6645552863626911, + "wql": 0.39708137439753904 + } + }, + { + "config_id": "M_DENSE__H__long", + "leaderboard_key": "m_dense/H/long", + "dataset": "M_DENSE/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 1, + "n_instances": 30, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0805183298420056, + "wql": 0.3841191250034235 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 30, + "instances": 30, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0672793707357693, + "wql": 0.17673171599908968, + "wsql_by_level": [ + 0.0885777704179357, + 0.1409098886414513, + 0.1779479473622779, + 0.2042086697888406, + 0.2216895718067124, + 0.22677310733650696, + 0.21685168874887728, + 0.1856407135016919, + 0.1279860863875134 + ], + "n_valid_labels": 21600, + "n_masked_labels": 0, + "mae_median": 129.92462051678586, + "n_mase_elements": 21600, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9877475848945828, + "wql": 0.46009611210458357 + } + }, + { + "config_id": "M_DENSE__D__short", + "leaderboard_key": "m_dense/D/short", + "dataset": "M_DENSE/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 30, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.007688577826318, + "wql": 0.1992117768924222 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 30, + "instances": 30, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0146909967850928, + "wql": 0.09300675561199173, + "wsql_by_level": [ + 0.062155977840783284, + 0.0920758739199232, + 0.11135392807539309, + 0.12167506550937991, + 0.12311962415265726, + 0.11390481914729532, + 0.09755896829291665, + 0.07196657060473871, + 0.04324997296483829 + ], + "n_valid_labels": 900, + "n_masked_labels": 0, + "mae_median": 72.15617010116577, + "n_mase_elements": 900, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.0069489910998888, + "wql": 0.46687378157475595 + } + }, + { + "config_id": "ett1__T__short", + "leaderboard_key": "ett1/15T/short", + "dataset": "ett1/15T", + "term": "short", + "freq": "15T", + "prediction_length": 48, + "seasonality": 96, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.2054822899524387, + "wql": 0.48104386522982623 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7861952701548554, + "wql": 0.2781313397322598, + "wsql_by_level": [ + 0.17163906990138705, + 0.2635094339766818, + 0.3175216885205536, + 0.3484613063247964, + 0.35654602517698736, + 0.35350738381853414, + 0.31966443888907814, + 0.24285488813285372, + 0.12947782284946613 + ], + "n_valid_labels": 336, + "n_masked_labels": 0, + "mae_median": 1.3030993169633716, + "n_mase_elements": 336, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6521831773952267, + "wql": 0.578182905626243 + } + }, + { + "config_id": "ett1__T__medium", + "leaderboard_key": "ett1/15T/medium", + "dataset": "ett1/15T", + "term": "medium", + "freq": "15T", + "prediction_length": 480, + "seasonality": 96, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7745679584044315, + "wql": 0.4386794376669185 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9483490405632168, + "wql": 0.36992177709382124, + "wsql_by_level": [ + 0.18453524701009083, + 0.3243701889494048, + 0.43478209696205533, + 0.4891891404441278, + 0.4976610379404633, + 0.4728583786043851, + 0.4110798558318513, + 0.3183976133825099, + 0.19642243471950266 + ], + "n_valid_labels": 3360, + "n_masked_labels": 0, + "mae_median": 1.6228282105078549, + "n_mase_elements": 3360, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.2243587283377497, + "wql": 0.8432621758184532 + } + }, + { + "config_id": "ett1__T__long", + "leaderboard_key": "ett1/15T/long", + "dataset": "ett1/15T", + "term": "long", + "freq": "15T", + "prediction_length": 720, + "seasonality": 96, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.327073089604087, + "wql": 0.5796800252115644 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.2995431955321375, + "wql": 0.479959837137, + "wsql_by_level": [ + 0.31319874037206374, + 0.4727527586752656, + 0.5847937953343401, + 0.6365326010830435, + 0.6329741751592887, + 0.5830491975985287, + 0.4951840906577475, + 0.3770096755473828, + 0.22414349980533962 + ], + "n_valid_labels": 5040, + "n_masked_labels": 0, + "mae_median": 2.1700557576004593, + "n_mase_elements": 5040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9792551787180293, + "wql": 0.8279737376871495 + } + }, + { + "config_id": "ett1__H__short", + "leaderboard_key": "ett1/H/short", + "dataset": "ett1/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0441605493380515, + "wql": 0.5044116168241106 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7714160684749277, + "wql": 0.3411749331970942, + "wsql_by_level": [ + 0.19669763475419064, + 0.299370922831512, + 0.36935852036282424, + 0.42199219887131, + 0.44364343233715464, + 0.43964223913076406, + 0.401412538544223, + 0.3206613242906956, + 0.1777955876511737 + ], + "n_valid_labels": 336, + "n_masked_labels": 0, + "mae_median": 5.361388619456973, + "n_mase_elements": 336, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7387906667839242, + "wql": 0.6763819900604363 + } + }, + { + "config_id": "ett1__H__medium", + "leaderboard_key": "ett1/H/medium", + "dataset": "ett1/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.2235872159229322, + "wql": 0.5499353323396741 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.4030182838162806, + "wql": 0.433627796039987, + "wsql_by_level": [ + 0.30610970566996526, + 0.4719287081629942, + 0.5400676155134152, + 0.5582423533249119, + 0.5439958424666501, + 0.5015402834859995, + 0.4317431148299099, + 0.33876845127430216, + 0.21025408963173495 + ], + "n_valid_labels": 3360, + "n_masked_labels": 0, + "mae_median": 8.324256275029898, + "n_mase_elements": 3360, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.1466434640361998, + "wql": 0.7885068853371139 + } + }, + { + "config_id": "ett1__H__long", + "leaderboard_key": "ett1/H/long", + "dataset": "ett1/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.4320631719624162, + "wql": 0.5783242328839591 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.4291033091507688, + "wql": 0.4167634685722065, + "wsql_by_level": [ + 0.3050582209370219, + 0.46987610512239636, + 0.5419404785268626, + 0.5557198010601024, + 0.5303603260607195, + 0.47422123923689485, + 0.3950821381799316, + 0.29707700996482267, + 0.18153589806110668 + ], + "n_valid_labels": 5040, + "n_masked_labels": 0, + "mae_median": 8.930028906732147, + "n_mase_elements": 5040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9979331478739228, + "wql": 0.7206398156513532 + } + }, + { + "config_id": "ett1__D__short", + "leaderboard_key": "ett1/D/short", + "dataset": "ett1/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.8181967261759215, + "wql": 0.48528320354978605 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.742680247137463, + "wql": 0.33727980726387363, + "wsql_by_level": [ + 0.16183829277173312, + 0.2941755551696673, + 0.3977656728434318, + 0.45164595518081424, + 0.45335308475809477, + 0.42474557196491897, + 0.364016907221025, + 0.2900617294003689, + 0.1979154960648083 + ], + "n_valid_labels": 210, + "n_masked_labels": 0, + "mae_median": 143.90527433213734, + "n_mase_elements": 210, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9584662770803207, + "wql": 0.6950164456480544 + } + }, + { + "config_id": "ett1__W__short", + "leaderboard_key": "ett1/W/short", + "dataset": "ett1/W", + "term": "short", + "freq": "W-THU", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.2444126904903803, + "wql": 0.25814356436755426 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0425318518944755, + "wql": 0.19703553405974528, + "wsql_by_level": [ + 0.1415173064672623, + 0.19169265463717025, + 0.23138093361348264, + 0.2376667368743951, + 0.22271069296219728, + 0.2167740227345499, + 0.21139684775853834, + 0.18327425029650843, + 0.13690636119360317 + ], + "n_valid_labels": 56, + "n_masked_labels": 0, + "mae_median": 555.8276361737933, + "n_mase_elements": 56, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8377701865798632, + "wql": 0.7632788930550245 + } + }, + { + "config_id": "ett2__T__short", + "leaderboard_key": "ett2/15T/short", + "dataset": "ett2/15T", + "term": "short", + "freq": "15T", + "prediction_length": 48, + "seasonality": 96, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7618250880337474, + "wql": 0.093929612604377 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0737319822496911, + "wql": 0.130385783783522, + "wsql_by_level": [ + 0.06934209919484559, + 0.10848057556039696, + 0.13658498545970746, + 0.15544592915106897, + 0.1658980801112388, + 0.16587477607827075, + 0.15540730296691582, + 0.13138010209399686, + 0.08505820343525682 + ], + "n_valid_labels": 336, + "n_masked_labels": 0, + "mae_median": 2.6472144282999492, + "n_mase_elements": 336, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.4094206125725894, + "wql": 1.3881222350260836 + } + }, + { + "config_id": "ett2__T__medium", + "leaderboard_key": "ett2/15T/medium", + "dataset": "ett2/15T", + "term": "medium", + "freq": "15T", + "prediction_length": 480, + "seasonality": 96, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9027189688220486, + "wql": 0.13649095157039726 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.799958181325761, + "wql": 0.09573880076472298, + "wsql_by_level": [ + 0.06269214470903792, + 0.095600181598384, + 0.11412303673673872, + 0.12252168832126892, + 0.12207854944855649, + 0.11439013503119215, + 0.10009235002168698, + 0.07879199148010096, + 0.051359129535540705 + ], + "n_valid_labels": 3360, + "n_masked_labels": 0, + "mae_median": 1.8578276965999976, + "n_mase_elements": 3360, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8861652507087788, + "wql": 0.7014296527586611 + } + }, + { + "config_id": "ett2__T__long", + "leaderboard_key": "ett2/15T/long", + "dataset": "ett2/15T", + "term": "long", + "freq": "15T", + "prediction_length": 720, + "seasonality": 96, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0565955316162643, + "wql": 0.16755935574924186 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0030263940935524, + "wql": 0.12492839180900105, + "wsql_by_level": [ + 0.08592212370846147, + 0.12597294020723188, + 0.15080645752280455, + 0.16293226712195075, + 0.16117027520234187, + 0.1481568937462754, + 0.12605435764158987, + 0.098094904650345, + 0.0652453064800088 + ], + "n_valid_labels": 5040, + "n_masked_labels": 0, + "mae_median": 2.430768441996308, + "n_mase_elements": 5040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9493002422215739, + "wql": 0.7455769404840666 + } + }, + { + "config_id": "ett2__H__short", + "leaderboard_key": "ett2/H/short", + "dataset": "ett2/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9915624508458626, + "wql": 0.11931409133707109 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6987818438301888, + "wql": 0.07562003654315357, + "wsql_by_level": [ + 0.05247003505676733, + 0.0787881618461473, + 0.09253294128471069, + 0.09762425280943178, + 0.0951900267725614, + 0.08551704261445367, + 0.07248493883987453, + 0.06110230438230066, + 0.04487062528213472 + ], + "n_valid_labels": 336, + "n_masked_labels": 0, + "mae_median": 5.836305375610079, + "n_mase_elements": 336, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.704728021148931, + "wql": 0.6337896529716796 + } + }, + { + "config_id": "ett2__H__medium", + "leaderboard_key": "ett2/H/medium", + "dataset": "ett2/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 2.649073318865916, + "wql": 0.345818716053239 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 2.6736907406411743, + "wql": 0.25790796422156903, + "wsql_by_level": [ + 0.1036511505665972, + 0.18574653090801851, + 0.257574022371238, + 0.31471507547067445, + 0.3534612256188364, + 0.35907786840174266, + 0.3290699996016567, + 0.2620609666608994, + 0.15581483839445762 + ], + "n_valid_labels": 3360, + "n_masked_labels": 0, + "mae_median": 20.103528779727363, + "n_mase_elements": 3360, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.009292842746156, + "wql": 0.7457894909940732 + } + }, + { + "config_id": "ett2__H__long", + "leaderboard_key": "ett2/H/long", + "dataset": "ett2/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 3.171779953228176, + "wql": 0.3702966971424018 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 3.2140068284082, + "wql": 0.3552587181208463, + "wsql_by_level": [ + 0.290650714673199, + 0.38957057586726596, + 0.43649026806695834, + 0.4535612785648727, + 0.4455852960585172, + 0.41114172607792265, + 0.35202695136031276, + 0.26692567542151474, + 0.15137597699705369 + ], + "n_valid_labels": 5040, + "n_masked_labels": 0, + "mae_median": 25.142941778599624, + "n_mase_elements": 5040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.0133133054003467, + "wql": 0.9593893784697397 + } + }, + { + "config_id": "ett2__D__short", + "leaderboard_key": "ett2/D/short", + "dataset": "ett2/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 4.704440132303346, + "wql": 0.31867490583739955 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 4.751074902834004, + "wql": 0.3298818251619046, + "wsql_by_level": [ + 0.30129480486943344, + 0.39933772631812803, + 0.43269699671141826, + 0.43247356887242455, + 0.40765313548218873, + 0.36057625205380156, + 0.29617609416420193, + 0.21621757269651698, + 0.12251027528902762 + ], + "n_valid_labels": 210, + "n_masked_labels": 0, + "mae_median": 551.2479079019456, + "n_mase_elements": 210, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.0099129267711235, + "wql": 1.0351672476220117 + } + }, + { + "config_id": "ett2__W__short", + "leaderboard_key": "ett2/W/short", + "dataset": "ett2/W", + "term": "short", + "freq": "W-THU", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.7680609986327813, + "wql": 0.21133928538207686 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.634533010924636, + "wql": 0.17327457890773973, + "wsql_by_level": [ + 0.10244889660711048, + 0.1739650674861126, + 0.20863041147092048, + 0.22344662310907615, + 0.2233719030297617, + 0.20833838732893945, + 0.1754920600983204, + 0.1430265456444586, + 0.10075131539495742 + ], + "n_valid_labels": 56, + "n_masked_labels": 0, + "mae_median": 2173.970405169896, + "n_mase_elements": 56, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9244777257055041, + "wql": 0.8198881651108049 + } + }, + { + "config_id": "jena_weather__T__short", + "leaderboard_key": "jena_weather/10T/short", + "dataset": "jena_weather/10T", + "term": "short", + "freq": "10T", + "prediction_length": 48, + "seasonality": 144, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7621672521709891, + "wql": 0.1366740261223883 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.4119917212381169, + "wql": 0.01820400914181904, + "wsql_by_level": [ + 0.006622229855916799, + 0.01186380404361966, + 0.015629473406076205, + 0.01878319506614101, + 0.02161955034140289, + 0.02330258470955096, + 0.024100882092288393, + 0.02287181992862729, + 0.019042542832748144 + ], + "n_valid_labels": 1008, + "n_masked_labels": 0, + "mae_median": 3.4069037577580836, + "n_mase_elements": 1008, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.5405529036633133, + "wql": 0.13319289449714306 + } + }, + { + "config_id": "jena_weather__T__medium", + "leaderboard_key": "jena_weather/10T/medium", + "dataset": "jena_weather/10T", + "term": "medium", + "freq": "10T", + "prediction_length": 480, + "seasonality": 144, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9778443284819783, + "wql": 0.22790411536869984 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8067262722910383, + "wql": 0.08324929715290008, + "wsql_by_level": [ + 0.02364052141777211, + 0.04991262484969891, + 0.07338212255018833, + 0.09058610295337838, + 0.10221742952164968, + 0.10884575732243369, + 0.10901021167953139, + 0.10282580614120686, + 0.08882309794024147 + ], + "n_valid_labels": 10080, + "n_masked_labels": 0, + "mae_median": 17.28649724634283, + "n_mase_elements": 10080, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8250048078137483, + "wql": 0.3652821144463347 + } + }, + { + "config_id": "jena_weather__T__long", + "leaderboard_key": "jena_weather/10T/long", + "dataset": "jena_weather/10T", + "term": "long", + "freq": "10T", + "prediction_length": 720, + "seasonality": 144, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9055523182794231, + "wql": 0.2428907683297211 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7052898078469829, + "wql": 0.07738331415402284, + "wsql_by_level": [ + 0.026584502844608615, + 0.051641596762053855, + 0.07153540674237926, + 0.08594206249016038, + 0.09518414497262774, + 0.09824765239278928, + 0.09719639457813395, + 0.09138349688415241, + 0.07873456971930017 + ], + "n_valid_labels": 15120, + "n_masked_labels": 0, + "mae_median": 16.272123342823413, + "n_mase_elements": 15120, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7788504248844009, + "wql": 0.3185930642245571 + } + }, + { + "config_id": "jena_weather__H__short", + "leaderboard_key": "jena_weather/H/short", + "dataset": "jena_weather/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7591774901189448, + "wql": 0.1835169108215369 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.500176974031497, + "wql": 0.054404868207301366, + "wsql_by_level": [ + 0.020683537169099746, + 0.04274914692137085, + 0.056648230080553204, + 0.064004675636956, + 0.06587048629976953, + 0.06575842523641581, + 0.06394255164108041, + 0.06055351108590874, + 0.049433249794557974 + ], + "n_valid_labels": 1008, + "n_masked_labels": 0, + "mae_median": 11.006842840829723, + "n_mase_elements": 1008, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6588406275759459, + "wql": 0.2964569748027635 + } + }, + { + "config_id": "jena_weather__H__medium", + "leaderboard_key": "jena_weather/H/medium", + "dataset": "jena_weather/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0707310989927863, + "wql": 0.3640989806826866 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8119335560801684, + "wql": 0.09019666207211911, + "wsql_by_level": [ + 0.04159197017298657, + 0.07157008703413187, + 0.08951669077075515, + 0.09962163122106811, + 0.10453142114876973, + 0.10775250495820864, + 0.10777564727398346, + 0.10278285842265447, + 0.08662714764651398 + ], + "n_valid_labels": 10080, + "n_masked_labels": 0, + "mae_median": 18.00503030815002, + "n_mase_elements": 10080, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7582982850165992, + "wql": 0.24772566488101702 + } + }, + { + "config_id": "jena_weather__H__long", + "leaderboard_key": "jena_weather/H/long", + "dataset": "jena_weather/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.4925574952113163, + "wql": 0.44387827099252614 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9833486597904604, + "wql": 0.12008694289649931, + "wsql_by_level": [ + 0.05929449925165726, + 0.10994764132585232, + 0.1361785918527056, + 0.14665530477783373, + 0.14602799088255233, + 0.1408876816887318, + 0.13111894511881333, + 0.11645446186153352, + 0.09421736930881396 + ], + "n_valid_labels": 15120, + "n_masked_labels": 0, + "mae_median": 25.45341921426698, + "n_mase_elements": 15120, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6588346934341969, + "wql": 0.27054026012127386 + } + }, + { + "config_id": "jena_weather__D__short", + "leaderboard_key": "jena_weather/D/short", + "dataset": "jena_weather/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.8578467510262653, + "wql": 0.23138296558762514 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.4391516993446412, + "wql": 0.11167748631905977, + "wsql_by_level": [ + 0.057661874062447015, + 0.10033667109586375, + 0.1248824352098661, + 0.13684695879468983, + 0.14071788204896363, + 0.1369312955343622, + 0.12674995081592735, + 0.10656033189627527, + 0.07440997741314269 + ], + "n_valid_labels": 630, + "n_masked_labels": 0, + "mae_median": 24.527840207746376, + "n_mase_elements": 630, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7746342364081757, + "wql": 0.48265215218173574 + } + }, + { + "config_id": "bitbrains_fast_storage__T__short", + "leaderboard_key": "bitbrains_fast_storage/5T/short", + "dataset": "bitbrains_fast_storage/5T", + "term": "short", + "freq": "5T", + "prediction_length": 48, + "seasonality": 288, + "n_variates": 2, + "n_instances": 1250, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.9726733005020567, + "wql": 1.8982594024982165 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1250, + "instances": 1250, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0564888773381853, + "wql": 0.4665399606034922, + "wsql_by_level": [ + 0.19506977056569585, + 0.3318585393866335, + 0.4299931565381228, + 0.5018622569698423, + 0.5577679852918329, + 0.5942073371065192, + 0.5994210758052967, + 0.5538332451023283, + 0.4348462786651583 + ], + "n_valid_labels": 107692, + "n_masked_labels": 12308, + "mae_median": 163.856146755481, + "n_mase_elements": 104420, + "n_seasonal_error_zero": 56, + "n_seasonal_error_nan": 52 + }, + "relative": { + "mase": 0.5355620097201613, + "wql": 0.24577250084445743 + } + }, + { + "config_id": "bitbrains_fast_storage__T__medium", + "leaderboard_key": "bitbrains_fast_storage/5T/medium", + "dataset": "bitbrains_fast_storage/5T", + "term": "medium", + "freq": "5T", + "prediction_length": 480, + "seasonality": 288, + "n_variates": 2, + "n_instances": 1250, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.332305698225943, + "wql": 0.7965658755181099 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1250, + "instances": 1250, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.1065106940753378, + "wql": 0.688163441946454, + "wsql_by_level": [ + 0.5525156662819343, + 0.914693315512023, + 0.9672172513428384, + 0.921172971534267, + 0.8338514603351116, + 0.7195032801736626, + 0.5863792884871317, + 0.4352307989403374, + 0.2629069449107795 + ], + "n_valid_labels": 1151890, + "n_masked_labels": 48110, + "mae_median": 518.2848853742898, + "n_mase_elements": 1112970, + "n_seasonal_error_zero": 58, + "n_seasonal_error_nan": 66 + }, + "relative": { + "mase": 0.8305231265982974, + "wql": 0.8639127824787275 + } + }, + { + "config_id": "bitbrains_fast_storage__T__long", + "leaderboard_key": "bitbrains_fast_storage/5T/long", + "dataset": "bitbrains_fast_storage/5T", + "term": "long", + "freq": "5T", + "prediction_length": 720, + "seasonality": 288, + "n_variates": 2, + "n_instances": 1250, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.5068539886984111, + "wql": 0.6979053733746295 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1250, + "instances": 1250, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.2537698373489332, + "wql": 0.5065267576509979, + "wsql_by_level": [ + 0.3602692953375754, + 0.5734407751080007, + 0.6460008907725583, + 0.6609441967665627, + 0.6370915942637823, + 0.5757873561289084, + 0.49152362048322196, + 0.37935090114764447, + 0.23433218885072762 + ], + "n_valid_labels": 1732080, + "n_masked_labels": 67920, + "mae_median": 465.0871464367486, + "n_mase_elements": 1677544, + "n_seasonal_error_zero": 58, + "n_seasonal_error_nan": 66 + }, + "relative": { + "mase": 0.8320446750331221, + "wql": 0.7257814267882111 + } + }, + { + "config_id": "bitbrains_fast_storage__H__short", + "leaderboard_key": "bitbrains_fast_storage/H/short", + "dataset": "bitbrains_fast_storage/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 2, + "n_instances": 1250, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.5571822067903167, + "wql": 0.6231221387021137 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1250, + "instances": 1250, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.3585012394188047, + "wql": 0.48609651112196534, + "wsql_by_level": [ + 0.34944529619179626, + 0.5649858855449645, + 0.6433627421603844, + 0.6487725396699244, + 0.6074467401072651, + 0.5379087384815439, + 0.45367697149920766, + 0.3515455287698311, + 0.2177241576727711 + ], + "n_valid_labels": 116442, + "n_masked_labels": 3558, + "mae_median": 428.86045090538, + "n_mase_elements": 112610, + "n_seasonal_error_zero": 58, + "n_seasonal_error_nan": 66 + }, + "relative": { + "mase": 0.8724099424555873, + "wql": 0.7800982839968488 + } + }, + { + "config_id": "bitbrains_rnd__T__short", + "leaderboard_key": "bitbrains_rnd/5T/short", + "dataset": "bitbrains_rnd/5T", + "term": "short", + "freq": "5T", + "prediction_length": 48, + "seasonality": 288, + "n_variates": 2, + "n_instances": 500, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.8369702659182979, + "wql": 0.895586111036325 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 500, + "instances": 500, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.5533313180375549, + "wql": 0.21833769136382022, + "wsql_by_level": [ + 0.11489732854351399, + 0.17275280366934948, + 0.2105406849350623, + 0.236692925407826, + 0.2485953238273328, + 0.2556642323952921, + 0.25640107962889364, + 0.25049401665568055, + 0.21900082721143121 + ], + "n_valid_labels": 46368, + "n_masked_labels": 1632, + "mae_median": 133.2164183966901, + "n_mase_elements": 45888, + "n_seasonal_error_zero": 10, + "n_seasonal_error_nan": 34 + }, + "relative": { + "mase": 0.6611122767072936, + "wql": 0.24379307436017666 + } + }, + { + "config_id": "bitbrains_rnd__T__medium", + "leaderboard_key": "bitbrains_rnd/5T/medium", + "dataset": "bitbrains_rnd/5T", + "term": "medium", + "freq": "5T", + "prediction_length": 480, + "seasonality": 288, + "n_variates": 2, + "n_instances": 500, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9740075110165132, + "wql": 1.1044931903333195 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 500, + "instances": 500, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8187799276759826, + "wql": 0.8878001636923963, + "wsql_by_level": [ + 0.3698941999943222, + 0.7431750732033421, + 0.9251349786787509, + 1.0178974703956913, + 1.0593461457997955, + 1.059275534547999, + 1.0222563089462533, + 0.9518502022042916, + 0.8413715594611211 + ], + "n_valid_labels": 455110, + "n_masked_labels": 24890, + "mae_median": 318.1412552923275, + "n_mase_elements": 441864, + "n_seasonal_error_zero": 10, + "n_seasonal_error_nan": 54 + }, + "relative": { + "mase": 0.8406299935217862, + "wql": 0.8038077296107834 + } + }, + { + "config_id": "bitbrains_rnd__T__long", + "leaderboard_key": "bitbrains_rnd/5T/long", + "dataset": "bitbrains_rnd/5T", + "term": "long", + "freq": "5T", + "prediction_length": 720, + "seasonality": 288, + "n_variates": 2, + "n_instances": 500, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.1660081104198932, + "wql": 0.9977535818816068 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 500, + "instances": 500, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9640281160792594, + "wql": 0.745914154932523, + "wsql_by_level": [ + 0.280850810290739, + 0.4415437404235254, + 0.5788870245217714, + 0.7052010364937698, + 0.8200277507224712, + 0.9272113507725408, + 1.012341565475448, + 1.0536946838892534, + 0.8934694318031887 + ], + "n_valid_labels": 684238, + "n_masked_labels": 35762, + "mae_median": 268.25053104350155, + "n_mase_elements": 657984, + "n_seasonal_error_zero": 12, + "n_seasonal_error_nan": 64 + }, + "relative": { + "mase": 0.8267765099267634, + "wql": 0.7475935626568695 + } + }, + { + "config_id": "bitbrains_rnd__H__short", + "leaderboard_key": "bitbrains_rnd/H/short", + "dataset": "bitbrains_rnd/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 2, + "n_instances": 500, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.1175347302132743, + "wql": 0.9314629241561541 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 500, + "instances": 500, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9132105198149795, + "wql": 0.6164160838285433, + "wsql_by_level": [ + 0.16704979518520705, + 0.32786365940179435, + 0.5061280734403805, + 0.6585618773113322, + 0.787533135184566, + 0.8489421548428817, + 0.8429434990763429, + 0.7824539535551864, + 0.626268606459199 + ], + "n_valid_labels": 46216, + "n_masked_labels": 1784, + "mae_median": 255.11100867263835, + "n_mase_elements": 44928, + "n_seasonal_error_zero": 10, + "n_seasonal_error_nan": 54 + }, + "relative": { + "mase": 0.8171652254965706, + "wql": 0.6617720017004186 + } + }, + { + "config_id": "bizitobs_application__S__short", + "leaderboard_key": "bizitobs_application/10S/short", + "dataset": "bizitobs_application", + "term": "short", + "freq": "10S", + "prediction_length": 60, + "seasonality": 360, + "n_variates": 2, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.3935671590031806, + "wql": 0.01840457246049758 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.5361255883671379, + "wql": 0.009643841352176313, + "wsql_by_level": [ + 0.005733874686755171, + 0.009214441219021216, + 0.011467951613715402, + 0.01265672542945329, + 0.012941322124945427, + 0.01229412316123507, + 0.010518202712377623, + 0.007728085036778579, + 0.004239846185305042 + ], + "n_valid_labels": 120, + "n_masked_labels": 0, + "mae_median": 334.8618872642517, + "n_mase_elements": 120, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.3847145685828509, + "wql": 0.5239915989830923 + } + }, + { + "config_id": "bizitobs_application__S__medium", + "leaderboard_key": "bizitobs_application/10S/medium", + "dataset": "bizitobs_application", + "term": "medium", + "freq": "10S", + "prediction_length": 600, + "seasonality": 360, + "n_variates": 2, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9183336447716528, + "wql": 0.013742470259025481 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6697628961082668, + "wql": 0.008980656796688464, + "wsql_by_level": [ + 0.005330938922091888, + 0.008042858093108847, + 0.009914181526837373, + 0.01104596325602783, + 0.011535904919156943, + 0.01125435148428508, + 0.010209930510673829, + 0.00829921489978141, + 0.0051925675582329784 + ], + "n_valid_labels": 1200, + "n_masked_labels": 0, + "mae_median": 276.17080470720924, + "n_mase_elements": 1200, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7293241404378753, + "wql": 0.6534965422821521 + } + }, + { + "config_id": "bizitobs_application__S__long", + "leaderboard_key": "bizitobs_application/10S/long", + "dataset": "bizitobs_application", + "term": "long", + "freq": "10S", + "prediction_length": 900, + "seasonality": 360, + "n_variates": 2, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7487259254586917, + "wql": 0.012942679940654697 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7067958588583219, + "wql": 0.00936884931372982, + "wsql_by_level": [ + 0.005631156069909842, + 0.008796057298399567, + 0.010752949093895682, + 0.01176418544997009, + 0.011913481663760484, + 0.01144545348364903, + 0.010320845530495913, + 0.00838245509469587, + 0.005313060138791902 + ], + "n_valid_labels": 1800, + "n_masked_labels": 0, + "mae_median": 290.2763890224033, + "n_mase_elements": 1800, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.943998110423808, + "wql": 0.7238724403823822 + } + }, + { + "config_id": "bizitobs_service__S__short", + "leaderboard_key": "bizitobs_service/10S/short", + "dataset": "bizitobs_service", + "term": "short", + "freq": "10S", + "prediction_length": 60, + "seasonality": 360, + "n_variates": 2, + "n_instances": 21, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0559084960397855, + "wql": 0.025515037101462117 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 21, + "instances": 21, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.5073638001113749, + "wql": 0.00900106417445603, + "wsql_by_level": [ + 0.005558586866439315, + 0.008747167533281473, + 0.010792879464750596, + 0.011843791993980056, + 0.012010056136612277, + 0.011371662745670068, + 0.009830443159820464, + 0.007217408684306281, + 0.003637580985243757 + ], + "n_valid_labels": 2520, + "n_masked_labels": 0, + "mae_median": 16.10402358647377, + "n_mase_elements": 2520, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.4804997800607317, + "wql": 0.3527748808932844 + } + }, + { + "config_id": "bizitobs_service__S__medium", + "leaderboard_key": "bizitobs_service/10S/medium", + "dataset": "bizitobs_service", + "term": "medium", + "freq": "10S", + "prediction_length": 600, + "seasonality": 360, + "n_variates": 2, + "n_instances": 21, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9546641394188339, + "wql": 0.023513421962609537 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 21, + "instances": 21, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6730393362439785, + "wql": 0.009794274110657844, + "wsql_by_level": [ + 0.006094114158094369, + 0.009232874011964279, + 0.011185325899884692, + 0.012223013674078763, + 0.012465839527039545, + 0.011978501065002603, + 0.010760760907759997, + 0.008721101881154833, + 0.005486935870941528 + ], + "n_valid_labels": 25200, + "n_masked_labels": 0, + "mae_median": 15.72331048632898, + "n_mase_elements": 25200, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7050011710439875, + "wql": 0.41653971617710334 + } + }, + { + "config_id": "bizitobs_service__S__long", + "leaderboard_key": "bizitobs_service/10S/long", + "dataset": "bizitobs_service", + "term": "long", + "freq": "10S", + "prediction_length": 900, + "seasonality": 360, + "n_variates": 2, + "n_instances": 21, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.8316933390369606, + "wql": 0.023678985220657325 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 21, + "instances": 21, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7390123938224726, + "wql": 0.010531845890164962, + "wsql_by_level": [ + 0.006383249298614066, + 0.009864785967957233, + 0.012008653597603508, + 0.013169747904611243, + 0.013468660212741398, + 0.013005218376279899, + 0.01165396372387063, + 0.009300078919780642, + 0.005932255010026046 + ], + "n_valid_labels": 37800, + "n_masked_labels": 0, + "mae_median": 17.210727057569617, + "n_mase_elements": 37800, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.888563559590599, + "wql": 0.4447760658669223 + } + }, + { + "config_id": "bizitobs_l2c__T__short", + "leaderboard_key": "bizitobs_l2c/5T/short", + "dataset": "bizitobs_l2c/5T", + "term": "short", + "freq": "5T", + "prediction_length": 48, + "seasonality": 288, + "n_variates": 7, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7721410982041648, + "wql": 0.22094461659341424 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.17719682949533103, + "wql": 0.05196935328989167, + "wsql_by_level": [ + 0.03673161648408669, + 0.054512367841345874, + 0.06394689379394639, + 0.06690333390467752, + 0.06513516044849195, + 0.06030893066436873, + 0.05122422444721566, + 0.040440560786911044, + 0.02852109123798114 + ], + "n_valid_labels": 336, + "n_masked_labels": 0, + "mae_median": 1.6732738145760127, + "n_mase_elements": 336, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.22948762850138787, + "wql": 0.2352143903353232 + } + }, + { + "config_id": "bizitobs_l2c__T__medium", + "leaderboard_key": "bizitobs_l2c/5T/medium", + "dataset": "bizitobs_l2c/5T", + "term": "medium", + "freq": "5T", + "prediction_length": 480, + "seasonality": 288, + "n_variates": 7, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.4416925389331963, + "wql": 0.47091183801289255 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.46346546475350414, + "wql": 0.15159845640223224, + "wsql_by_level": [ + 0.12127430819567343, + 0.16607473783211424, + 0.18719243602577904, + 0.18619616428412292, + 0.179147632080042, + 0.17049806728655326, + 0.15113113711271856, + 0.11788249457268349, + 0.08498913023040323 + ], + "n_valid_labels": 3360, + "n_masked_labels": 0, + "mae_median": 3.9870425178181557, + "n_mase_elements": 3360, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.3214731659057159, + "wql": 0.3219253460306551 + } + }, + { + "config_id": "bizitobs_l2c__T__long", + "leaderboard_key": "bizitobs_l2c/5T/long", + "dataset": "bizitobs_l2c/5T", + "term": "long", + "freq": "5T", + "prediction_length": 720, + "seasonality": 288, + "n_variates": 7, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.6820288964143004, + "wql": 0.6755692567838184 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7315768386440953, + "wql": 0.27624994389467344, + "wsql_by_level": [ + 0.14370013271124615, + 0.22908316824397407, + 0.2899181908242404, + 0.3328947237403348, + 0.365667060367179, + 0.3719921393365034, + 0.3498308536582773, + 0.26617716044159706, + 0.13698606572870853 + ], + "n_valid_labels": 5040, + "n_masked_labels": 0, + "mae_median": 6.689369549773752, + "n_mase_elements": 5040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.43493714061848116, + "wql": 0.40891432095328933 + } + }, + { + "config_id": "bizitobs_l2c__H__short", + "leaderboard_key": "bizitobs_l2c/H/short", + "dataset": "bizitobs_l2c/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.5845833438972332, + "wql": 0.5573763030242874 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7281863995250054, + "wql": 0.21887555185281887, + "wsql_by_level": [ + 0.12935013034640708, + 0.22625016246031043, + 0.29584627028899346, + 0.3184465576338112, + 0.31609470499419845, + 0.276097796463806, + 0.20090938838269853, + 0.12853732789351696, + 0.07834762821162769 + ], + "n_valid_labels": 336, + "n_masked_labels": 0, + "mae_median": 6.613412265089297, + "n_mase_elements": 336, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.4595443984246696, + "wql": 0.39268901577841475 + } + }, + { + "config_id": "bizitobs_l2c__H__medium", + "leaderboard_key": "bizitobs_l2c/H/medium", + "dataset": "bizitobs_l2c/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.6159633796006725, + "wql": 1.1167911109559348 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.3531724130014339, + "wql": 0.21283566933621648, + "wsql_by_level": [ + 0.1178209057055767, + 0.18198599997738826, + 0.21772318368274352, + 0.24125997432591903, + 0.25393724300506315, + 0.25322518151645723, + 0.24497799558765035, + 0.22755688913576316, + 0.17703365108938712 + ], + "n_valid_labels": 3360, + "n_masked_labels": 0, + "mae_median": 3.47557669572, + "n_mase_elements": 3360, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.2185522379156314, + "wql": 0.19057786836612306 + } + }, + { + "config_id": "bizitobs_l2c__H__long", + "leaderboard_key": "bizitobs_l2c/H/long", + "dataset": "bizitobs_l2c/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.280223980485366, + "wql": 1.0134048622912797 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.42744435821408167, + "wql": 0.21406973407355634, + "wsql_by_level": [ + 0.11740421799454576, + 0.1881229771862347, + 0.2314492001948075, + 0.2541587793142006, + 0.2605547377290509, + 0.2542271452306906, + 0.24123954770324577, + 0.2160806119193573, + 0.16339038938987388 + ], + "n_valid_labels": 5040, + "n_masked_labels": 0, + "mae_median": 3.9366751333816894, + "n_mase_elements": 5040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.33388248051097, + "wql": 0.2112381162150246 + } + } + ], + "checkpoint_sha256": "90199d09666c1653819ef17813f69fc4014fca075f99cc3766d24f457b50ca79", + "inference_seconds": 362.1720542849507 +} diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/zero_mass.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/zero_mass.py new file mode 100644 index 0000000000000000000000000000000000000000..7e9c7067950c67da130e2c2538ffb42f34537402 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S063/zero_mass.py @@ -0,0 +1,12 @@ +"""Fixed zero-mass projection from the supplied history only.""" +import numpy as np + +def project(ctx,q,threshold=.4): + finite=np.isfinite(ctx);n=finite.sum(-1).clip(min=1) + x=np.where(finite,ctx,0.) + mean=x.sum(-1)/n + scale=np.sqrt((np.where(finite,ctx-mean[...,None],0.)**2).sum(-1)/n) + zero=((ctx==0)&finite).sum(-1) + active=((ctx>=0)|~finite).all(-1)&(zero>=4)&(zero/n>=.1) + cutoff=np.where(active,threshold*scale,0.) + return np.where((q>=0)&(q=0)|~np.isfinite(ctx)).all(-1) + for i in range(b): + x=ctx[i,-512:].astype(np.float64) + if len(x)<8 or not np.isfinite(x[-1]):continue + diff=np.diff(x) + if np.isfinite(diff).sum()<8 or not np.isfinite(diff[-8:]).any():continue + ratio=np.nanmean(diff*diff)/(np.nanvar(x)+1e-12) + weight=float(np.clip(1-ratio/.5,0,.95)) + bias[i]=weight*(x[-1]+np.nanmedian(diff[-8:])-quant[i,4,0]) + out=quant+bias[:,None,None]*np.exp(-np.arange(h)/tau)[None,None,:] + out=np.where(positive[:,None,None],np.maximum(0,out),out) + return out.astype(np.float32) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/gate_frequency.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/gate_frequency.py new file mode 100644 index 0000000000000000000000000000000000000000..bdeffd8b2d20972fa082c6875d5e16e0a9e21f1f --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/gate_frequency.py @@ -0,0 +1,14 @@ +"""Frequency mapping copied verbatim from our own E80 model.""" +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/gate_normalization.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/gate_normalization.py new file mode 100644 index 0000000000000000000000000000000000000000..f1cfec8685b97bc4c979e1daf9c9a3013a136d6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/gate_normalization.py @@ -0,0 +1,21 @@ +"""Canonical normalization copied from our own E79 model; no learned statistics.""" +import torch + +def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/infer.sh b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/infer.sh new file mode 100644 index 0000000000000000000000000000000000000000..725d90e5f2b609f06c4859c24b159192052d0b14 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/infer.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +export NUMPY_MADVISE_HUGEPAGE=0 +export OMP_NUM_THREADS=4 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=4 +exec python3 "$(dirname "$(readlink -f "$0")")/predict.py" "$1" "$2" diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/model.py new file mode 100644 index 0000000000000000000000000000000000000000..dedcdff4698028a8ba655865f8425d0dc3ef0dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/model.py @@ -0,0 +1,204 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/model0.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/model0.py new file mode 100644 index 0000000000000000000000000000000000000000..0fb76d7fe91edd7ea32a5e4cf8ea092b570edcfe --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/model0.py @@ -0,0 +1,279 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + + +def centered_seasonal_difference(z, valid, periods, horizon): + b, c = z.shape + time = torch.arange(horizon, device=z.device)[None, :] + sums = F.pad((z * valid).cumsum(-1), (1, 0)) + counts = F.pad(valid.float().cumsum(-1), (1, 0)) + deltas, extras, dispersion, width_deltas = [], [], [], [] + for j in range(2): + period = periods[:, j:j+1].clamp(min=1) + anchor = c - period + time % period + centered, masks = [], [] + for cycle in range(16): + end = (c - cycle * period).clamp(min=0, max=c) + start = (c - (cycle + 1) * period).clamp(min=0, max=c) + count = counts.gather(1, end) - counts.gather(1, start) + mean = (sums.gather(1, end) - sums.gather(1, start)) / count.clamp(min=1) + index = anchor - cycle * period + safe = index.clamp(min=0, max=c-1) + present = (index >= 0) & valid.gather(1, safe) + centered.append(z.gather(1, safe) - mean) + masks.append(present) + values = torch.stack(centered) + seen = torch.stack(masks) + n4 = seen[:4].sum(0) + n16 = seen.sum(0) + mean4 = (values[:4] * seen[:4]).sum(0) / n4.clamp(min=1) + mean16 = (values * seen).sum(0) / n16.clamp(min=1) + active = (period >= 2) & (n4 >= 2) & (n16 >= 8) + delta = torch.where(active, mean16 - mean4, 0.) + support = torch.where(active, n16.float() / 16, 0.) + deltas.append(delta) + extras.extend([delta, support]) + variance4 = (((values[:4] - mean4).square() * seen[:4]).sum(0) / (n4 - 1).clamp(min=1)) + variance16 = (((values - mean16).square() * seen).sum(0) / (n16 - 1).clamp(min=1)) + width_deltas.append(torch.where(active, variance16.sqrt().log1p() - math.log(2.), 0.)) + dispersion.extend([torch.where(active, variance4.sqrt().log1p(), 0.), + torch.where(active, variance16.sqrt().log1p(), 0.)]) + return torch.stack(deltas, -1), torch.stack(extras, -1), torch.stack(dispersion, -1), torch.stack(width_deltas, -1) + + + +def seasonal_width_multiplier(raw, delta): + return ((raw.float().tanh() * delta).sum(-1).clamp(-math.log(4.), math.log(4.))).exp() + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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,long_seasonal_features=True,seasonal_dispersion_features=True,seasonal_width_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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,long_seasonal_features=long_seasonal_features,seasonal_dispersion_features=seasonal_dispersion_features,seasonal_width_features=seasonal_width_features) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + self.long_query=nn.Linear(patch*4,d,bias=False) if long_seasonal_features else None + self.long_head=nn.Linear(d,patch*2) if long_seasonal_features else None + if long_seasonal_features: + nn.init.zeros_(self.long_query.weight) + nn.init.zeros_(self.long_head.weight);nn.init.zeros_(self.long_head.bias) + assert long_seasonal_features or not seasonal_dispersion_features + self.dispersion_query=nn.Linear(patch*4,d,bias=False) if seasonal_dispersion_features else None + if self.dispersion_query is not None:nn.init.zeros_(self.dispersion_query.weight) + assert seasonal_dispersion_features or not seasonal_width_features + self.width_head=nn.Linear(d,patch*2) if seasonal_width_features else None + if self.width_head is not None: + nn.init.zeros_(self.width_head.weight);nn.init.zeros_(self.width_head.bias) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + if self.long_query is not None:long_delta,long_extra,dispersion_extra,width_delta=centered_seasonal_difference(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + hidden=self.norm(q) + out=self.head(hidden).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + if self.long_head is not None: + gates=self.long_head(hidden).view(b,h,2).float().tanh() + median=median+(gates*long_delta).sum(-1) + widths=F.softplus(out[:,:,10:]).clamp(max=20) + if self.width_head is not None: + multiplier=seasonal_width_multiplier(self.width_head(hidden).view(b,h,2),width_delta) + widths=widths*multiplier[:,:,None] + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/model5.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/model5.py new file mode 100644 index 0000000000000000000000000000000000000000..298ee3b840cbc8b7da585ee5e47a3822d06717b0 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/model5.py @@ -0,0 +1,260 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + + +def centered_seasonal_difference(z, valid, periods, horizon): + b, c = z.shape + time = torch.arange(horizon, device=z.device)[None, :] + sums = F.pad((z * valid).cumsum(-1), (1, 0)) + counts = F.pad(valid.float().cumsum(-1), (1, 0)) + deltas, extras = [], [] + for j in range(2): + period = periods[:, j:j+1].clamp(min=1) + anchor = c - period + time % period + centered, masks = [], [] + for cycle in range(16): + end = (c - cycle * period).clamp(min=0, max=c) + start = (c - (cycle + 1) * period).clamp(min=0, max=c) + count = counts.gather(1, end) - counts.gather(1, start) + mean = (sums.gather(1, end) - sums.gather(1, start)) / count.clamp(min=1) + index = anchor - cycle * period + safe = index.clamp(min=0, max=c-1) + present = (index >= 0) & valid.gather(1, safe) + centered.append(z.gather(1, safe) - mean) + masks.append(present) + values = torch.stack(centered) + seen = torch.stack(masks) + n4 = seen[:4].sum(0) + n16 = seen.sum(0) + mean4 = (values[:4] * seen[:4]).sum(0) / n4.clamp(min=1) + mean16 = (values * seen).sum(0) / n16.clamp(min=1) + active = (period >= 2) & (n4 >= 2) & (n16 >= 8) + delta = torch.where(active, mean16 - mean4, 0.) + support = torch.where(active, n16.float() / 16, 0.) + deltas.append(delta) + extras.extend([delta, support]) + return torch.stack(deltas, -1), torch.stack(extras, -1) + + + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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,long_seasonal_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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,long_seasonal_features=long_seasonal_features) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + self.long_query=nn.Linear(patch*4,d,bias=False) if long_seasonal_features else None + self.long_head=nn.Linear(d,patch*2) if long_seasonal_features else None + if long_seasonal_features: + nn.init.zeros_(self.long_query.weight) + nn.init.zeros_(self.long_head.weight);nn.init.zeros_(self.long_head.bias) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + if self.long_query is not None:long_delta,long_extra=centered_seasonal_difference(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + hidden=self.norm(q) + out=self.head(hidden).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + if self.long_head is not None: + gates=self.long_head(hidden).view(b,h,2).float().tanh() + median=median+(gates*long_delta).sum(-1) + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..5a59e26122883727cb597a115e69133695b7696e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/predict.py @@ -0,0 +1,91 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import importlib.util +from seasonal import apply_gate +from continuity import apply_continuity +from zero_mass import project +import ts_io +from gate_model import DirectForecaster as LearnedGate, combine as gate_combine + +def load_model(checkpoint,device='cuda'): + from types import SimpleNamespace + path=Path(checkpoint);descriptor=json.loads(path.read_text());members=[] + for entry in descriptor['members']: + ck=torch.load(path.parent/entry['weights'],map_location='cpu',weights_only=False) + spec=importlib.util.spec_from_file_location('member_model_'+str(len(members)),path.parent/entry['model_code']) + module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module) + with torch.device('meta'): + model=module.DirectForecaster(**ck['config']) + model.load_state_dict(ck['model'],assign=True);model=model.to(device);model.eval();members.append(model) + assert len(members)==6 + assert descriptor["horizon_threshold"]==720 and descriptor["blend_coefficient"]==.5 + assert descriptor['gate_blend_coefficient']==.5 + gate_ck=torch.load(path.parent/descriptor['gate']['weights'],map_location='cpu',weights_only=False) + with torch.device('meta'):gate=LearnedGate(**gate_ck['config']) + gate.load_state_dict(gate_ck['model'],assign=True);gate=gate.to(device);gate.eval() + return SimpleNamespace(models=members,gate=gate,max_context=max(m.max_context for m in members),horizon_threshold=descriptor['horizon_threshold']) + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + forecasts=[] + for member in model.models: + member_ctx=ctx[:,-member.max_context:] + member_x=x[:,-member.max_context:] + rule_context=getattr(member,'rule_context',member.max_context) + rule_ctx=member_ctx[:,-rule_context:] + rule_x=member_x[:,-rule_context:] + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16): + qq,mu,scale=member(torch.cat((member_x,-member_x),0),p.repeat(2,1),h) + qq=qq*scale[:,:,None]+mu[:,:,None] + qq=(qq[:len(ids)]-qq[len(ids):].flip(-1))*.5 + recent=rule_x[:,-4096:] + positive=((recent>=0)|~torch.isfinite(recent)).all(-1) + qq=torch.where(positive[:,None,None],qq.clamp(min=0),qq) + q=qq.transpose(1,2).float().cpu().numpy() + q=apply_gate(rule_ctx[:,-4096:],p.cpu().numpy(),q) + q=project(rule_ctx,apply_continuity(rule_ctx,q)) + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + forecasts.append(q) + fourth=4 if h>=model.horizon_threshold else 3 + q=(forecasts[0]+forecasts[1]+forecasts[2]+forecasts[fourth])/4 + alternative=(forecasts[0]+forecasts[1]+forecasts[2]+forecasts[5])/4 + q=(q+alternative)/2 + # The independent four-expert gate receives exactly F0/F1/F2/F3. + gate_inputs=np.stack(forecasts[:4],axis=1).transpose(0,1,3,2).copy() + with torch.no_grad(): + expert_quantiles=torch.from_numpy(gate_inputs).to(x.device) + lengths=torch.full((len(ids),),h,device=x.device) + weights=model.gate(x,p,expert_quantiles,lengths) + gated=gate_combine(expert_quantiles,weights).transpose(1,2).cpu().numpy() + q=(q+gated)/2 + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'config.json'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/diversity.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/diversity.py new file mode 100644 index 0000000000000000000000000000000000000000..e23e13a74cf379fb4d5b57fa04bbbf4c0765c13a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/diversity.py @@ -0,0 +1,77 @@ +"""Describe fixed-pool loss reduction using completed validation metrics only.""" +import json,math,sys,time +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +from ts_io import read_prediction_file,read_truth_file +from score import config_metrics,QUANTILES +R=Path('/workspace/research');started=time.monotonic();panels=[] +declaration=json.loads((R/'gate_six_blend/declaration.json').read_text()) +member_names=['seasonal_width_transfer12k','patch8_ema6000','split_patch_ema12000','random_capacity_1024_ema96000','capacity_patch8_candidate_ema6000','random_capacity_long_seasonal_ema48000'] +folders=dict(valid_screen='evals',valid_backcast='backcast_evals',valid_backcast2='backcast2_evals',valid_backcast3='backcast3_evals') +def rounding_audit(cutoff,cfg,metric,average,recorded): + path=Path('cases')/(cfg['config_id']+'.h5') + forecasts=[read_prediction_file(R/folders[cutoff]/name/path)[1] for name in member_names] + selected=[0,1,2,4 if cfg['prediction_length']>=720 else 3] + first=forecasts[0].copy() + for index in selected[1:]:first+=forecasts[index] + first/=4 + second=forecasts[0].copy() + for index in [1,2,5]:second+=forecasts[index] + second/=4 + first=(first+second)/2 + second=read_prediction_file(R/folders[cutoff]/'ensemble_gate_refresh_ema6000'/path)[1] + rounded=(first+second)/2 + exact=(first.astype(np.float64)+second.astype(np.float64))/2 + labels,scale,_=read_truth_file(R/cutoff/'truth'/path) + rounded_metrics=config_metrics(labels,scale,rounded[:,:,4],rounded) + exact_metrics=config_metrics(labels,scale,exact[:,:,4],exact) + tolerance=1e-12*max(1,average) + assert abs(rounded_metrics[metric]-recorded)<=tolerance + assert exact_metrics[metric]<=average+tolerance + error=np.abs(rounded.astype(np.float64)-exact);valid=np.isfinite(labels) + if metric=='mase': + scales=scale.astype(np.float64)[:,:,None] + good=np.broadcast_to(np.isfinite(scales)&(scales>0),labels.shape)&valid + safe=np.where(np.isfinite(scales)&(scales>0),scales,1.) + bound=float((error[:,:,4,:]/safe)[good].mean()) + else: + denominator=float(np.abs(labels.astype(np.float64)[valid]).sum()) + bound=float(np.mean([2*max(level,1-level)*error[:,:,i,:][valid].sum()/denominator for i,level in enumerate(QUANTILES)])) + assert recorded-exact_metrics[metric]<=bound+tolerance + assert recorded-average<=bound+tolerance + return dict(exact_arithmetic_loss=exact_metrics[metric],rounded_loss=recorded, + loss_lipschitz_rounding_bound=bound,maximum_forecast_rounding=float(error.max()), + cached_rounded_metric_reproduced=True,exact_arithmetic_convexity_verified=True) +for cutoff in ['valid_screen','valid_backcast','valid_backcast2','valid_backcast3']: + a=json.loads((R/f'seasonal_six_member_blend_{cutoff}.json').read_text()) + b=json.loads((R/folders[cutoff]/'ensemble_gate_refresh_ema6000/report.json').read_text()) + assert b['checkpoint_sha256']==declaration['gate_checkpoint_sha256'] + pooled=json.loads((R/f'gate_six_blend_{cutoff}.json').read_text()) + left={row['config_id']:row for row in a['configs']};right={row['config_id']:row for row in b['configs']} + rows=[] + for row in pooled['configs']: + cid=row['config_id'];changes={} + for metric in ['mase','wql']: + average=(left[cid]['metrics'][metric]+right[cid]['metrics'][metric])/2 + actual=row['metrics'][metric] + if not math.isfinite(average) or not math.isfinite(actual):continue + gain=average-actual + changes[metric]=dict(arithmetic_mean_of_parent_losses=average,pooled_forecast_loss=actual, + absolute_reduction=gain,fractional_reduction=gain/average if average>0 else 0.) + if gain < -1e-10*max(1,average): + changes[metric]['rounding_audit']=rounding_audit(cutoff,row,metric,average,actual) + rows.append(dict(config_id=cid,term=row['term'],domain=row['domain'],metrics=changes)) + groups={} + for kind in ['term','domain']: + groups[kind]={} + for value in sorted({row[kind] for row in rows}): + selected=[row for row in rows if row[kind]==value] + groups[kind][value]={metric:sum(row['metrics'][metric]['fractional_reduction'] for row in selected if metric in row['metrics'])/sum(metric in row['metrics'] for row in selected) for metric in ['mase','wql']} + panels.append(dict(cutoff=cutoff,configurations=len(rows),groups=groups, + mean_fractional_loss_reduction={metric:sum(row['metrics'][metric]['fractional_reduction'] for row in rows if metric in row['metrics'])/sum(metric in row['metrics'] for row in rows) for metric in ['mase','wql']}, + strict_improvement_configs={metric:sum(row['metrics'].get(metric,{}).get('fractional_reduction',0)>1e-7 for row in rows) for metric in ['mase','wql']},configs=rows)) +result=dict(seconds=time.monotonic()-started,panels=panels,new_inference=False,optimizer_updates=0, + note='Descriptive validation analysis after the one fixed half-blend was selected for full replay. MASE and WQL are convex in their respective forecasts in exact arithmetic. Float32 pooling can slightly exceed that bound: every excess above1e-10*max(1,meanloss) is reproduced from cached member forecasts and checked against an explicit Lipschitz bound on measured forecast rounding. No tolerance sweep or forecast change. The reference is an arithmetic mean of parent losses, not a forecast model or benchmark score. Equal-configuration fractional reductions describe realized complementarity; they are not independent generalization evidence. No coefficients or forecast parameters are fitted.') +(R/'gate_six_blend_loss_diversity.json').write_text(json.dumps(result,indent=2)) +print(json.dumps(dict(seconds=result['seconds'],panels=[{k:v for k,v in row.items() if k not in ['configs','groups']} for row in panels]))) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/ensemble_gate_refresh6k_selection_review.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/ensemble_gate_refresh6k_selection_review.json new file mode 100644 index 0000000000000000000000000000000000000000..4ae91d6ce05424867f237d53d1433c689b0ba79f --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/ensemble_gate_refresh6k_selection_review.json @@ -0,0 +1,995 @@ +{ + "utc": "2026-10-24T01:07:25.727419+00:00", + "experiment": "E152", + "run": "ensemble_gate_refresh", + "step": 6000, + "seed": 751, + "checkpoint_sha256": "a7d0ee6866ea787f29eac043531aad3613674f159fd00b3491fd87fab8388fd1", + "expert_descriptor_sha256": "a1b4ab426901be8e1ee299eeeb3f041bac7cea3d4e59c4608824fc3d05c83e03", + "current_descriptor_sha256": "20f014ca61a9cfa4f275d9d7abfd297561ac37fddcdae9ba2ef60d3fca106cf8", + "training_loop_seconds_to_endpoint": 3001.1, + "rows": [ + { + "panel": "valid_screen", + "skill": 0.3895317981891372, + "delta_frozen": 0.0013038472113747757, + "delta_current": 0.0007980085065080189, + "evaluation_seconds": 104.56864271895029, + "groups": { + "term": { + "long": 0.4079866631952618, + "medium": 0.41258880657692587, + "short": 0.37318757798678504 + }, + "domain": { + "Econ/Fin": 0.15134004808705748, + "Energy": 0.24756263469529682, + "Healthcare": 0.49081279988705917, + "Nature": 0.44430890056162586, + "Sales": 0.34421182882527446, + "Transport": 0.47564320698580886, + "Web/CloudOps": 0.5090064800219256 + }, + "frequency": { + "A": 0.38125442600116843, + "D": 0.3764878327158627, + "H": 0.4050571340835527, + "M": 0.1178489213132371, + "Q": 0.2040508082264969, + "S": 0.42502161801476035, + "T": 0.44736533885146146, + "W": 0.24431128616312048 + }, + "variates": { + "multivariate": 0.4017889801668404, + "univariate": 0.37959208008211376 + } + }, + "comparisons": { + "frozen": { + "positive_configs": 48, + "total_configs": 97, + "group_skill_delta": { + "term": { + "long": 0.001979145934475457, + "medium": 0.0016581305764672427, + "short": 0.0008858077334963355 + }, + "domain": { + "Econ/Fin": 0.002326763326451209, + "Energy": 0.0001622814565461761, + "Healthcare": -0.004256479423524473, + "Nature": 0.0029434205001249714, + "Sales": -0.00039834293388396613, + "Transport": 0.003033568737229708, + "Web/CloudOps": 0.0015307127130606002 + }, + "frequency": { + "A": -0.0023961463980423092, + "D": 0.0043531681397361854, + "H": 0.001469259302773196, + "M": -0.008973524724004145, + "Q": -0.0020165482765339693, + "S": 0.0009938363030151942, + "T": 0.0023428943229019117, + "W": -0.005047136096300586 + }, + "variates": { + "multivariate": 0.0010980257532510196, + "univariate": 0.001473472999836578 + } + }, + "largest_regressions": [ + { + "config_id": "us_births__M__short", + "delta": -0.04546500997581182 + }, + { + "config_id": "us_births__W__short", + "delta": -0.01886523225190284 + }, + { + "config_id": "ett1__W__short", + "delta": -0.01399842375190008 + }, + { + "config_id": "m4_hourly__H__short", + "delta": -0.01244203247704223 + }, + { + "config_id": "bizitobs_l2c__H__short", + "delta": -0.011755568521799042 + }, + { + "config_id": "ett2__T__short", + "delta": -0.0113816133910154 + }, + { + "config_id": "covid_deaths__D__short", + "delta": -0.011325562493132324 + }, + { + "config_id": "ett1__D__short", + "delta": -0.007979035819571378 + } + ], + "largest_improvements": [ + { + "config_id": "m4_weekly__W__short", + "delta": 0.027156179855509 + }, + { + "config_id": "M_DENSE__H__long", + "delta": 0.019206599969448512 + }, + { + "config_id": "us_births__D__short", + "delta": 0.01594704433170646 + }, + { + "config_id": "saugeenday__D__short", + "delta": 0.012966759020383134 + }, + { + "config_id": "bizitobs_l2c__T__medium", + "delta": 0.012355667804988535 + }, + { + "config_id": "saugeenday__M__short", + "delta": 0.012137554666010741 + }, + { + "config_id": "M_DENSE__H__short", + "delta": 0.011330351977005715 + }, + { + "config_id": "electricity__H__short", + "delta": 0.01054775939191277 + } + ] + }, + "current": { + "positive_configs": 50, + "total_configs": 97, + "group_skill_delta": { + "term": { + "long": 0.0007518949582022705, + "medium": 0.0008284759606443926, + "short": 0.0008035714708022335 + }, + "domain": { + "Econ/Fin": 0.001830727725445458, + "Energy": -0.0004957162094531009, + "Healthcare": 0.00570223830204275, + "Nature": 0.0006961173101691642, + "Sales": -0.0020040875405479275, + "Transport": 0.000619236118382549, + "Web/CloudOps": 0.001350955512749663 + }, + "frequency": { + "A": -0.0009314535267384016, + "D": 0.0018952278393165045, + "H": 0.0005256723851021494, + "M": -0.0056496298266519585, + "Q": -0.0021561099495120972, + "S": 4.61708207354361e-05, + "T": 0.001795407320581477, + "W": -0.0007205222360062713 + }, + "variates": { + "multivariate": 0.00018655022602742655, + "univariate": 0.001303177684338075 + } + }, + "largest_regressions": [ + { + "config_id": "us_births__M__short", + "delta": -0.026353313245838783 + }, + { + "config_id": "ett2__T__short", + "delta": -0.02014323024911424 + }, + { + "config_id": "LOOP_SEATTLE__T__short", + "delta": -0.015608059405994412 + }, + { + "config_id": "ett1__W__short", + "delta": -0.015479939789509012 + }, + { + "config_id": "bizitobs_l2c__H__short", + "delta": -0.015158425149146115 + }, + { + "config_id": "saugeenday__W__short", + "delta": -0.014372855021653419 + }, + { + "config_id": "covid_deaths__D__short", + "delta": -0.013058005066113432 + }, + { + "config_id": "M_DENSE__D__short", + "delta": -0.01294387378332118 + } + ], + "largest_improvements": [ + { + "config_id": "m4_weekly__W__short", + "delta": 0.02361780438598793 + }, + { + "config_id": "us_births__D__short", + "delta": 0.018366121505148714 + }, + { + "config_id": "bizitobs_l2c__T__short", + "delta": 0.014197290849927602 + }, + { + "config_id": "M_DENSE__H__short", + "delta": 0.012262037315359797 + }, + { + "config_id": "saugeenday__M__short", + "delta": 0.011026616884412421 + }, + { + "config_id": "solar__T__short", + "delta": 0.010509239968234496 + }, + { + "config_id": "electricity__H__short", + "delta": 0.010250960891911687 + }, + { + "config_id": "M_DENSE__H__medium", + "delta": 0.010215725325502523 + } + ] + } + } + }, + { + "panel": "valid_backcast", + "skill": 0.3454776695706264, + "delta_frozen": -0.00018844608814816421, + "delta_current": -0.0002963984481781923, + "evaluation_seconds": 102.79379361798055, + "groups": { + "term": { + "long": 0.40528562240907895, + "medium": 0.3636030703777581, + "short": 0.31376789992934595 + }, + "domain": { + "Econ/Fin": 0.18255322929224826, + "Energy": 0.23460562763292858, + "Healthcare": 0.3991450958419892, + "Nature": 0.3846536547042607, + "Sales": 0.40786948398139855, + "Transport": 0.379669615375008, + "Web/CloudOps": 0.45825301786525063 + }, + "frequency": { + "A": 0.32698375941472213, + "D": 0.3638934438537482, + "H": 0.3788496068013374, + "M": 0.1914771840379833, + "Q": 0.23774390253181066, + "S": 0.3453845857797502, + "T": 0.34138425941056927, + "W": 0.2922259201661095 + }, + "variates": { + "multivariate": 0.36316077411183334, + "univariate": 0.3310461716131965 + } + }, + "comparisons": { + "frozen": { + "positive_configs": 46, + "total_configs": 97, + "group_skill_delta": { + "term": { + "long": -0.0019119535436493695, + "medium": -0.0004927772186985591, + "short": 0.0006985316262305696 + }, + "domain": { + "Econ/Fin": 0.002117954506798636, + "Energy": -0.00020977631158514143, + "Healthcare": -0.008290190964119315, + "Nature": 0.0033504099601329163, + "Sales": 0.00034525946352415016, + "Transport": 0.002004748328961914, + "Web/CloudOps": -0.0026318400241568396 + }, + "frequency": { + "A": -0.0047973654732119675, + "D": -0.00029556913373474103, + "H": 0.002480940428061129, + "M": 0.003999175061233706, + "Q": 0.0005021708627526156, + "S": -0.0044929448697250685, + "T": -0.00219475323413576, + "W": -0.0018771058075813807 + }, + "variates": { + "multivariate": -0.0021765061132417163, + "univariate": 0.0014792757316079985 + } + }, + "largest_regressions": [ + { + "config_id": "ett2__T__short", + "delta": -0.025440533791053377 + }, + { + "config_id": "jena_weather__T__short", + "delta": -0.021474520391312923 + }, + { + "config_id": "us_births__M__short", + "delta": -0.017970652265217435 + }, + { + "config_id": "ett2__W__short", + "delta": -0.013656608246303326 + }, + { + "config_id": "electricity__D__short", + "delta": -0.01239720383797882 + }, + { + "config_id": "covid_deaths__D__short", + "delta": -0.012170777609198269 + }, + { + "config_id": "solar__T__medium", + "delta": -0.011669472126964675 + }, + { + "config_id": "bizitobs_l2c__T__medium", + "delta": -0.010309166183636753 + } + ], + "largest_improvements": [ + { + "config_id": "saugeenday__M__short", + "delta": 0.06399735769082437 + }, + { + "config_id": "solar__H__short", + "delta": 0.032314635527553315 + }, + { + "config_id": "ett1__H__short", + "delta": 0.021353753653667207 + }, + { + "config_id": "m4_weekly__W__short", + "delta": 0.02113333006091833 + }, + { + "config_id": "saugeenday__D__short", + "delta": 0.018856209249390132 + }, + { + "config_id": "M_DENSE__H__medium", + "delta": 0.015305308597099332 + }, + { + "config_id": "bitbrains_rnd__T__short", + "delta": 0.011814513965627382 + }, + { + "config_id": "bitbrains_fast_storage__T__short", + "delta": 0.009708158834936365 + } + ] + }, + "current": { + "positive_configs": 53, + "total_configs": 97, + "group_skill_delta": { + "term": { + "long": -0.0016714249186486896, + "medium": 0.0006295118648368403, + "short": -6.981432435215762e-05 + }, + "domain": { + "Econ/Fin": 0.0025607881587276227, + "Energy": -0.0009764494106837551, + "Healthcare": -0.0034369094727746408, + "Nature": 0.0019861337575274307, + "Sales": -0.0016631062107022032, + "Transport": 0.0010649224930543433, + "Web/CloudOps": -0.0015143773362779056 + }, + "frequency": { + "A": -0.007284340388180155, + "D": -0.0011011486797889436, + "H": 0.001750220262270008, + "M": -0.0003416906949502696, + "Q": 0.0018177109331917185, + "S": -0.004901924960286963, + "T": -0.0008988227623395462, + "W": -0.000750856591086646 + }, + "variates": { + "multivariate": -0.001100458825907813, + "univariate": 0.0003771015236686548 + } + }, + "largest_regressions": [ + { + "config_id": "ett2__T__short", + "delta": -0.03752995758620148 + }, + { + "config_id": "solar__W__short", + "delta": -0.01533952306784947 + }, + { + "config_id": "electricity__D__short", + "delta": -0.014278007645682878 + }, + { + "config_id": "ett2__W__short", + "delta": -0.013238694460688039 + }, + { + "config_id": "us_births__M__short", + "delta": -0.012627791238285946 + }, + { + "config_id": "covid_deaths__D__short", + "delta": -0.012198030304103158 + }, + { + "config_id": "bizitobs_l2c__H__long", + "delta": -0.010803612778359506 + }, + { + "config_id": "bizitobs_service__S__long", + "delta": -0.010050731212922548 + } + ], + "largest_improvements": [ + { + "config_id": "saugeenday__M__short", + "delta": 0.03020026077059823 + }, + { + "config_id": "solar__H__short", + "delta": 0.022114685855228244 + }, + { + "config_id": "m4_weekly__W__short", + "delta": 0.01777517680268792 + }, + { + "config_id": "saugeenday__D__short", + "delta": 0.016384565809412055 + }, + { + "config_id": "ett1__H__short", + "delta": 0.01634647827951685 + }, + { + "config_id": "bizitobs_l2c__T__short", + "delta": 0.009153951656844739 + }, + { + "config_id": "ett2__H__long", + "delta": 0.009055952297336467 + }, + { + "config_id": "us_births__W__short", + "delta": 0.008843222314374732 + } + ] + } + } + }, + { + "panel": "valid_backcast2", + "skill": 0.370165235742403, + "delta_frozen": 0.0005025115722999685, + "delta_current": 0.00014243668260938147, + "evaluation_seconds": 100.25852539995685, + "groups": { + "term": { + "long": 0.3746030178698837, + "medium": 0.39802671895428543, + "short": 0.35738841642464303 + }, + "domain": { + "Econ/Fin": 0.1323486875356592, + "Energy": 0.24292163183181514, + "Healthcare": 0.35228401440266144, + "Nature": 0.4852885285490327, + "Sales": 0.558062864460154, + "Transport": 0.4292701878450944, + "Web/CloudOps": 0.4472373718762672 + }, + "frequency": { + "A": 0.3376791200195063, + "D": 0.434576795036537, + "H": 0.4007111671293758, + "M": 0.17558532638266144, + "Q": 0.1570532697461301, + "S": 0.29041607621088816, + "T": 0.3713653832285535, + "W": 0.2835290764348716 + }, + "variates": { + "multivariate": 0.3727462281145816, + "univariate": 0.36807283708470684 + } + }, + "comparisons": { + "frozen": { + "positive_configs": 53, + "total_configs": 94, + "group_skill_delta": { + "term": { + "long": 0.00046154921242391733, + "medium": -0.0009259667697880669, + "short": 0.0011109891098166624 + }, + "domain": { + "Econ/Fin": 0.004840787974594418, + "Energy": 0.0021567995702810316, + "Healthcare": -0.009885633893269574, + "Nature": 0.0030193997111206405, + "Sales": -0.0011798327261103303, + "Transport": 0.001386919479457016, + "Web/CloudOps": -0.002503391368354202 + }, + "frequency": { + "A": -0.0005070593385431144, + "D": -0.0007705332940446397, + "H": 0.00011737693536750804, + "M": 0.006461641804624163, + "Q": 0.0014695791247345547, + "S": -0.00048487960534449037, + "T": 0.0005296600020219255, + "W": 0.003323158351278055 + }, + "variates": { + "multivariate": -0.0013042695454289488, + "univariate": 0.0019765275269396643 + } + }, + "largest_regressions": [ + { + "config_id": "us_births__W__short", + "delta": -0.02914353927801272 + }, + { + "config_id": "covid_deaths__D__short", + "delta": -0.02553922227352634 + }, + { + "config_id": "ett1__H__short", + "delta": -0.02225682025809561 + }, + { + "config_id": "bizitobs_l2c__T__medium", + "delta": -0.012161659250741863 + }, + { + "config_id": "bizitobs_l2c__H__medium", + "delta": -0.01109889175034473 + }, + { + "config_id": "bizitobs_l2c__T__long", + "delta": -0.010258181331123994 + }, + { + "config_id": "bitbrains_fast_storage__T__long", + "delta": -0.008041928465346238 + }, + { + "config_id": "solar__H__short", + "delta": -0.007818024534947399 + } + ], + "largest_improvements": [ + { + "config_id": "solar__T__medium", + "delta": 0.028617771667922565 + }, + { + "config_id": "saugeenday__M__short", + "delta": 0.027788292391105807 + }, + { + "config_id": "electricity__H__short", + "delta": 0.024438714197914324 + }, + { + "config_id": "m4_weekly__W__short", + "delta": 0.01695457751928464 + }, + { + "config_id": "bizitobs_application__S__long", + "delta": 0.01596727617238436 + }, + { + "config_id": "bitbrains_fast_storage__T__short", + "delta": 0.014352145036357511 + }, + { + "config_id": "m4_hourly__H__short", + "delta": 0.013747019489813495 + }, + { + "config_id": "saugeenday__W__short", + "delta": 0.012095518468011046 + } + ] + }, + "current": { + "positive_configs": 47, + "total_configs": 94, + "group_skill_delta": { + "term": { + "long": -8.190260641760538e-05, + "medium": -0.001289588649044382, + "short": 0.0008190177037810109 + }, + "domain": { + "Econ/Fin": 0.006566241477034329, + "Energy": 0.00201888105482928, + "Healthcare": -0.010789734477457014, + "Nature": 0.0008615603182332565, + "Sales": -0.0030187923435289754, + "Transport": -0.000312957374618561, + "Web/CloudOps": -0.0006412279560695788 + }, + "frequency": { + "A": 0.0008860976972934198, + "D": -0.0012877007479034086, + "H": -0.001147416970784576, + "M": 0.003957552056173874, + "Q": 0.0018692664066987108, + "S": -0.0031346020586952017, + "T": 0.0028218090788735273, + "W": -0.0011702871962671058 + }, + "variates": { + "multivariate": -0.00043473632107537963, + "univariate": 0.0006124764646336933 + } + }, + "largest_regressions": [ + { + "config_id": "us_births__W__short", + "delta": -0.04522864918889835 + }, + { + "config_id": "ett1__H__short", + "delta": -0.02980086636965662 + }, + { + "config_id": "covid_deaths__D__short", + "delta": -0.026622975228819068 + }, + { + "config_id": "bizitobs_l2c__T__long", + "delta": -0.013925789747193829 + }, + { + "config_id": "bizitobs_l2c__H__medium", + "delta": -0.01225959211572869 + }, + { + "config_id": "M_DENSE__D__short", + "delta": -0.01139837638500496 + }, + { + "config_id": "kdd_cup_2018_with_missing__H__short", + "delta": -0.010071935346354866 + }, + { + "config_id": "bizitobs_l2c__T__medium", + "delta": -0.008937401580049187 + } + ], + "largest_improvements": [ + { + "config_id": "bitbrains_fast_storage__T__short", + "delta": 0.026437292973894078 + }, + { + "config_id": "electricity__H__short", + "delta": 0.024124697531306527 + }, + { + "config_id": "solar__T__medium", + "delta": 0.021358420118383514 + }, + { + "config_id": "m4_weekly__W__short", + "delta": 0.01771913006559611 + }, + { + "config_id": "bizitobs_application__S__long", + "delta": 0.01610448772034556 + }, + { + "config_id": "bizitobs_l2c__T__short", + "delta": 0.016047750480295164 + }, + { + "config_id": "saugeenday__M__short", + "delta": 0.015056733755292484 + }, + { + "config_id": "m4_hourly__H__short", + "delta": 0.014967185976311748 + } + ] + } + } + }, + { + "panel": "valid_backcast3", + "skill": 0.39237316871514827, + "delta_frozen": 0.00024349043050786445, + "delta_current": -0.00044726562041652596, + "evaluation_seconds": 99.79332129308023, + "groups": { + "term": { + "long": 0.3987399912668941, + "medium": 0.3712118543710127, + "short": 0.3978009201473006 + }, + "domain": { + "Econ/Fin": 0.19374184549525353, + "Energy": 0.319225077746341, + "Healthcare": 0.23540521735709186, + "Nature": 0.5055944342925276, + "Sales": 0.40439439187277426, + "Transport": 0.5133813444860625, + "Web/CloudOps": 0.39979817688479 + }, + "frequency": { + "A": 0.36363686159997777, + "D": 0.4444603045575869, + "H": 0.40931261715130385, + "M": 0.14492875729774468, + "Q": 0.2626350749217361, + "S": 0.28942160957712804, + "T": 0.43408860654354897, + "W": 0.2502433193667285 + }, + "variates": { + "multivariate": 0.37544255081972233, + "univariate": 0.4053980899115547 + } + }, + "comparisons": { + "frozen": { + "positive_configs": 48, + "total_configs": 93, + "group_skill_delta": { + "term": { + "long": -0.0006048008701443619, + "medium": -0.0019682574919023255, + "short": 0.0013294740788182269 + }, + "domain": { + "Econ/Fin": 0.0022270104202506413, + "Energy": 0.002075301385040529, + "Healthcare": 0.0013360968373909987, + "Nature": -0.003182878045671522, + "Sales": 0.001984467999793904, + "Transport": 0.0031662799449563295, + "Web/CloudOps": -0.0029709645730785494 + }, + "frequency": { + "A": 0.0003488720385010913, + "D": 0.004219693771285504, + "H": 0.0012654276529275865, + "M": -0.0012313475135308227, + "Q": -0.0009322157859709135, + "S": -0.004782139438104904, + "T": -0.000576009232815311, + "W": -0.005767223191885051 + }, + "variates": { + "multivariate": -0.00011465668895771497, + "univariate": 0.0005123481721718282 + } + }, + "largest_regressions": [ + { + "config_id": "saugeenday__W__short", + "delta": -0.028017629370064467 + }, + { + "config_id": "us_births__M__short", + "delta": -0.026429078592109634 + }, + { + "config_id": "ett2__T__medium", + "delta": -0.01987959040247167 + }, + { + "config_id": "bizitobs_l2c__T__medium", + "delta": -0.019216515883336727 + }, + { + "config_id": "solar__H__short", + "delta": -0.017831254043257916 + }, + { + "config_id": "bizitobs_application__S__medium", + "delta": -0.014237599062127404 + }, + { + "config_id": "bizitobs_application__S__long", + "delta": -0.012947171894775567 + }, + { + "config_id": "saugeenday__D__short", + "delta": -0.011737583574634947 + } + ], + "largest_improvements": [ + { + "config_id": "ett1__D__short", + "delta": 0.021305286916028843 + }, + { + "config_id": "ett1__T__short", + "delta": 0.01950320729113786 + }, + { + "config_id": "us_births__D__short", + "delta": 0.019002635067128293 + }, + { + "config_id": "saugeenday__M__short", + "delta": 0.01899588796034757 + }, + { + "config_id": "ett2__W__short", + "delta": 0.017104737525266978 + }, + { + "config_id": "ett1__H__short", + "delta": 0.012380541272503875 + }, + { + "config_id": "ett1__H__long", + "delta": 0.011673314863784645 + }, + { + "config_id": "M_DENSE__H__short", + "delta": 0.01153556514460563 + } + ] + }, + "current": { + "positive_configs": 52, + "total_configs": 93, + "group_skill_delta": { + "term": { + "long": -0.0015782659204579552, + "medium": -0.0010045391496978917, + "short": 0.00014984569175102713 + }, + "domain": { + "Econ/Fin": 0.004516372311230921, + "Energy": 0.00023727507758941613, + "Healthcare": -0.004427549646247031, + "Nature": -0.004658795890397194, + "Sales": 0.0012921341810825382, + "Transport": 0.0019642951937861586, + "Web/CloudOps": -0.00016654951124606132 + }, + "frequency": { + "A": 0.005503187931264142, + "D": 0.0006819861506709435, + "H": 0.00010140165168415205, + "M": -0.005570992768429317, + "Q": 0.00017412488848378427, + "S": -0.005037492821408418, + "T": 0.000687029370882386, + "W": -0.00625863145277028 + }, + "variates": { + "multivariate": -0.00019730174336130002, + "univariate": -0.0006345930027260582 + } + }, + "largest_regressions": [ + { + "config_id": "saugeenday__W__short", + "delta": -0.032284102135443415 + }, + { + "config_id": "us_births__M__short", + "delta": -0.02972875112606821 + }, + { + "config_id": "ett2__T__medium", + "delta": -0.020831796104619493 + }, + { + "config_id": "bizitobs_l2c__T__medium", + "delta": -0.020696457368158505 + }, + { + "config_id": "bizitobs_application__S__long", + "delta": -0.017386586312124863 + }, + { + "config_id": "solar__H__short", + "delta": -0.015834585889969333 + }, + { + "config_id": "ett2__H__long", + "delta": -0.013223281881858728 + }, + { + "config_id": "saugeenday__D__short", + "delta": -0.012939111941303483 + } + ], + "largest_improvements": [ + { + "config_id": "bitbrains_fast_storage__T__short", + "delta": 0.014989922544629941 + }, + { + "config_id": "ett2__D__short", + "delta": 0.012295103918030459 + }, + { + "config_id": "ett2__W__short", + "delta": 0.01205773770567875 + }, + { + "config_id": "M_DENSE__H__short", + "delta": 0.01064022250326746 + }, + { + "config_id": "ett1__D__short", + "delta": 0.010164132991920205 + }, + { + "config_id": "electricity__H__short", + "delta": 0.010111892506530551 + }, + { + "config_id": "m4_hourly__H__short", + "delta": 0.009831015829539158 + }, + { + "config_id": "ett2__H__medium", + "delta": 0.008743734810650383 + } + ] + } + } + } + ], + "selection_gate_passed": false, + "positive_frozen": 3, + "mean_delta_frozen": 0.0004653507815086111, + "positive_current": 2, + "mean_delta_current": 4.919528013067054e-05, + "cpu_review_seconds": 0.04057373688556254, + "new_optimizer_updates": 0, + "new_inference": false, + "outcome": "Four-cutoff gate fails; no full replay or publication from this endpoint.", + "interpretation": "Adaptive validation diagnostics, not independent test evidence. Frequency groups are recomputed using the scorer frequency parser, avoiding comparison of full aliases with frequency-unit groups." +} \ No newline at end of file diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_six_blend_receipt.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_six_blend_receipt.json new file mode 100644 index 0000000000000000000000000000000000000000..3e0463be707f59e2811a69750cd4738bc600e8da --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_six_blend_receipt.json @@ -0,0 +1,328 @@ +{ + "utc": "2026-10-24T01:56:53.145693+00:00", + "declaration": { + "experiment": "E172", + "declared_utc": "2026-10-24T01:56:39.279821+00:00", + "status": "declared; cached four-cutoff comparison pending", + "hypothesis": "E152refreshed primary6k gate improves its fixedE148source3of4 but currentE159comparison2of4 with positive mean. Test one equal blend with E159 to reduce departures from the selected six-expert forecast while retaining complementary gate behavior. This is a separately declared fixed pooling hypothesis, not a reinterpretation of the rejected standalone gate.", + "parent_descriptor": "20f014ca61a9cfa4f275d9d7abfd297561ac37fddcdae9ba2ef60d3fca106cf8", + "parent_probe_prefix": "seasonal_six_member_blend", + "gate_run": "ensemble_gate_refresh", + "gate_step": 6000, + "gate_checkpoint_sha256": "a7d0ee6866ea787f29eac043531aad3613674f159fd00b3491fd87fab8388fd1", + "gate_expert_descriptor": "a1b4ab426901be8e1ee299eeeb3f041bac7cea3d4e59c4608824fc3d05c83e03", + "member_checkpoint_hashes": [ + "0b11b7351a4a92d1d18c71a4159ec445be3a94ace8c7a9fa0edafad87d14e960", + "308389b7217c080af9eb185559d4ee3cafa0f3e0f8c4dd8f5526b68198c89988", + "1a2fb20a9fb5cae6526f2e36ea47559626bece78fd9c284899836505030ae9fe", + "d7cfcd72c3cb84aa69e447b76c4c3ab98c21b7c600a463f0b805f4b4300baf33", + "2877a38b94a7d77a53a9df410349cecc2f6ab134c83a76744924543bbe73eb17", + "4b309f0721378f97db815dd511b8b54711348270c48e9eae0103dba506f66708" + ], + "parameters": 549432812, + "blend_coefficient": 0.5, + "composition": "Compute all six ownE159expertforecasts and the fixedE152primary6k gate on F0/F1/F2/F3 for every instance. Preserve orderedFP32E159two-quartermeans asA and orderedFP32gateweightedpoolasG; output(A+G)/2. No duplicate neural expert parameters; the gate adds6340. Everyexpert andgate executes everyinstance.", + "source_training": "Existing E152seed751/B64/LR.001/12k/oldpack/originalAR frozenE148expert recipe; only the alreadydeclared primary6000 is used. No new training, coefficient, threshold, checkpoint or frequency search.", + "source_gate": { + "positive_frozen": 3, + "mean_delta_frozen": 0.0004653507815086111, + "primary_standalone_current_positive": 2, + "primary_standalone_current_mean_delta": 4.919528013067054e-05 + }, + "selection": "One cached allfourcutoff probe; require>=3positive andpositivemean versus frozenE159 and then-current publication. Onlyifpasses, build independent composition/actualallforward synthetic/relocation and full97publicreplay againstcurrent. No automaticpublication. FinalE15212k is not partof this declaration.", + "scientific_scope": "Validation selection only. No weight fitting, no trained parameters changed, no validation training.", + "training_queued": false + }, + "rows": [ + { + "cutoff": "valid_screen", + "skill": 0.3893607757169213, + "control_skill": 0.38873378968262917, + "delta": 0.0006269860342921207, + "groups": { + "term": { + "short": 0.3730551980552743, + "medium": 0.4123605358882224, + "long": 0.40777809459379144 + }, + "domain": { + "Econ/Fin": 0.1507657392482069, + "Energy": 0.2481104899131934, + "Healthcare": 0.488089767759725, + "Nature": 0.44415019213823026, + "Sales": 0.34537564038514124, + "Transport": 0.47556873259947485, + "Web/CloudOps": 0.5085043509486793 + }, + "freq": { + "A-DEC": 0.3818434006747864, + "Q-DEC": 0.2052608713475952, + "M": 0.12088969329714627, + "W-SUN": 0.10603481522416103, + "D": 0.3757624318941025, + "H": 0.4049899775226913, + "15T": 0.21818881284983382, + "W-FRI": 0.020070427473252495, + "10T": 0.6276775322383856, + "W-TUE": 0.620546697076482, + "W-THU": 0.21623223124759539, + "W-WED": 0.32674883823352585, + "5T": 0.5227392646506106, + "10S": 0.4250765858338945 + } + }, + "group_deltas": { + "term": { + "short": 0.0006711915392915158, + "medium": 0.0006002052719409345, + "long": 0.0005433263567319324 + }, + "domain": { + "Econ/Fin": 0.001256418886594779, + "Energy": 5.2139008443474744e-05, + "Healthcare": 0.002979206174708482, + "Nature": 0.0005374088867736715, + "Sales": -0.0008402759806811488, + "Transport": 0.0005447617320485376, + "Web/CloudOps": 0.0008488264395033474 + }, + "freq": { + "A-DEC": -0.00034247885312044257, + "Q-DEC": -0.0009460468284139267, + "M": -0.0026088578427427844, + "W-SUN": 0.012810782494087625, + "D": 0.001169827017556302, + "H": 0.0004585158242407239, + "15T": -0.0009271546024641752, + "W-FRI": -0.0007025384832913817, + "10T": 0.0023751766041738565, + "W-TUE": 0.0021652001513374763, + "W-THU": -0.004881323867965581, + "W-WED": -0.00010312681437629756, + "5T": 0.001578705020093718, + "10S": 0.00010113863986971339 + } + }, + "cpu_seconds": 3.7019952330738306 + }, + { + "cutoff": "valid_backcast", + "skill": 0.34590472083989543, + "control_skill": 0.3457740680188046, + "delta": 0.00013065282109081533, + "groups": { + "term": { + "short": 0.3141547815467325, + "medium": 0.3634616307960672, + "long": 0.40633139357265224 + }, + "domain": { + "Econ/Fin": 0.18160067214769848, + "Energy": 0.2353018767525965, + "Healthcare": 0.40212545303316916, + "Nature": 0.3838286469349642, + "Sales": 0.40883915245233005, + "Transport": 0.3793792686903773, + "Web/CloudOps": 0.45925088449552687 + }, + "freq": { + "A-DEC": 0.33078754893744844, + "Q-DEC": 0.23700570996944292, + "M": 0.19175411902001915, + "W-SUN": 0.059062160550052645, + "D": 0.3646819545891079, + "H": 0.3781561519075256, + "15T": 0.22230194455244912, + "W-FRI": 0.23968590164728443, + "10T": 0.33197069489258824, + "W-TUE": 0.5482014822555118, + "W-THU": 0.26697898734276704, + "W-WED": 0.3596949129785524, + "5T": 0.447691271232037, + "10S": 0.3480039033453973 + } + }, + "group_deltas": { + "term": { + "short": 0.00031706729303448977, + "medium": 0.0004880722831459572, + "long": -0.0006256537550753949 + }, + "domain": { + "Econ/Fin": 0.001608231014177841, + "Energy": -0.00028020029101583077, + "Healthcare": -0.00045655228159469097, + "Nature": 0.0011611259882308156, + "Sales": -0.0006934377397707081, + "Transport": 0.0007745758084236609, + "Web/CloudOps": -0.0005165107060015606 + }, + "freq": { + "A-DEC": -0.0034805508654538464, + "Q-DEC": 0.0010795183708239842, + "M": -6.475571291453264e-05, + "W-SUN": 0.009777700438601933, + "D": -0.0003126379444291505, + "H": 0.0010567653684582234, + "15T": -0.0012034479413790544, + "W-FRI": -0.004422242821654376, + "10T": -0.00024151542419659222, + "W-TUE": 0.008623779828861977, + "W-THU": -0.001894526919008821, + "W-WED": -0.001504054330422333, + "5T": 0.000582692474802804, + "10S": -0.002282607394639813 + } + }, + "cpu_seconds": 3.0887457050848752 + }, + { + "cutoff": "valid_backcast2", + "skill": 0.37032451826756796, + "control_skill": 0.37002279905979363, + "delta": 0.00030171920777433137, + "groups": { + "term": { + "short": 0.35723644813894817, + "medium": 0.39885376165266295, + "long": 0.37485551090685776 + }, + "domain": { + "Econ/Fin": 0.1294828662555424, + "Energy": 0.2420929700491008, + "Healthcare": 0.35832911544768686, + "Nature": 0.4850218341451855, + "Sales": 0.5597828255558903, + "Transport": 0.4296637233616497, + "Web/CloudOps": 0.44776364143411507 + }, + "freq": { + "A-DEC": 0.33751333277513795, + "Q-DEC": 0.15624001754761851, + "M": 0.173705610096883, + "W-SUN": 0.08174657817330688, + "D": 0.4355268947155827, + "H": 0.4014479697019465, + "15T": 0.10760686555452637, + "W-FRI": 0.1497453849053848, + "10T": 0.5100968640751355, + "W-TUE": 0.1486916688372394, + "W-THU": 0.34865588619800225, + "W-WED": 0.5605192267020931, + "5T": 0.4810945186712752, + "10S": 0.29233165162853614 + } + }, + "group_deltas": { + "term": { + "short": 0.000667049418086263, + "medium": -0.00046254595066685944, + "long": 0.00017059043055644985 + }, + "domain": { + "Econ/Fin": 0.003700420196917631, + "Energy": 0.001190219272115045, + "Healthcare": -0.004744633432431589, + "Nature": 0.0005948659143860668, + "Sales": -0.00129883124779262, + "Transport": 8.057814193673796e-05, + "Web/CloudOps": -0.00011495839822184273 + }, + "freq": { + "A-DEC": 0.0007203104529249771, + "Q-DEC": 0.0010560142081871282, + "M": 0.002077835770395442, + "W-SUN": 0.009924292322614381, + "D": -0.000337601068857718, + "H": -0.0004106143982137711, + "15T": 0.0017468468609213028, + "W-FRI": 0.0015954103228104088, + "10T": 0.0016902448197386732, + "W-TUE": -0.021206499546449487, + "W-THU": 0.002327210402568669, + "W-WED": -0.0006048046974167498, + "5T": 0.00137609860180532, + "10S": -0.0012190266410473383 + } + }, + "cpu_seconds": 3.160733606899157 + }, + { + "cutoff": "valid_backcast3", + "skill": 0.3928349019291829, + "control_skill": 0.3928204343355648, + "delta": 1.4467593618117114e-05, + "groups": { + "term": { + "short": 0.3979990711275432, + "medium": 0.3718944414184592, + "long": 0.39972660239069135 + }, + "domain": { + "Econ/Fin": 0.1918528924020163, + "Energy": 0.3194076629319105, + "Healthcare": 0.2379658962711424, + "Nature": 0.508075572513706, + "Sales": 0.40386469156469385, + "Transport": 0.5126069399879463, + "Web/CloudOps": 0.40009299351864624 + }, + "freq": { + "A-DEC": 0.3610310384013814, + "Q-DEC": 0.26270153125987217, + "M": 0.1478243478998057, + "W-SUN": 0.1749840554744284, + "D": 0.44442387004267214, + "H": 0.40947638058906866, + "15T": 0.2589060819854081, + "W-FRI": 0.041384655614342125, + "10T": 0.6042590264705352, + "W-TUE": 0.2829189507620672, + "W-THU": 0.3435745424656176, + "W-WED": 0.37388652896545693, + "5T": 0.47123445884488524, + "10S": 0.29219007122444685 + } + }, + "group_deltas": { + "term": { + "short": 0.00034799667199358897, + "medium": -0.00032195210225138826, + "long": -0.0005916547966606789 + }, + "domain": { + "Econ/Fin": 0.0026274192179935874, + "Energy": 0.0004198602631588777, + "Healthcare": -0.0018668707321964906, + "Nature": -0.0021776576692187355, + "Sales": 0.0007624338730021218, + "Transport": 0.0011898906956698818, + "Web/CloudOps": 0.0001282671226101595 + }, + "freq": { + "A-DEC": 0.002897364732667773, + "Q-DEC": 0.00024058122661985148, + "M": -0.0026754021663683014, + "W-SUN": 0.004152506234445519, + "D": 0.0006455516357561919, + "H": 0.0002651650894490709, + "15T": -0.0008473575991772009, + "W-FRI": -0.001924335287768919, + "10T": 0.0011361723999093742, + "W-TUE": 0.0003600536753383121, + "W-THU": -0.007689208493001143, + "W-WED": 0.002034211822345089, + "5T": 0.0010919100951652938, + "10S": -0.0022690311740896085 + } + }, + "cpu_seconds": 3.08497832599096 + } + ], + "positive_cutoffs": 4, + "mean_delta": 0.00026845641419384614, + "seconds": 13.781859948066995, + "optimizer_updates": 0, + "new_neural_inference": false, + "selection_gate_passed": true +} \ No newline at end of file diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/check_cpu.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/check_cpu.py new file mode 100644 index 0000000000000000000000000000000000000000..c6f59ae2fda2dff9368b2fbac7b0d436f04ff6c3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/check_cpu.py @@ -0,0 +1,55 @@ +"""Verify unchanged E138 arithmetic, initialization and source probabilities for E152.""" +import ast, copy, datetime, hashlib, importlib.util, json, time +from pathlib import Path +import numpy as np +import torch +from data import Sampler +from model import DirectForecaster + +R = Path('/workspace/research'); HERE = Path(__file__).resolve().parent +started = time.monotonic(); torch.set_num_threads(1) +def digest(path): + with Path(path).open('rb') as f:return hashlib.file_digest(f, 'sha256').hexdigest() +identical = {} +for name in ['model.py', 'data.py', 'normalization.py', 'frequency.py', 'predict.py', 'infer.sh', 'ts_io.py']: + assert (HERE/name).read_bytes() == (R/'ensemble_gate'/name).read_bytes() + identical[name] = digest(HERE/name) +def method(path): + tree = ast.parse(Path(path).read_text()) + cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'FrozenExperts') + return ast.dump(next(n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == '__call__'), include_attributes=False) +assert method(HERE/'experts.py') == method(R/'ensemble_gate/experts.py') +path = R/'ensemble_gate_initial.pt'; checkpoint_hash = digest(path) +assert checkpoint_hash == '9d1401cd4d5b5f1c3ddd25a4a74e15e5db7ef708116cdf5c4fa7e90580b58da1' +checkpoint = torch.load(path, map_location='cpu', weights_only=False) +torch.manual_seed(751); model = DirectForecaster(**checkpoint['config']) +assert all(torch.equal(model.state_dict()[k], v) for k, v in checkpoint['model'].items()) +spec = importlib.util.spec_from_file_location('original_gate_sampler', R/'ensemble_gate/data.py') +original = importlib.util.module_from_spec(spec); spec.loader.exec_module(original) +seed = 983 +old = original.Sampler(R/'packed_sample', seed=seed, source_weights_from=R/'packed_sample') +new = Sampler(R/'packed_sample', seed=seed, source_weights_from=R/'packed_sample') +for _ in range(8): + a = old.sample(64, 512, 128); b = new.sample(64, 512, 128) + assert all(np.array_equal(x, y, equal_nan=True) for x, y in zip(a, b)) +for key in ['rng', 'horizon_rng']: + assert getattr(old, key).bit_generator.state == getattr(new, key).bit_generator.state +full = Sampler(R/'packed_stratified_full', seed=seed, source_weights_from=R/'packed_sample') +assert old.dirs == full.dirs and len(full.dirs) == 95 +assert np.array_equal(old.probs, full.probs) +assert old.synthetic_fraction == full.synthetic_fraction == .2 +full_states = {k: copy.deepcopy(v.bit_generator.state) for k, v in vars(full).items() if isinstance(v, np.random.Generator)} +first = full.sample(64, 512, 128) +for key, value in full_states.items():getattr(full, key).bit_generator.state = value +repeated = full.sample(64, 512, 128) +assert all(np.array_equal(a, b, equal_nan=True) for a, b in zip(first, repeated)) +result = dict(utc=datetime.datetime.now(datetime.timezone.utc).isoformat(), fixture_seed=seed, training_seed=751, + initial_sha256=checkpoint_hash, same_seed_recreates_initial_bitwise=True, + unchanged_files=identical, frozen_expert_forward_ast_identical=True, + original_old_pack_stream_bitwise=True, sampled_old_rows=512, + all95_sources_and_probabilities_identical=True, synthetic_fraction=.2, + full_pack_sampler_state_recovery_bitwise=True, full_pack_fixture_rows=64, + reused_feature_gradient_audit=str(R/'ensemble_gate_cpu_checks.json'), + seconds=time.monotonic()-started, optimizer_updates=0, validation_data_read=False) +(R/'ensemble_gate_factorial_cpu_checks.json').write_text(json.dumps(result, indent=2)) +print(json.dumps(result), flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/check_gpu.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/check_gpu.py new file mode 100644 index 0000000000000000000000000000000000000000..4098d1c0c7e05b03101343af8f3109f84c7e25b6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/check_gpu.py @@ -0,0 +1,58 @@ +"""E152 updated frozen-expert replay on existing synthetic fixtures and maximum training shape.""" +import fcntl,hashlib,json,sys,time +from pathlib import Path +import numpy as np +import torch +R=Path('/workspace/research');sys.path.insert(0,str(R/'ensemble_gate_factorial'));sys.path.insert(0,'/workspace/evaluation') +from model import DirectForecaster,combine,loss_fn +from experts import FrozenExperts +from data import Sampler +from ts_io import CaseFile,read_prediction_file +started=time.monotonic();torch.set_num_threads(4);torch.manual_seed(1009);torch.backends.cuda.matmul.allow_tf32=False +lock=open(R/'.evaluation.lock','a');tick=time.monotonic();fcntl.flock(lock,fcntl.LOCK_EX);wait=time.monotonic()-tick +path=R/'ensemble_gate_initial.pt';initial_hash=hashlib.sha256(path.read_bytes()).hexdigest();ck=torch.load(path,map_location='cpu',weights_only=False) +gate=DirectForecaster(**ck['config']).cuda();gate.load_state_dict(ck['model']);experts=FrozenExperts(R/'gating_experts_E148') +assert sum(p.numel() for p in gate.parameters())==6340 and all(not p.requires_grad for model in experts.models for p in model.parameters()) +fixture=R/'fresh_capacity4_fixture';index=json.loads((fixture/'input/index.json').read_text());checks=[] +for cfg in index['configs']: + cid=cfg['config_id'];case=CaseFile(fixture/'input/cases'/(cid+'.h5'));n,d,h=case.n,case.n_variates,case.prediction_length + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + reference_dirs=[R/'width12_fixture/standalone0',fixture/'standalone1',fixture/'standalone2',R/'fresh_capacity96_fixture/standalone3'] + for directory,expected in zip(reference_dirs,experts.member_hashes): + assert json.loads((directory/'model_manifest.json').read_text())['weights_sha256']==expected + assert json.loads((R/'width12_fresh96_fixture/ensemble/model_manifest.json').read_text())['checkpoint_sha256']==experts.descriptor_sha256 + references=[read_prediction_file(path/'cases'/(cid+'.h5'))[1].reshape(n*d,9,h) for path in reference_dirs] + ensemble_reference=read_prediction_file(R/'width12_fresh96_fixture/ensemble/cases'/(cid+'.h5'))[1].reshape(n*d,9,h) + # The saved E130 audit deliberately used batch4; match its batch shapes exactly. + for offset in range(0,len(order),4): + ids=order[offset:offset+4];length=min(4096,max(int(case.context_length[i//d]) for i in ids));ctx=np.full((len(ids),length),np.nan,np.float32) + for j,k in enumerate(ids): + values=case.context(int(k//d))[k%d,-length:];ctx[j,-len(values):]=values + x=torch.from_numpy(ctx).cuda();p=torch.tensor([experts.periods_for_freq(cfg['freq'])]*len(ids),device='cuda');outputs=experts(x,p,h) + for member in range(4): + reference=references[member][ids].transpose(0,2,1);observed=outputs[:,member].cpu().numpy() + assert np.array_equal(reference,observed),(cid,offset,member,float(np.max(np.abs(reference-observed)))) + with torch.no_grad():weights=gate(x,p,outputs,torch.full((len(ids),),h,device='cuda'));prediction=combine(outputs,weights) + reference=ensemble_reference[ids].transpose(0,2,1) + assert np.array_equal(reference,prediction.cpu().numpy()),(cid,offset,float(np.max(np.abs(reference-prediction.cpu().numpy())))) + assert torch.equal(weights,torch.full_like(weights,.25)) + checks.append(dict(config_id=cid,rows=n*d,horizon=h,batch=4,all_four_experts_bitwise=True,initial_ensemble_bitwise=True)) + case.close() +del x,p,outputs,weights,prediction +# Temporary head perturbation exercises all gate layers, not only the zero output layer. +torch.manual_seed(1009) +with torch.no_grad():gate.net[-1].weight.normal_(0,.01) +torch.cuda.empty_cache();torch.cuda.reset_peak_memory_stats();free_before=torch.cuda.mem_get_info()[0]/2**20 +sampler=Sampler(R/'packed_stratified_full',seed=1009,source_weights_from=R/'packed_sample');x,y,p=[torch.from_numpy(v).cuda() for v in sampler.sample(64,4096,1024)] +positions=torch.arange(y.shape[-1],device='cuda')[None,:]+1;lengths=torch.where(torch.isfinite(y),positions,0).max(-1).values.clamp(min=1) +tick=time.monotonic();outputs=experts(x,p,y.shape[-1],forecast_lengths=lengths);torch.cuda.synchronize();expert_seconds=time.monotonic()-tick +placeholders=[torch.zeros_like(v) for v in gate.parameters() for _ in range(3)] +tick=time.monotonic();loss=loss_fn(gate,x,y,p,outputs,paired=True);loss.backward();torch.cuda.synchronize();gate_seconds=time.monotonic()-tick +assert torch.isfinite(loss) and all(v.grad is not None and torch.isfinite(v.grad).all() and v.grad.norm()>0 for v in gate.parameters()) +assert all(v.grad is None and not v.requires_grad for model in experts.models for v in model.parameters()) +with torch.no_grad():weights=gate(x,p,outputs,lengths);prediction=combine(outputs,weights) +assert torch.all((weights>=.125)&(weights<=.625)) and torch.max(torch.abs(weights.sum(-1)-1))<2e-7 +assert torch.isfinite(prediction).all() and torch.all(prediction[:,:,1:]>=prediction[:,:,:-1]) +assert hashlib.sha256(path.read_bytes()).hexdigest()==initial_hash +result=dict(fixture_seed=1009,training_seed=751,initial_checkpoint_sha256=initial_hash,expert_descriptor_sha256=experts.descriptor_sha256,expert_hashes=experts.member_hashes,synthetic_replay_checks=checks,maximum_shape=[64,4096,1024],frozen_expert_parameters=experts.parameters,trainable_parameters=6340,temporary_gate_head_std=.01,all_gate_layers_finite_nonzero_gradients=True,experts_have_no_gradients=True,loss=float(loss.detach()),minimum_weight=float(weights.min()),maximum_weight=float(weights.max()),peak_allocated_mib=torch.cuda.max_memory_allocated()/2**20,peak_reserved_mib=torch.cuda.max_memory_reserved()/2**20,free_before_mib=free_before,includes_gate_adam_and_ema_placeholders=True,expert_forward_seconds=expert_seconds,gate_forward_backward_seconds=gate_seconds,lock_wait_seconds=wait,seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False,initial_checkpoint_unchanged=True) +(R/'ensemble_gate_factorial_gpu_checks.json').write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/check_learned_runtime.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/check_learned_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..5af43dcfb141e0dd5fe79690b08b46a41d19320a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/check_learned_runtime.py @@ -0,0 +1,95 @@ +"""Independent NumPy composition of separately replayed experts with learned gate weights.""" +import argparse +import fcntl +import hashlib +import json +import subprocess +import sys +import time +from pathlib import Path + +import numpy as np +import torch + +R=Path('/workspace/research') +ap=argparse.ArgumentParser();ap.add_argument('--package',required=True);ap.add_argument('--receipt',required=True) +a=ap.parse_args();package=Path(a.package);receipt=Path(a.receipt) +sys.path.insert(0,str(package)) +from model import DirectForecaster +from frequency import periods_for_freq +import ts_io + +started=time.monotonic();torch.set_num_threads(4);torch.manual_seed(0) +torch.backends.cuda.matmul.allow_tf32=False +manifest=json.loads((package/'model_manifest.json').read_text()) +assert manifest['expert_descriptor_sha256'] in ('fa97880dd132b1cdff459be4798f8f360d7df59b13e78026a9d74a95d63df0db','a1b4ab426901be8e1ee299eeeb3f041bac7cea3d4e59c4608824fc3d05c83e03') +with (package/'gate.pt').open('rb') as f:assert hashlib.file_digest(f,'sha256').hexdigest()==manifest['gate_weights_sha256'] +root=R/(package.name+'-runtime-fixture');root.mkdir(exist_ok=True) +sources=[('synthetic',R/'fresh_capacity4_fixture/input',[R/'fresh_capacity4_fixture'/f'standalone{i}' for i in range(4)],4), + ('real',R/'composition_input',[R/n for n in ['composition-pred-long-seasonal-transfer12k','valid-pred-patch8-6k','composition-pred-split-patch-12k','composition-pred-fresh146m48']],128)] +if manifest['expert_descriptor_sha256']=='a1b4ab426901be8e1ee299eeeb3f041bac7cea3d4e59c4608824fc3d05c83e03': + sources=[('synthetic',R/'fresh_capacity4_fixture/input',[R/'width12_fixture/standalone0',R/'fresh_capacity4_fixture/standalone1',R/'fresh_capacity4_fixture/standalone2',R/'fresh_capacity96_fixture/standalone3'],4), + ('real',R/'composition_input',[R/n for n in ['composition-pred-width-transfer12k','valid-pred-patch8-6k','composition-pred-split-patch-12k','composition-pred-fresh146m96']],128)] +checks=[] +with open(R/'.evaluation.lock','a') as lock: + wait_start=time.monotonic();fcntl.flock(lock,fcntl.LOCK_EX);wait_seconds=time.monotonic()-wait_start + for label,inp,references,batch in sources: + for reference,member in zip(references,manifest['members']): + ref_manifest=json.loads((reference/'model_manifest.json').read_text()) + assert ref_manifest['weights_sha256']==member['weights_sha256'] + out=root/label;tick=time.monotonic() + command=['bash',str(package/'infer.sh'),str(inp),str(out)] if label=='real' else ['python3',str(package/'predict.py'),str(inp),str(out),'--batch',str(batch)] + with (root/(label+'.log')).open('w') as log: + subprocess.run(command,cwd='/tmp',stdout=log,stderr=subprocess.STDOUT,check=True) + checkpoint=torch.load(package/'gate.pt',map_location='cpu',weights_only=False) + gate=DirectForecaster(**checkpoint['config']).cuda();gate.load_state_dict(checkpoint['model']);gate.eval() + rows=[] + for cfg in json.loads((inp/'index.json').read_text())['configs']: + cid=cfg['config_id'];case=ts_io.CaseFile(inp/'cases'/(cid+'.h5')) + n,d,h=case.n,case.n_variates,case.prediction_length + experts=np.stack([ts_io.read_prediction_file(ref/'cases'/(cid+'.h5'))[1].reshape(n*d,9,h).transpose(0,2,1) for ref in references],axis=1) + actual_mean,actual=ts_io.read_prediction_file(out/'cases'/(cid+'.h5')) + expected=np.zeros((n*d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + minimum=1.;maximum=0.;sum_error=0.;deviation=0.;weight_totals=np.zeros(4,np.float64);lead_count=0 + for offset in range(0,n*d,batch): + ids=order[offset:offset+batch] + length=min(4096,max(int(case.context_length[i//d]) for i in ids)) + context=np.full((len(ids),length),np.nan,np.float32) + for row,index in enumerate(ids): + values=case.context(int(index//d))[index%d,-length:] + context[row,-len(values):]=values + x=torch.from_numpy(context).cuda() + periods=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + member_predictions=experts[ids].copy() + with torch.inference_mode(): + weights=gate(x,periods,torch.from_numpy(member_predictions).cuda(),torch.full((len(ids),),h,device=x.device)).cpu().numpy() + assert np.isfinite(weights).all() + minimum=min(minimum,float(weights.min()));maximum=max(maximum,float(weights.max())) + sum_error=max(sum_error,float(np.max(np.abs(weights.sum(-1)-1)))) + deviation=max(deviation,float(np.max(np.abs(weights-.25)))) + weight_totals+=weights.sum(axis=(0,1),dtype=np.float64);lead_count+=len(ids)*h + combined=member_predictions[:,0]*weights[:,:,0,None] + for i in range(1,4):combined=combined+member_predictions[:,i]*weights[:,:,i,None] + combined=np.nan_to_num(combined,nan=0.,posinf=1e20,neginf=-1e20) + combined=np.maximum.accumulate(combined,axis=-1) + expected[ids]=combined.transpose(0,2,1) + expected=expected.reshape(n,d,9,h) + assert np.array_equal(expected,actual),(label,cid,float(np.max(np.abs(expected-actual)))) + assert np.array_equal(actual_mean,actual[:,:,4]) + assert np.isfinite(actual).all() and np.all(np.diff(actual,axis=2)>=0) + assert minimum>=.125 and maximum<=.625 and sum_error<3e-7 + if manifest['gate_training_step']>0:assert deviation>0 + rows.append(dict(config_id=cid,instances=n,bitwise_independent_composition=True, + finite_ordered=True,weight_minimum=minimum,weight_maximum=maximum, + weight_sum_maximum_error=sum_error,mean_weights=(weight_totals/lead_count).tolist())) + case.close() + del gate,checkpoint + torch.cuda.empty_cache() + checks.append(dict(kind=label,batch=batch,checks=rows,seconds=time.monotonic()-tick)) +result=dict(status='complete',package=str(package),descriptor_sha256=manifest['checkpoint_sha256'], + gate_weights_sha256=manifest['gate_weights_sha256'],gate_training_step=manifest['gate_training_step'], + expert_descriptor_sha256=manifest['expert_descriptor_sha256'],checks=checks, + lock_wait_seconds=wait_seconds,seconds=time.monotonic()-started,optimizer_updates=0, + validation_labels_read=False,composition='independent ordered NumPy float32 weighted sum and cumulative maximum') +receipt.write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/check_recovery.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/check_recovery.py new file mode 100644 index 0000000000000000000000000000000000000000..73ef4470a083b44fb3a4456c702635276d8cb143 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/check_recovery.py @@ -0,0 +1,42 @@ +"""E152 full-corpus updated-expert rehearsal: uninterrupted and restored gate training must match.""" +import datetime,fcntl,hashlib,json,os,subprocess,time +from pathlib import Path +import numpy as np +import torch + +R=Path('/workspace/research');root=R/'ensemble_gate_factorial_recovery_fixture';root.mkdir(exist_ok=False) +started=time.monotonic();lock=open(R/'.evaluation.lock','a');fcntl.flock(lock,fcntl.LOCK_EX);wait=time.monotonic()-started +initial=R/'ensemble_gate_initial.pt';digest=hashlib.sha256(initial.read_bytes()).hexdigest() +command=['python3',str(R/'recovery/train.py'),'--code-dir',str(R/'ensemble_gate_factorial'),'--packed',str(R/'packed_stratified_full'),'--source-weights-from',str(R/'packed_sample'),'--initialize-from',str(initial),'--steps','12000','--batch','4','--lr','.001','--seed','751','--loss-mode','paired','--gate-package',str(R/'gating_experts_E148'),'--save-every','3','--recovery-every','1'] +durations=[] +for label,out,halt,resume in [('continuous',root/'continuous',6,None),('interrupted',root/'resumed',3,None),('restored',root/'resumed',6,root/'resumed/recovery.pt')]: + assert not out.exists() or resume,label + cmd=command+['--out',str(out),'--halt-after',str(halt)] + if resume:cmd+=['--resume',str(resume)] + tick=time.monotonic() + with (root/(label+'.log')).open('w') as log:subprocess.run(cmd,stdout=log,stderr=subprocess.STDOUT,check=True,env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1')) + durations.append(dict(label=label,seconds=time.monotonic()-tick)) + +def equal(a,b,path=''): + assert type(a)==type(b),(path,type(a),type(b)) + if isinstance(a,torch.Tensor):assert torch.equal(a,b),path + elif isinstance(a,np.ndarray):assert np.array_equal(a,b,equal_nan=True),path + elif isinstance(a,dict): + assert a.keys()==b.keys(),path + for k in a:equal(a[k],b[k],path+'/'+str(k)) + elif isinstance(a,(list,tuple)): + assert len(a)==len(b),path + for i,(x,y) in enumerate(zip(a,b)):equal(x,y,path+'/'+str(i)) + else:assert a==b,(path,a,b) + +left=torch.load(root/'continuous/recovery.pt',map_location='cpu',weights_only=False) +right=torch.load(root/'resumed/recovery.pt',map_location='cpu',weights_only=False) +keys=['step','config','model','optimizer','ema_state','prefetched_batch','batch_rng_state','sampler_rng_state','sampler_rng_states','torch_rng_state','cuda_rng_state','parent_checkpoints'] +for key in keys:equal(left[key],right[key],key) +assert left['step']==6 and sum(t.numel() for t in left['model'].values())==6340 +assert len(left['optimizer']['state'])==len(left['model'])==6 +assert left['args']['fixed_expert_descriptor_sha256']=='a1b4ab426901be8e1ee299eeeb3f041bac7cea3d4e59c4608824fc3d05c83e03' +assert len(left['parent_checkpoints'])==4 +assert digest==hashlib.sha256(initial.read_bytes()).hexdigest() +result=dict(completed_utc=datetime.datetime.now(datetime.timezone.utc).isoformat(),fixture_seed=751,batch=4,training_schedule_steps=12000,continuous_steps=6,interruption_after=3,bitwise_equal_keys=keys,trainable_parameters=6340,optimizer_parameter_tensors=6,initial_checkpoint_sha256=digest,initial_checkpoint_unchanged=True,validation_data_read=False,selection_weights=False,optimizer_updates=12,processes=durations,lock_wait_seconds=wait,seconds=time.monotonic()-started) +(R/'ensemble_gate_factorial_recovery_checks.json').write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/describe_weights.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/describe_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..1c022ebf0a3e504983dd43cfde148b028b132b1f --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/describe_weights.py @@ -0,0 +1,84 @@ +"""Describe learned gate weights from existing expert caches; never fit a correction.""" +import argparse, datetime, hashlib, json, sys, time +from pathlib import Path + +import numpy as np +import torch + +from study import ARMS, EXPERTS +from model import DirectForecaster +from frequency import periods_for_freq +import ts_io + +R = Path('/workspace/research') +ap = argparse.ArgumentParser() +ap.add_argument('--step', type=int, choices=[6000, 12000], required=True) +ap.add_argument('--run', choices=list(ARMS), required=True) +a = ap.parse_args() +started = time.monotonic() +torch.set_num_threads(1) +torch.manual_seed(0) +checkpoint_path = R/'runs'/a.run/f'ema{a.step:06d}.pt' +checkpoint = torch.load(checkpoint_path, map_location='cpu', weights_only=False) +checkpoint_hash = hashlib.sha256(checkpoint_path.read_bytes()).hexdigest() +gate = DirectForecaster(**checkpoint['config']).eval() +gate.load_state_dict(checkpoint['model']) +expert_root, expert_id, baseline = EXPERTS[ARMS[a.run]['experts']] +assert checkpoint['args']['fixed_expert_descriptor_sha256'] == expert_id +panels = [] +for cutoff in ['valid_screen', 'valid_backcast', 'valid_backcast2', 'valid_backcast3']: + control = json.loads((R/f'{baseline}_{cutoff}.json').read_text()) + members = [Path(p) for p in control['members']] + for member, expected in zip(members, control['member_checkpoint_hashes']): + assert json.loads((member/'report.json').read_text())['checkpoint_sha256'] == expected + inp = R/cutoff/'input' + rows = [] + for cfg in json.loads((inp/'index.json').read_text())['configs']: + cid = cfg['config_id'] + case = ts_io.CaseFile(inp/'cases'/f'{cid}.h5') + n, d, h = case.n, case.n_variates, case.prediction_length + cached = [ts_io.read_prediction_file(p/'cases'/f'{cid}.h5')[1].reshape(n*d, 9, h) for p in members] + order = np.argsort(np.repeat(case.context_length, d), kind='stable') + sums = np.zeros(4, np.float64) + floors = np.zeros(4, np.int64) + ceilings = np.zeros(4, np.int64) + per_quarter = np.zeros((4, 4), np.float64) + quarter_counts = np.zeros(4, np.int64) + count = 0 + for start in range(0, n*d, 128): + ids = order[start:start+128] + length = min(4096, max(int(case.context_length[i//d]) for i in ids)) + x = np.full((len(ids), length), np.nan, np.float32) + for j, k in enumerate(ids): + context = case.context(int(k//d))[k % d, -length:] + x[j, -len(context):] = context + experts = np.stack([q[ids].transpose(0, 2, 1) for q in cached], axis=1) + with torch.no_grad(): + weights = gate(torch.from_numpy(x), torch.tensor([periods_for_freq(cfg['freq'])]*len(ids)), torch.from_numpy(experts), torch.full((len(ids),), h)).numpy() + assert np.isfinite(weights).all() and np.allclose(weights.sum(-1), 1, atol=2e-7) + assert weights.min() >= .125 and weights.max() <= .625 + sums += weights.sum(axis=(0, 1), dtype=np.float64) + floors += (weights <= .1251).sum(axis=(0, 1)) + ceilings += (weights >= .6249).sum(axis=(0, 1)) + count += len(ids)*h + for quarter, leads in enumerate(np.array_split(np.arange(h), 4)): + per_quarter[quarter] += weights[:, leads].sum(axis=(0, 1), dtype=np.float64) + quarter_counts[quarter] += len(ids)*len(leads) + case.close() + rows.append(dict(config_id=cid, term=cfg['term'], domain=cfg['domain'], frequency=cfg['freq'], + leads=count, mean_weights=(sums/count).tolist(), fraction_near_lower_bound=(floors/count).tolist(), + fraction_near_upper_bound=(ceilings/count).tolist(), lead_quarter_mean_weights=(per_quarter/quarter_counts[:, None]).tolist())) + groups = {} + for key in ['term', 'domain', 'frequency']: + groups[key] = {} + for value in sorted({row[key] for row in rows}): + selected = [row for row in rows if row[key] == value] + groups[key][value] = dict(configs=len(selected), **{field: np.mean([row[field] for row in selected], axis=0).tolist() for field in ['mean_weights', 'fraction_near_lower_bound', 'fraction_near_upper_bound', 'lead_quarter_mean_weights']}) + panels.append(dict(cutoff=cutoff, equal_configuration_mean_weights=np.mean([row['mean_weights'] for row in rows], axis=0).tolist(), groups=groups, configs=rows)) + print(json.dumps({k: panels[-1][k] for k in ['cutoff', 'equal_configuration_mean_weights']}), flush=True) +result = dict(utc=datetime.datetime.now(datetime.timezone.utc).isoformat(), gate_checkpoint_sha256=checkpoint_hash, + run=a.run, step=a.step, expert_descriptor_sha256=checkpoint['args']['fixed_expert_descriptor_sha256'], panels=panels, + seconds=time.monotonic()-started, optimizer_updates=0, new_expert_inference=False, labels_read=False, + note='Descriptive CPU gate evaluation on cached standalone expert forecasts and validation contexts. No forecast outputs, corrections, coefficients or parameters fitted. CPU gate arithmetic and cached neural batching are not claimed bitwise identical to production GPU execution. Group means give configurations equal weight; bound occupancy is descriptive, not a selection criterion.') +(R/f'{a.run}{a.step//1000}k_weight_structure.json').write_text(json.dumps(result, indent=2)) +print(json.dumps({k: v for k, v in result.items() if k != 'panels'}), flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/evaluate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..d122e067e37749779694cad1da3ba473b31c4d9d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/evaluate.py @@ -0,0 +1,26 @@ +"""Research-only E152 evaluator, resolving the immutable expert snapshot from the checkpoint.""" +import argparse, fcntl, hashlib, json, sys, time +from pathlib import Path +import torch +from predict import load_model, run +sys.path.insert(0, '/workspace/evaluation') +from score import score, json_safe + +ap = argparse.ArgumentParser() +for key in ['weights', 'out']:ap.add_argument('--'+key, required=True) +ap.add_argument('--experts') +ap.add_argument('--valid', default='/workspace/research/valid_screen') +ap.add_argument('--baseline', default='/workspace/research/valid_screen/baseline.json') +a = ap.parse_args() +checkpoint = torch.load(a.weights, map_location='cpu', weights_only=False) +experts = a.experts or checkpoint['args']['gate_package'] +lock = open('/workspace/research/.evaluation.lock', 'a'); fcntl.flock(lock, fcntl.LOCK_EX) +torch.set_num_threads(4); torch.manual_seed(0); torch.backends.cuda.matmul.allow_tf32 = False +started = time.monotonic(); out = Path(a.out); valid = Path(a.valid) +model = load_model(a.weights, experts); run(model, valid/'input', out) +report = score(valid/'truth', out, json.loads(Path(a.baseline).read_text())['configs']) +report['checkpoint_sha256'] = hashlib.sha256(Path(a.weights).read_bytes()).hexdigest() +report['expert_descriptor_sha256'] = model.experts.descriptor_sha256 +report['eval_seconds'] = time.monotonic()-started +(out/'report.json').write_text(json.dumps(json_safe(report), indent=1)) +print(json.dumps({k: report[k] for k in ['skill_score', 'rel_mase_gmean', 'rel_wql_gmean', 'n_failed', 'groups', 'eval_seconds']})) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/experts.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/experts.py new file mode 100644 index 0000000000000000000000000000000000000000..a03e8dc36a991a884eefb6429c7e650730716ff2 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/experts.py @@ -0,0 +1,57 @@ +"""Frozen declared E130 or E148 members with the exact packaged per-member inference transforms.""" +import hashlib,importlib.util,json +from pathlib import Path +import numpy as np +import torch + +def digest(path): + with Path(path).open('rb') as f:return hashlib.file_digest(f,'sha256').hexdigest() + +def module_from_file(name,path): + spec=importlib.util.spec_from_file_location(name,path);module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module);return module + +class FrozenExperts: + def __init__(self,package,device='cuda'): + root=Path(package);manifest=json.loads((root/'model_manifest.json').read_text());descriptor=json.loads((root/'config.json').read_text()) + assert manifest['pretrained_assets']==[] + self.descriptor_sha256=digest(root/'config.json') + assert self.descriptor_sha256==manifest['checkpoint_sha256'] + expected_parameters={'fa97880dd132b1cdff459be4798f8f360d7df59b13e78026a9d74a95d63df0db':256594744,'a1b4ab426901be8e1ee299eeeb3f041bac7cea3d4e59c4608824fc3d05c83e03':256643928} + assert self.descriptor_sha256 in expected_parameters + assert len(descriptor['members'])==4 and descriptor['weights']==[.25]*4 + self.models=[];self.checkpoints=[];self.member_hashes=[];self.device=torch.device(device) + for i,entry in enumerate(descriptor['members']): + path=root/entry['weights'];code=root/entry['model_code'];weight_hash=digest(path) + assert weight_hash==entry['weights_sha256'] and digest(code)==manifest['runtime_code_sha256'][code.name] + module=module_from_file('frozen_E130_model_'+str(i),code) + checkpoint=torch.load(path,map_location='cpu',weights_only=False) + model=module.DirectForecaster(**checkpoint['config']).to(device);model.load_state_dict(checkpoint['model']);model.eval();model.requires_grad_(False) + self.models.append(model);self.checkpoints.append(str(path.resolve()));self.member_hashes.append(weight_hash) + if i==0:self.periods_for_freq=module.periods_for_freq + transforms={} + for name in ['seasonal','continuity','zero_mass']: + path=root/(name+'.py');assert digest(path)==manifest['runtime_code_sha256'][path.name] + transforms[name]=module_from_file('frozen_E130_'+name,path) + self.apply_gate=transforms['seasonal'].apply_gate;self.apply_continuity=transforms['continuity'].apply_continuity;self.project=transforms['zero_mass'].project + self.parameters=sum(p.numel() for model in self.models for p in model.parameters());self.max_context=max(model.max_context for model in self.models) + assert self.parameters==manifest['parameters']==expected_parameters[self.descriptor_sha256] and self.max_context==4096 + + @torch.no_grad() + def __call__(self,ctx,periods,horizon,forecast_lengths=None): + assert ctx.device.type=='cuda' and not torch.backends.cuda.matmul.allow_tf32 + b=ctx.shape[0];context=ctx.detach().float().cpu().numpy();p_np=periods.detach().cpu().numpy();forecasts=[] + for member in self.models: + member_x=ctx[:,-member.max_context:];member_ctx=context[:,-member.max_context:] + rule_context=getattr(member,'rule_context',member.max_context);rule_x=member_x[:,-rule_context:];rule_ctx=member_ctx[:,-rule_context:] + lengths=None if forecast_lengths is None else forecast_lengths.repeat(2) + with torch.autocast('cuda',dtype=torch.bfloat16): + q,mu,scale=member(torch.cat((member_x,-member_x),0),periods.repeat(2,1),horizon,forecast_lengths=lengths) + q=q*scale[:,:,None]+mu[:,:,None];q=(q[:b]-q[b:].flip(-1))*.5 + recent=rule_x[:,-4096:];positive=((recent>=0)|~torch.isfinite(recent)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + q=q.transpose(1,2).float().cpu().numpy() + q=self.apply_gate(rule_ctx[:,-4096:],p_np,q) + q=self.project(rule_ctx,self.apply_continuity(rule_ctx,q)) + forecasts.append(np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20)) + result=np.stack(forecasts,axis=1).transpose(0,1,3,2).copy() + return torch.from_numpy(result).to(ctx.device) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/frequency.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/frequency.py new file mode 100644 index 0000000000000000000000000000000000000000..bdeffd8b2d20972fa082c6875d5e16e0a9e21f1f --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/frequency.py @@ -0,0 +1,14 @@ +"""Frequency mapping copied verbatim from our own E80 model.""" +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/interaction.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/interaction.py new file mode 100644 index 0000000000000000000000000000000000000000..2059894bc62d709a5e8fe941e51b7af5d3616765 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/interaction.py @@ -0,0 +1,26 @@ +"""Describe the predeclared E152 two-factor interaction without fitting forecasts.""" +import argparse, datetime, json, math, time +from study import ARMS, EXPERTS, PANELS, R + +ap=argparse.ArgumentParser();ap.add_argument('--step',type=int,choices=[6000,12000],required=True);a=ap.parse_args() +started=time.monotonic();rows=[] +cells=['ensemble_gate','ensemble_gate_refresh','ensemble_gate_full','ensemble_gate_refresh_full'] +def error(report):return .5*(math.log(report['rel_mase_gmean'])+math.log(report['rel_wql_gmean'])) +def contrast(values):return values[3]-values[1]-values[2]+values[0] +for cutoff,folder in PANELS: + reports=[json.loads((R/folder/f'{name}_ema{a.step}'/'report.json').read_text()) for name in cells] + assert all(report['n_failed']==0 for report in reports) + assert all([cfg['config_id'] for cfg in report['configs']]==[cfg['config_id'] for cfg in reports[0]['configs']] for report in reports) + assert [report['expert_descriptor_sha256'] for report in reports]==[EXPERTS['E130'][1],EXPERTS['E148'][1],EXPERTS['E130'][1],EXPERTS['E148'][1]] + logerrors=list(map(error,reports)) + groups={key:{group:contrast([error(report['groups'][key][group]) for report in reports]) for group in reports[0]['groups'][key]} for key in ['term','domain','frequency']} + rows.append(dict(cutoff=cutoff,cell_skills={name:report['skill_score'] for name,report in zip(cells,reports)}, + checkpoint_hashes={name:report['checkpoint_sha256'] for name,report in zip(cells,reports)}, + corpus_effect_logerror_old_experts=logerrors[2]-logerrors[0],corpus_effect_logerror_new_experts=logerrors[3]-logerrors[1], + expert_refresh_effect_logerror_old_pack=logerrors[1]-logerrors[0],expert_refresh_effect_logerror_full_pack=logerrors[3]-logerrors[2], + interaction_logerror=contrast(logerrors),group_interactions_logerror=groups)) +result=dict(utc=datetime.datetime.now(datetime.timezone.utc).isoformat(),step=a.step,cells=cells,rows=rows, + mean_interaction_logerror=sum(row['interaction_logerror'] for row in rows)/4, + seconds=time.monotonic()-started,optimizer_updates=0,new_inference=False, + note='Predeclared factorial interaction: (new experts/full pack minus new experts/old pack) minus (old experts/full pack minus old experts/old pack), on log geometric relative error. Negative indicates a larger corpus benefit with refreshed experts. Descriptive adaptive-validation result, not a significance test or causal attribution beyond these fixed contrasts. No fitted corrections or changed forecasts.') +(R/f'ensemble_gate_factorial{a.step//1000}k_interaction.json').write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/launch.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..5c90365270193a427b041ea1e1b6e47ba62724d9 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/launch.py @@ -0,0 +1,45 @@ +"""Queue the three audited E152 cells sequentially after E149, retaining six allocations.""" +import hashlib, json, os, subprocess +from study import ARMS, EXPERTS, INITIAL_SHA, R + +initial=R/'ensemble_gate_initial.pt' +assert hashlib.sha256(initial.read_bytes()).hexdigest()==INITIAL_SHA +cpu=json.loads((R/'ensemble_gate_factorial_cpu_checks.json').read_text()) +gpu=json.loads((R/'ensemble_gate_factorial_gpu_checks.json').read_text()) +recovery=json.loads((R/'ensemble_gate_factorial_recovery_checks.json').read_text()) +relocation=json.loads((R/'ensemble_gate_factorial_initial_package_checks.json').read_text()) +assert cpu['all95_sources_and_probabilities_identical'] and cpu['original_old_pack_stream_bitwise'] +assert gpu['all_gate_layers_finite_nonzero_gradients'] and gpu['experts_have_no_gradients'] and gpu['initial_checkpoint_unchanged'] +assert 'optimizer' in recovery['bitwise_equal_keys'] and 'prefetched_batch' in recovery['bitwise_equal_keys'] +assert all(v['all_four_experts_bitwise'] and v['initial_ensemble_bitwise'] for v in gpu['synthetic_replay_checks']) +assert sum(v['configurations'] for v in relocation)==3 and all(v['bitwise_equal_after_relocation'] for v in relocation) +dependency=json.loads((R/'integrated_level_queue.json').read_text())['launcher_pid'] +required=R/'runs/integrated_level/ema012000.pt' +env=dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1') +processes=[]; launched=[] +for name, arm in ARMS.items(): + run=R/'runs'/name + assert not run.exists() and not (R/f'{name}_queue.json').exists(), name + package=R/EXPERTS[arm['experts']][0] + command=['python3',str(R/'recovery/train.py'),'--code-dir',str(R/'ensemble_gate_factorial'), + '--packed',str(R/arm['pack']),'--source-weights-from',str(R/'packed_sample'),'--out',str(run), + '--initialize-from',str(initial),'--steps','12000','--batch','64','--lr','.001','--seed','751', + '--loss-mode','paired','--gate-package',str(package),'--stop-file',str(R/f'{name}.stop')] + with (R/f'{name}_queue.log').open('w') as qlog, (R/f'{name}_watch.log').open('w') as wlog, (R/f'{name}_selection.log').open('w') as clog: + queue=subprocess.Popen(['python3',str(R/'queued_train.py'),'--label','E152 '+name+' seed751', + '--log',str(R/f'{name}_train.log'),'--receipt',str(R/f'{name}_queue.json'),'--wait-pid',str(dependency), + '--require-checkpoint',str(required),'--',*command],stdout=qlog,stderr=subprocess.STDOUT,env=env) + watch=subprocess.Popen(['python3',str(R/'watch_evaluate.py'),'--run',str(run),'--evaluator',str(R/'ensemble_gate_factorial/evaluate.py'), + '--name',name,'--expected-packed',str(R/arm['pack']),'--steps','1000,3000,6000,12000'],stdout=wlog,stderr=subprocess.STDOUT,env=env) + controller=subprocess.Popen(['python3',str(R/'ensemble_gate_factorial/watch_selection.py'),'--run',name],stdout=clog,stderr=subprocess.STDOUT,env=env) + processes.append((queue,watch,controller)); launched.append(dict(name=name,queue_pid=queue.pid,watch_pid=watch.pid,selection_pid=controller.pid,wait_pid=dependency,required_checkpoint=str(required))) + dependency=queue.pid; required=run/'ema012000.pt' +(R/'ensemble_gate_factorial_launch_receipt.json').write_text(json.dumps(launched,indent=2)) +print(json.dumps(launched),flush=True) +code=0 +for queue,watch,controller in processes: + result=queue.wait();code=code or result + if result:watch.terminate();controller.terminate() + watch_result=watch.wait();controller_result=controller.wait() + code=code or watch_result or controller_result +raise SystemExit(code) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/model.py new file mode 100644 index 0000000000000000000000000000000000000000..f0db533af0eae9b8fa38689ba459ad7b5c8a392f --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/model.py @@ -0,0 +1,97 @@ +"""A small fixed-parameter gate over four frozen scratch-trained forecasting experts.""" +import torch +from torch import nn +from torch.nn import functional as F +from normalization import standardize as original_standardize +from frequency import periods_for_freq + +FEATURE_NAMES=['log_finite_count','log_period0','log_period1','log_horizon','lead_fraction','log_lead','finite_fraction','log_absdiff_lag1','log_absdiff_period0','log_absdiff_period1','adjacent_mean4','adjacent_mean16','adjacent_mean128']+[f'{kind}_expert{i}' for kind in ['median_from_consensus','log_width80','median_from_last','median_from_mean32'] for i in range(4)] +assert len(FEATURE_NAMES)==29 + +def statistics(ctx): + ctx=ctx[:,-4096:];ctx=F.pad(ctx,((-ctx.shape[1])%16,0),value=float('nan')) + z,valid,mu,scale=original_standardize(ctx) + # Preserve ordinary arithmetic, and keep gate inputs defined at float32 extremes. + z=torch.nan_to_num(z,nan=0.,posinf=30.,neginf=-30.) + mu=torch.nan_to_num(mu,nan=0.,posinf=0.,neginf=0.) + scale=torch.where(torch.isfinite(scale)&(scale>0),scale,torch.ones_like(scale)) + return z,valid,mu,scale + +def gate_features(ctx,periods,expert_quantiles,lengths): + """Expert quantiles are final raw-scale (batch,4,horizon,9) forecasts.""" + assert expert_quantiles.shape[1]==4 and expert_quantiles.shape[-1]==9 + z,valid,mu,scale=statistics(ctx);b,c=z.shape;h=expert_quantiles.shape[2] + lengths=lengths.clamp(min=1,max=h);position=torch.arange(c,device=z.device)[None,:] + count=valid.sum(-1);first=torch.where(valid,position,c).min(-1).values;span=c-first + context=[count.float().log1p()/8,periods[:,0].float().log1p()/8,periods[:,1].float().log1p()/8] + context.append(lengths.float().log1p()/8) + lead=torch.arange(h,device=z.device).float()[None,:] + pieces=[torch.stack(context,-1)[:,None,:].expand(-1,h,-1),((lead+.5)/lengths[:,None]).clamp(max=1)[:,:,None],(lead+1).log1p().expand(b,-1)[:,:,None]/8,(count/span.clamp(min=1)).float()[:,None,None].expand(-1,h,-1)] + differences=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + index=position-lag;safe=index.clamp(min=0,max=c-1) + pairs=(index>=0)&(position>=c-window)&valid&valid.gather(1,safe) + n=pairs.sum(-1);absolute=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/n.clamp(min=1) + absolute=torch.where(n>=8,absolute,1.) + differences.append(absolute.clamp(max=10).log1p()) + adjacent=[] + for k in (4,16,128): + vr=valid[:,-k:];vo=valid[:,-2*k:-k];nr=vr.sum(-1);no=vo.sum(-1) + recent=(z[:,-k:]*vr).sum(-1)/nr.clamp(min=1) + older=(z[:,-2*k:-k]*vo).sum(-1)/no.clamp(min=1) + active=(nr>=max(2,k//2))&(no>=max(2,k//2)) + adjacent.append(torch.where(active,(recent-older).abs().clamp(max=30),0.)) + pieces.extend([torch.stack(differences,-1)[:,None,:].expand(-1,h,-1),torch.stack(adjacent,-1)[:,None,:].expand(-1,h,-1)]) + # Expert disagreement can subtract large, nearly equal normalized medians. + # Compute these fixed features in float64, then feed the small gate float32. + normalized=(expert_quantiles.double()-mu.double()[:,None,None,:])/scale.double()[:,None,None,:] + median=normalized[:,:,:,4].transpose(1,2) + consensus=(median[:,:,0]+median[:,:,1]+median[:,:,2]+median[:,:,3])/4 + last_index=torch.where(valid,position,-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_index[:,None])[:,0] + mean32=(z[:,-32:]*valid[:,-32:]).sum(-1)/valid[:,-32:].sum(-1).clamp(min=1) + pieces.extend([(median-consensus[:,:,None]).abs().clamp(max=30),(normalized[:,:,:,8]-normalized[:,:,:,0]).transpose(1,2).clamp(0,60).log1p(),(median-last[:,None,None]).abs().clamp(max=30),(median-mean32[:,None,None]).abs().clamp(max=30)]) + features=torch.cat(pieces,-1).float();assert features.shape==(b,h,29) + return torch.nan_to_num(features,nan=0.,posinf=30.,neginf=0.).clamp(0,30) + +def combine(expert_quantiles,weights): + """Same positive weight across all quantiles at each lead; fixed ordered accumulation.""" + q=expert_quantiles[:,0]*weights[:,:,0,None] + for i in range(1,4):q=q+expert_quantiles[:,i]*weights[:,:,i,None] + q=torch.nan_to_num(q,nan=0.,posinf=1e20,neginf=-1e20) + return q.cummax(-1).values + +class DirectForecaster(nn.Module): + def __init__(self,input_dim=29,hidden=64,members=4,mixing=.5,max_context=4096): + super().__init__();assert input_dim==29 and members==4 and mixing==.5 and max_context==4096 + self.max_context=max_context;self.mixing=mixing + self.config=dict(input_dim=input_dim,hidden=hidden,members=members,mixing=mixing,max_context=max_context) + self.net=nn.Sequential(nn.Linear(input_dim,hidden),nn.GELU(),nn.Linear(hidden,hidden),nn.GELU(),nn.Linear(hidden,members)) + nn.init.zeros_(self.net[-1].weight);nn.init.zeros_(self.net[-1].bias) + def forward(self,ctx,periods,expert_quantiles,lengths): + with torch.autocast(device_type=ctx.device.type,enabled=False): + features=gate_features(ctx.float(),periods,expert_quantiles.float(),lengths) + return .125+.5*self.net(features).softmax(-1) + +def loss_fn(model,ctx,target,periods,expert_quantiles,paired=True): + assert paired + with torch.autocast(device_type=ctx.device.type,enabled=False): + valid=torch.isfinite(target);pos=torch.arange(target.shape[-1],device=ctx.device)[None,:]+1 + lengths=torch.where(valid,pos,0).max(-1).values.clamp(min=1) + weights=model(ctx,periods,expert_quantiles,lengths) + prediction=combine(expert_quantiles.float(),weights) + z,seen,mu,scale=statistics(ctx) + q=(prediction-mu[:,:,None])/scale[:,:,None] + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + error=y[:,:,None]-q;levels=torch.arange(1,10,device=q.device)/10 + pin=.5*torch.maximum(levels*error,(levels-1)*error).mean(-1)+.25*error[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + with torch.no_grad(): + c=z.shape[-1];position=torch.arange(c,device=z.device)[None,:];lag=periods[:,0:1].clamp(min=1);index=position-lag;safe=index.clamp(min=0) + pairs=(index>=0)&seen&seen.gather(1,safe);count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/normalization.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/normalization.py new file mode 100644 index 0000000000000000000000000000000000000000..f1cfec8685b97bc4c979e1daf9c9a3013a136d6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/normalization.py @@ -0,0 +1,21 @@ +"""Canonical normalization copied from our own E79 model; no learned statistics.""" +import torch + +def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..f9a2b45d1347fcb2a14b183c8a9d31ac6ea34d52 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/predict.py @@ -0,0 +1,46 @@ +"""Deterministic forecasts with four frozen experts and a fixed learned convex gate.""" +import argparse,json,time +from pathlib import Path +import numpy as np +import torch +from model import DirectForecaster,combine +from experts import FrozenExperts +import ts_io +HERE=Path(__file__).resolve().parent + +def load_model(weights,expert_package=None): + from types import SimpleNamespace + ck=torch.load(weights,map_location='cpu',weights_only=False) + gate=DirectForecaster(**ck['config']).cuda();gate.load_state_dict(ck['model']);gate.eval() + experts=FrozenExperts(expert_package or HERE/'experts') + expected=ck.get('args',{}).get('fixed_expert_descriptor_sha256') + if expected:assert expected==experts.descriptor_sha256 + return SimpleNamespace(gate=gate,experts=experts,max_context=4096) + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.monotonic() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/(cid+'.h5'));n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32);order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];length=min(model.max_context,max(int(case.context_length[i//d]) for i in ids));context=np.full((len(ids),length),np.nan,np.float32) + for j,k in enumerate(ids): + values=case.context(int(k//d))[k%d,-length:];context[j,-len(values):]=values + x=torch.from_numpy(context).cuda();periods=torch.tensor([model.experts.periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + experts=model.experts(x,periods,h) + with torch.no_grad(): + weights=model.gate(x,periods,experts,torch.full((len(ids),),h,device=x.device)) + q=combine(experts,weights).transpose(1,2).cpu().numpy() + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/(cid+'.h5'),quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.monotonic()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'gate.pt'));ap.add_argument('--experts',default=str(HERE/'experts'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False;torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights,a.experts),a.input,a.output,a.batch) +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/prepare.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/prepare.py new file mode 100644 index 0000000000000000000000000000000000000000..fb02581da69aa068f3c41eb7ac427c8a3489661c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/prepare.py @@ -0,0 +1,42 @@ +"""Freeze E148 and prepare the unchanged E138 gate for the declared E152 factorial.""" +import datetime, hashlib, json, shutil, time +from pathlib import Path + +R = Path('/workspace/research'); HERE = Path(__file__).resolve().parent +started = time.monotonic() +def digest(path): + with Path(path).open('rb') as f: + return hashlib.file_digest(f, 'sha256').hexdigest() +source = R/'candidate-width12-fresh96-ensemble' +target = R/'gating_experts_E148' +expected = 'a1b4ab426901be8e1ee299eeeb3f041bac7cea3d4e59c4608824fc3d05c83e03' +assert not target.exists() +manifest = json.loads((source/'model_manifest.json').read_text()) +assert digest(source/'config.json') == manifest['checkpoint_sha256'] == expected +assert manifest['parameters'] == 256643928 and manifest['pretrained_assets'] == [] +for name, value in manifest['runtime_code_sha256'].items(): + assert digest(source/name) == value +for member in manifest['members']: + assert digest(source/member['weights']) == member['weights_sha256'] +shutil.copytree(source, target, ignore=shutil.ignore_patterns('__pycache__', '*.pyc')) +for name, value in manifest['runtime_code_sha256'].items(): + assert digest(target/name) == value +for member in manifest['members']: + assert digest(target/member['weights']) == member['weights_sha256'] +identical = {} +for name in ['model.py', 'data.py', 'normalization.py', 'frequency.py', 'predict.py', 'infer.sh', 'ts_io.py']: + shutil.copy2(R/'ensemble_gate'/name, HERE/name) + identical[name] = digest(HERE/name) + assert identical[name] == digest(R/'ensemble_gate'/name) +text = (R/'ensemble_gate/experts.py').read_text() +text = text.replace('Frozen E130 members', 'Frozen declared E130 or E148 members') +text = text.replace("assert self.descriptor_sha256==manifest['checkpoint_sha256']=='fa97880dd132b1cdff459be4798f8f360d7df59b13e78026a9d74a95d63df0db'", "assert self.descriptor_sha256==manifest['checkpoint_sha256']\n expected_parameters={'fa97880dd132b1cdff459be4798f8f360d7df59b13e78026a9d74a95d63df0db':256594744,'a1b4ab426901be8e1ee299eeeb3f041bac7cea3d4e59c4608824fc3d05c83e03':256643928}\n assert self.descriptor_sha256 in expected_parameters") +text = text.replace('assert self.parameters==256594744 and self.max_context==4096', "assert self.parameters==manifest['parameters']==expected_parameters[self.descriptor_sha256] and self.max_context==4096") +(HERE/'experts.py').write_text(text) +receipt = dict(utc=datetime.datetime.now(datetime.timezone.utc).isoformat(), immutable_experts=str(target), + expert_descriptor_sha256=expected, expert_parameters=manifest['parameters'], + copied_expert_hashes=[v['weights_sha256'] for v in manifest['members']], + files_byte_identical_to_E138=identical, original_E130_and_E101_assets_untouched=True, + seconds=time.monotonic()-started, optimizer_updates=0) +(R/'ensemble_gate_factorial_preparation.json').write_text(json.dumps(receipt, indent=2)) +print(json.dumps(receipt), flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/promote.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/promote.py new file mode 100644 index 0000000000000000000000000000000000000000..723e658b549cae2d5a67db81e901ae64b08ca946 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/promote.py @@ -0,0 +1,57 @@ +"""Publish only a fully checked gate package that improves the current publication.""" +import argparse,datetime,hashlib,json,os,subprocess +from pathlib import Path +from study import ARMS,EXPERTS +R=Path('/workspace/research');ap=argparse.ArgumentParser();ap.add_argument('--step',type=int,choices=[6000,12000],required=True);ap.add_argument('--run',choices=list(ARMS),required=True);a=ap.parse_args() +step=a.step;prefix=f'{a.run}_{step}';slug=prefix.replace('_','-');package=R/f'candidate-{slug}' +expert_root,expert_id,baseline=EXPERTS[ARMS[a.run]['experts']] +read=lambda path:json.loads(path.read_text()) +report_path=R/f'valid-report-{slug}.json';report=read(report_path);validated=read(package/'model_manifest.json') +suite=read(R/(prefix+'_validation_receipt.json'));runtime=read(R/(prefix+'_runtime_checks.json'));relocation=read(R/(prefix+'_package_checks.json')) +assert suite['status']=='complete' and all(x['returncode']==0 for x in suite['steps']) +assert runtime['status']=='complete' and runtime['descriptor_sha256']==validated['checkpoint_sha256']==report['checkpoint_sha256'] +assert runtime['gate_weights_sha256']==validated['gate_weights_sha256'] +assert len(runtime['checks'])==2 and sum(len(v['checks']) for v in runtime['checks'])==5 +assert all(row['bitwise_independent_composition'] and row['finite_ordered'] for item in runtime['checks'] for row in item['checks']) +assert sum(x['configurations'] for x in relocation)==3 and all(x['bitwise_equal_after_relocation'] and x['finite_and_monotone'] for x in relocation) +assert validated['pretrained_assets']==[] and validated['every_member_forecasts_every_instance'] +assert validated['gate_training_step']==step and validated['parameters']==read(R/expert_root/'model_manifest.json')['parameters']+6340 +assert validated['expert_descriptor_sha256']==expert_id +state=read(R/'CURRENT_RESEARCH_STATE.json');current=state['published'] +old=read(Path('/workspace/submission/validation_report.json'));old_manifest=read(Path('/workspace/submission/model_manifest.json')) +assert current['checkpoint_sha256']==old_manifest['checkpoint_sha256'] +assert report['n_configs']==97 and report['n_instances']==151170 and report['n_failed']==0 +assert report['skill_score']>old['skill_score'] +selection=next(v for v in read(R/f'{a.run}_selection_receipt.json')['results'] if v['step']==step) +assert selection['selection_gate_passed'] +differences=[row['skill']-prior for row,prior in zip(selection['rows'],[current['main_skill']]+current['earlier_skills'])] +assert len(differences)==4 and sum(x>0 for x in differences)>=3 and sum(differences)>0 +for name,digest in validated['runtime_code_sha256'].items(): + source=R/expert_root/name.removeprefix('experts/') if name.startswith('experts/') else R/'ensemble_gate_factorial'/name + assert hashlib.sha256(source.read_bytes()).hexdigest()==digest +weights=R/'runs'/a.run/f'ema{step:06d}.pt' +assert hashlib.sha256(weights.read_bytes()).hexdigest()==validated['gate_weights_sha256'] +outcome=f"Only6340gateparameters learned from allowed training data, with all four {ARMS[a.run]["experts"]}experts frozen. Full validation improves from {old['skill_score']:.12f} to {report['skill_score']:.12f}; all97configs151170instances pass. Inference {report['inference_seconds']:.3f}s sharedH100. Independent standalone composition and relocation are exact. Validation selection only, not held-out reward." +subprocess.run(['python3',str(R/'direct_v1/record.py'),str(report_path),'--label',f'E152 {a.run} learned gate{step} full replay selected','--outcome',outcome],check=True) +subprocess.run(['python3',str(R/'compare_reports.py'),'--candidate',str(report_path),'--parent',current['full_report'],'--out',str(R/(prefix+'_current_publication_comparison.json'))],check=True) +comparison=read(R/(prefix+'_current_publication_comparison.json')) +with (R/'direct_v1/EXPERIMENTS.md').open('a') as f: + f.write('\nE152 fullsuite '+json.dumps(suite)+'. Runtime composition '+json.dumps(runtime)+'. Current-publication cutoff deltas '+json.dumps(differences)+'. Descriptive comparison '+json.dumps({k:v for k,v in comparison.items() if k!='configs'})+'. E101teacher/E138experts remain immutable.\n') +command=['python3',str(R/'ensemble_gate_factorial/publish.py'),'--weights',str(weights),'--report',str(report_path),'--out','/workspace/submission','--experts',str(R/expert_root)] +subprocess.run(command,check=True) +published=read(Path('/workspace/submission/model_manifest.json')) +assert published['checkpoint_sha256']==validated['checkpoint_sha256'] and published['runtime_code_sha256']==validated['runtime_code_sha256'] +now=datetime.datetime.now(datetime.timezone.utc).isoformat();state=read(R/'CURRENT_RESEARCH_STATE.json') +state.setdefault('previous_published',[]).append(state['published']) +state['published']=dict(experiment=f'E152 {a.run} learned bounded gate{step} over immutable {ARMS[a.run]["experts"]}experts',package='/workspace/submission', + checkpoint_sha256=report['checkpoint_sha256'],parameters=published['parameters'], + main_skill=selection['rows'][0]['skill'],earlier_skills=[x['skill'] for x in selection['rows'][1:]], + full_validation_skill=report['skill_score'],full_report=str(report_path),status='published after complete replay and independent composition', + publisher=command[1],publisher_arguments=command[2:],published_utc=now,journal_refreshed_utc=now, + validation_receipt=str(R/(prefix+'_validation_receipt.json')),package_checks=str(R/(prefix+'_package_checks.json')), + composition_checks=str(R/(prefix+'_runtime_checks.json')),notes='All experts forecast every instance; fixed learned gate, no inference updates. Validation only.') +state['prepared_research']['E152'].setdefault('publications',[]).append(dict(run=a.run,step=step,full_skill=report['skill_score'],published_utc=now,descriptor=report['checkpoint_sha256'])) +state['next_candidate']=dict(experiment='active matched model and data studies',status='continue research') +p=R/'CURRENT_RESEARCH_STATE.json';tmp=p.with_suffix('.tmp');tmp.write_text(json.dumps(state,indent=2));os.replace(tmp,p) +with (R/'SESSION_20261023_PROGRESS.md').open('a') as f:f.write('\n'+now+': E152 '+a.run+' gate'+str(step)+' atomically published. '+outcome+' Descriptor '+report['checkpoint_sha256']+'.\n') +print(json.dumps(dict(utc=now,step=step,skill=report['skill_score'],descriptor=report['checkpoint_sha256'])),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..0c0a8e12a19aa5e67b7e528ac169bf723b59d7f5 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/publish.py @@ -0,0 +1,72 @@ +"""E152 portable package for a scratch-trained gate and its four immutable scratch experts.""" +import argparse,ctypes,hashlib,json,os,shutil +from pathlib import Path +import torch + +HERE=Path(__file__).resolve().parent;R=HERE.parent +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);ap.add_argument('--report');ap.add_argument('--experts',required=True);a=ap.parse_args() +def digest(path): + with Path(path).open('rb') as f:return hashlib.file_digest(f,'sha256').hexdigest() + +source=Path(a.experts);expert_manifest=json.loads((source/'model_manifest.json').read_text()) +expert_id=digest(source/'config.json');assert expert_id==expert_manifest['checkpoint_sha256'] and expert_id in ('fa97880dd132b1cdff459be4798f8f360d7df59b13e78026a9d74a95d63df0db','a1b4ab426901be8e1ee299eeeb3f041bac7cea3d4e59c4608824fc3d05c83e03') +assert expert_manifest['pretrained_assets']==[] +for name,value in expert_manifest['runtime_code_sha256'].items():assert digest(source/name)==value +for member in expert_manifest['members']:assert digest(source/member['weights'])==member['weights_sha256'] +checkpoint=torch.load(a.weights,map_location='cpu',weights_only=False);step=checkpoint.get('step',0);args=checkpoint.get('args',{}) +assert sum(v.numel() for v in checkpoint['model'].values())==6340 +if step: + assert args['seed']==751 and args['batch']==64 and args['steps']==12000 + assert args['fixed_expert_descriptor_sha256']==expert_id + assert args['fixed_expert_checkpoint_sha256']==[m['weights_sha256'] for m in expert_manifest['members']] +else:assert digest(a.weights)=='9d1401cd4d5b5f1c3ddd25a4a74e15e5db7ef708116cdf5c4fa7e90580b58da1' +final=Path(a.out);stage=final.parent/f'.{final.name}-staging-{os.getpid()}';assert not stage.exists();stage.mkdir(parents=True) +runtime=['infer.sh','predict.py','model.py','experts.py','frequency.py','normalization.py','ts_io.py'] +for name in runtime:shutil.copy2(HERE/name,stage/name) +shutil.copytree(source,stage/'experts',ignore=shutil.ignore_patterns('__pycache__','*.pyc')) +shutil.copy2(a.weights,stage/'gate.pt');gate_hash=digest(stage/'gate.pt') +shutil.copy2('/opt/runtime/requirements.txt',stage/'requirements.txt') +shutil.copy2(R/'direct_v1/EXPERIMENTS.md',stage/'EXPERIMENTS.md') +provenance=stage/'provenance';(provenance/'ensemble_gate_factorial').mkdir(parents=True) +for path in HERE.glob('*.py'):shutil.copy2(path,provenance/'ensemble_gate_factorial'/path.name) +(provenance/'recovery').mkdir() +for name in ['train.py','schedules.py']:shutil.copy2(R/'recovery'/name,provenance/'recovery'/name) +shutil.copy2(R/'ensemble_gate_initial.pt',provenance/'gate_initial.pt') +for name in ['ensemble_gate_factorial_preparation.json','ensemble_gate_factorial_cpu_checks.json','ensemble_gate_factorial_gpu_checks.json','ensemble_gate_factorial_recovery_checks.json']: + if (R/name).exists():shutil.copy2(R/name,provenance/name) +sources=set(expert_manifest['sources_used']) +if step: + meta=json.loads((Path(args['packed'])/'meta.json').read_text()) + sources.update('gifteval_pretrain/'+name for name in meta['dirs']) + sources.update(['synthetic:own direct_v1 Fourier seasons, damped trends, AR noise with coefficient uniform(0.2,0.995), changepoints and intermittent demand; gate training seed 751', + 'synthetic:independent sign reflection of allowed-corpus and locally generated windows; gate training seed 751', + 'synthetic:own random requested-horizon prefixes, half full and half patch-rounded one-quarter to full; gate training independent seed 300754']) + shutil.copy2(Path(args['packed'])/'meta.json',provenance/'gate_corpus_metadata.json') +descriptor=dict(gate=dict(weights='gate.pt',weights_sha256=gate_hash,parameters=6340,config=checkpoint['config']),experts=dict(package='experts',descriptor_sha256=expert_id),composition='per-lead 0.125+0.5*softmax(logits), same weights across all nine quantiles; ordered float32 weighted sum then monotone cumulative maximum') +(stage/'config.json').write_text(json.dumps(descriptor,indent=2)+'\n');identifier=digest(stage/'config.json') +members=[{**m,'weights':'experts/'+m['weights'],'model_code':'experts/'+m['model_code']} for m in expert_manifest['members']] +lineage=list(expert_manifest['training_lineage'])+[dict(sha256=digest(R/'ensemble_gate_initial.pt'),step=0,role='local gate random initialization, seed751')] +if step:lineage.append(dict(sha256=gate_hash,step=step,role='gate trained on allowed corpus and own synthetic generator; four experts frozen')) +manifest=dict(name='bounded-ensemble-gate-factorial-foundation',contract='timeseries-forecast/v1',parameters=expert_manifest['parameters']+6340,pretrained_assets=[],sources_used=sorted(sources),members=members,gate_parameters=6340,gate_weights='gate.pt',gate_weights_sha256=gate_hash,gate_config=checkpoint['config'],gate_training_step=step,gate_training_args=args,checkpoint_sha256=identifier,checkpoint_digest_method='SHA-256 of config.json including gate and frozen expert hashes',expert_descriptor_sha256=expert_id,training_lineage=lineage,every_member_forecasts_every_instance=True,gate_weight_rule=descriptor['composition'],runtime_code_sha256={name:digest(stage/name) for name in runtime},notes='All forecasting experts and gate originate from local random initialization. Fixed learned context-based gate; all experts forecast all instances; no test-time updates or adaptation. Validation is selection/diagnostics only.') +manifest['runtime_code_sha256'].update({'experts/'+k:v for k,v in expert_manifest['runtime_code_sha256'].items()}) +(stage/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') +if a.report: + report=json.loads(Path(a.report).read_text());assert report['checkpoint_sha256']==identifier + shutil.copy2(a.report,stage/'validation_report.json') +else:(stage/'validation_report.json').write_text(json.dumps(dict(status='private candidate; full package validation pending'))+'\n') +if final.resolve()==Path('/workspace/submission').resolve(): + assert a.report and step>0 and report['n_configs']==97 and report['n_instances']==151170 and report['n_failed']==0 +(stage/'README.md').write_text('''# Frozen expert ensemble with a learned bounded gate + +Run `bash infer.sh INPUT_DIR OUTPUT_DIR`. All runtime assets are included; requirements.txt pins the provided runtime. The package contains four scratch-trained forecasters and a 6,340-parameter gate; model_manifest.json records the exact total for this immutable expert set. Every expert forecasts every instance. The experts retain their original normalization, sign averaging and fixed seasonal, continuity, positivity and zero-mass rules. + +The gate uses 29 statistics of each instance's latest 4,096 observations, requested horizon and four expert forecasts. Its two 64-unit hidden layers produce four positive weights per lead, bounded between 0.125 and 0.625 and summing to one. The same weights combine all nine quantiles at a lead. A cumulative maximum removes possible floating-point quantile crossings. The gate runs in float32, fixed features use float64 where necessary, and expert neural forecasts use bfloat16. Parameters remain fixed at inference; no fitting, updates, external data or cross-instance information is used. + +model_manifest.json records all training sources, ordered expert and gate hashes, lineage and runtime code hashes. config.json uses relative asset paths. The experts/ directory contains their complete portable package and original provenance; provenance/ records the gate trainer, generator and engineering checks. Normalization needs only the supplied context and no external statistics. EXPERIMENTS.md includes negative results, compute and validation diagnostics. Validation skill is not the held-out reward scale. +''') +if final.exists(): + libc=ctypes.CDLL(None,use_errno=True) + if libc.renameat2(-100,os.fsencode(stage),-100,os.fsencode(final),2):raise OSError(ctypes.get_errno(),os.strerror(ctypes.get_errno())) + shutil.rmtree(stage) +else:os.replace(stage,final) +print(json.dumps(dict(out=str(final),checkpoint_sha256=identifier,gate_weights_sha256=gate_hash,parameters=manifest['parameters'],step=step))) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/review_selection.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/review_selection.py new file mode 100644 index 0000000000000000000000000000000000000000..b7eb94e89285719812356969843a6ae1f9e0f9a8 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/review_selection.py @@ -0,0 +1,108 @@ +"""Summarize declared E152 selection endpoints against frozen and current forecasts.""" +import argparse +import datetime +import hashlib +import json +import math +import sys +import time + +from study import ARMS, EXPERTS, PANELS, R + +sys.path.insert(0, '/workspace/evaluation') +import ts_io + +ap = argparse.ArgumentParser() +ap.add_argument('--run', choices=list(ARMS), required=True) +ap.add_argument('--step', choices=[6000, 12000], type=int, required=True) +ap.add_argument('--current-probe-prefix', required=True) +a = ap.parse_args() +started = time.monotonic() +output = R / f'{a.run}{a.step // 1000}k_selection_review.json' +assert not output.exists(), 'Refuse duplicate selection review' +selection = json.loads((R / f'{a.run}_selection_receipt.json').read_text()) +selected = next(v for v in selection['results'] if v['step'] == a.step) +current = json.loads((R / 'CURRENT_RESEARCH_STATE.json').read_text())['published'] +assert current['checkpoint_sha256'] == selected['current_descriptor_sha256'] +expected_skills = [current['main_skill']] + current['earlier_skills'] +expert_root, expert_id, frozen_prefix = EXPERTS[ARMS[a.run]['experts']] +weights = R / 'runs' / a.run / f'ema{a.step:06d}.pt' +with weights.open('rb') as f: + expected_hash = hashlib.file_digest(f, 'sha256').hexdigest() + +def skill(configs): + return 1 - math.exp(sum(math.log(c['relative']['mase']) + math.log(c['relative']['wql']) + for c in configs) / (2 * len(configs))) + +def grouped(configs): + result = {} + for category, key in [('term', lambda c: c['term']), + ('domain', lambda c: c['domain']), + ('frequency', lambda c: ts_io.parse_freq(c['freq'])[1]), + ('variates', lambda c: 'multivariate' if c['n_variates'] > 1 else 'univariate')]: + buckets = {} + for config in configs: + buckets.setdefault(key(config), []).append(config) + result[category] = {name: skill(rows) for name, rows in sorted(buckets.items())} + return result + +rows = [] +for (panel, folder), current_skill in zip(PANELS, expected_skills): + candidate = json.loads((R / folder / f'{a.run}_ema{a.step}' / 'report.json').read_text()) + frozen = json.loads((R / f'{frozen_prefix}_{panel}.json').read_text()) + parent = json.loads((R / f'{a.current_probe_prefix}_{panel}.json').read_text()) + assert candidate['checkpoint_sha256'] == expected_hash + assert candidate['expert_descriptor_sha256'] == expert_id and candidate['n_failed'] == 0 + assert abs(parent['skill_score'] - current_skill) < 1e-12 + tables = [{c['config_id']: c for c in report['configs']} for report in [candidate, frozen, parent]] + assert set(tables[0]) == set(tables[1]) == set(tables[2]) + for report in [candidate, frozen, parent]: + assert abs(skill(report['configs']) - report['skill_score']) < 1e-12 + groups = [grouped(report['configs']) for report in [candidate, frozen, parent]] + comparisons = {} + for label, table, group in [('frozen', tables[1], groups[1]), ('current', tables[2], groups[2])]: + deltas = [{'config_id': cid, 'delta': skill([config]) - skill([table[cid]])} + for cid, config in tables[0].items()] + deltas.sort(key=lambda v: v['delta']) + comparisons[label] = dict( + positive_configs=sum(v['delta'] > 0 for v in deltas), + total_configs=len(deltas), + group_skill_delta={category: {name: value - group[category][name] + for name, value in entries.items()} + for category, entries in groups[0].items()}, + largest_regressions=deltas[:8], largest_improvements=deltas[-8:][::-1]) + rows.append(dict(panel=panel, skill=candidate['skill_score'], + delta_frozen=candidate['skill_score']-frozen['skill_score'], + delta_current=candidate['skill_score']-current_skill, + evaluation_seconds=candidate['eval_seconds'], + groups=groups[0], comparisons=comparisons)) + +training = None +for line in (R / f'{a.run}_train.log').read_text().splitlines(): + try: + item = json.loads(line) + except json.JSONDecodeError: + continue + if item.get('step') == a.step: + training = item +assert training is not None +result = dict(utc=datetime.datetime.now(datetime.timezone.utc).isoformat(), + experiment='E152', run=a.run, step=a.step, seed=751, + checkpoint_sha256=expected_hash, expert_descriptor_sha256=expert_id, + current_descriptor_sha256=current['checkpoint_sha256'], + training_loop_seconds_to_endpoint=training['seconds'], + rows=rows, selection_gate_passed=selected['selection_gate_passed'], + positive_frozen=selected['positive_frozen'], mean_delta_frozen=selected['mean_delta_frozen'], + positive_current=selected['positive_current'], mean_delta_current=selected['mean_delta_current'], + cpu_review_seconds=time.monotonic()-started, + new_optimizer_updates=0, new_inference=False, + outcome='Four-cutoff gate passes; full public replay and runtime checks are required before publication.' + if selected['selection_gate_passed'] else + 'Four-cutoff gate fails; no full replay or publication from this endpoint.', + interpretation='Adaptive validation diagnostics, not independent test evidence. ' + 'Frequency groups are recomputed using the scorer frequency parser, ' + 'avoiding comparison of full aliases with frequency-unit groups.') +output.write_text(json.dumps(result, indent=2)) +with (R / 'direct_v1/EXPERIMENTS.md').open('a') as f: + f.write('\n' + result['utc'] + ': E152 declared endpoint review ' + json.dumps(result) + '.\n') +print(json.dumps({k: v for k, v in result.items() if k != 'rows'})) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/study.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/study.py new file mode 100644 index 0000000000000000000000000000000000000000..4248ce59fa7ad608729cbcec6be9e64c615d81be --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/study.py @@ -0,0 +1,14 @@ +"""Fixed E152 cells; no inference-time routing between expert sets.""" +from pathlib import Path +R = Path('/workspace/research') +EXPERTS = { + 'E130': ('gating_experts_E130', 'fa97880dd132b1cdff459be4798f8f360d7df59b13e78026a9d74a95d63df0db', 'fresh_capacity4_ensemble'), + 'E148': ('gating_experts_E148', 'a1b4ab426901be8e1ee299eeeb3f041bac7cea3d4e59c4608824fc3d05c83e03', 'width12_fresh96_ensemble'), +} +ARMS = { + 'ensemble_gate_refresh': dict(experts='E148', pack='packed_sample', controls=['ensemble_gate']), + 'ensemble_gate_full': dict(experts='E130', pack='packed_stratified_full', controls=['ensemble_gate']), + 'ensemble_gate_refresh_full': dict(experts='E148', pack='packed_stratified_full', controls=['ensemble_gate_refresh', 'ensemble_gate_full']), +} +INITIAL_SHA = '9d1401cd4d5b5f1c3ddd25a4a74e15e5db7ef708116cdf5c4fa7e90580b58da1' +PANELS = [('valid_screen', 'evals'), ('valid_backcast', 'backcast_evals'), ('valid_backcast2', 'backcast2_evals'), ('valid_backcast3', 'backcast3_evals')] diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/validate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/validate.py new file mode 100644 index 0000000000000000000000000000000000000000..fe381c80fa5b935ae28ad0e2f643489d94d8d00c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/validate.py @@ -0,0 +1,29 @@ +"""Selected learned-gate full replay; every promotion remains a separate reviewed action.""" +import argparse,json,subprocess,time +from pathlib import Path +from study import ARMS,EXPERTS +R=Path('/workspace/research');ap=argparse.ArgumentParser();ap.add_argument('--step',type=int,choices=[6000,12000],required=True);ap.add_argument('--run',choices=list(ARMS),required=True);a=ap.parse_args() +step=a.step;prefix=f'{a.run}_{step}';slug=prefix.replace('_','-');package=R/f'candidate-{slug}' +expert_root,expert_id,baseline=EXPERTS[ARMS[a.run]['experts']] +selection=json.loads((R/f'{a.run}_selection_receipt.json').read_text()) +result=next(v for v in selection['results'] if v['step']==step) +assert result['selection_gate_passed'] and result['positive_frozen']>=3 and result['mean_delta_frozen']>0 +current=json.loads((R/'CURRENT_RESEARCH_STATE.json').read_text())['published'] +differences=[v['skill']-old for v,old in zip(result['rows'],[current['main_skill']]+current['earlier_skills'])] +assert len(differences)==4 and sum(x>0 for x in differences)>=3 and sum(differences)>0 +report=R/f'valid-report-{slug}.json';pred=R/f'valid-pred-{slug}' +receipt=R/(prefix+'_validation_receipt.json');started=time.monotonic() +state=dict(status='running',steps=[],package=str(package),selection_current_deltas=differences) +commands=[('assemble',['python3',str(R/'ensemble_gate_factorial/publish.py'),'--weights',str(R/'runs'/a.run/f'ema{step:06d}.pt'),'--out',str(package),'--experts',str(R/expert_root)]), + ('independent_composition',['python3',str(R/'ensemble_gate_factorial/check_learned_runtime.py'),'--package',str(package),'--receipt',str(R/(prefix+'_runtime_checks.json'))]), + ('relocation',['python3',str(R/'verify_package_examples.py'),'--package',str(package),'--receipt',str(R/(prefix+'_package_checks.json'))]), + ('full_public_replay',['python3',str(R/'run_package_validation.py'),'--package',str(package),'--out',str(pred),'--report',str(report)]), + ('descriptive_comparison',['python3',str(R/'compare_reports.py'),'--candidate',str(report),'--parent',current['full_report'],'--out',str(R/(prefix+'_comparison.json'))])] +for label,command in commands: + state['current_step']=label;receipt.write_text(json.dumps(state,indent=2));tick=time.monotonic() + completed=subprocess.run(command);state['steps'].append(dict(name=label,returncode=completed.returncode,seconds=time.monotonic()-tick)) + if completed.returncode: + state.update(status='failed',seconds=time.monotonic()-started);receipt.write_text(json.dumps(state,indent=2));raise SystemExit(completed.returncode) +full=json.loads(report.read_text());assert full['n_configs']==97 and full['n_instances']==151170 and full['n_failed']==0 +state.update(status='complete',seconds=time.monotonic()-started,skill=full['skill_score']) +receipt.write_text(json.dumps(state,indent=2));print(json.dumps(state),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/watch_selection.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/watch_selection.py new file mode 100644 index 0000000000000000000000000000000000000000..4aa4be968b023be1b3777e05d1b27e470e5e98c9 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/watch_selection.py @@ -0,0 +1,62 @@ +"""Evaluate each declared E152 endpoint against its fixed experts and current publication.""" +import argparse, datetime, hashlib, json, os, subprocess, time +from study import ARMS, EXPERTS, PANELS, R + +ap = argparse.ArgumentParser(); ap.add_argument('--run', choices=list(ARMS), required=True); a = ap.parse_args() +arm = ARMS[a.run]; expert_root, expert_id, baseline = EXPERTS[arm['experts']] +started = time.monotonic(); receipt = R/f'{a.run}_selection_receipt.json' +state = dict(pid=os.getpid(), run=a.run, status='waiting', steps=[], results=[]) +def save(): + state['seconds'] = time.monotonic()-started + tmp = receipt.with_suffix('.tmp'); tmp.write_text(json.dumps(state, indent=2)); os.replace(tmp, receipt) +def call(label, command): + state['status'] = label; save(); tick = time.monotonic() + result = subprocess.run(command) + state['steps'].append(dict(label=label, returncode=result.returncode, seconds=time.monotonic()-tick)); save() + if result.returncode:state['status']='failed'; save(); raise SystemExit(result.returncode) +for step in [6000, 12000]: + name = f'{a.run}_ema{step}'; weights = R/'runs'/a.run/f'ema{step:06d}.pt' + state['status'] = f'waiting for main{step}'; save() + while not (R/'evals'/name/'report.json').exists(): + path = R/f'{a.run}_queue.json' + if path.exists() and json.loads(path.read_text())['status'] == 'failed': + state['status']='training failed'; save(); raise SystemExit(1) + time.sleep(3) + time.sleep(1) + expected = hashlib.sha256(weights.read_bytes()).hexdigest() + call(f'earlier cutoffs{step}', ['python3', str(R/'evaluate_cutoffs.py'), '--name', name, '--weights', str(weights), '--evaluator', str(R/'ensemble_gate_factorial/evaluate.py'), '--cutoffs', '1,2,3']) + current = json.loads((R/'CURRENT_RESEARCH_STATE.json').read_text())['published'] + current_skills = [current['main_skill']]+current['earlier_skills'] + rows=[] + for (cutoff, folder), current_skill in zip(PANELS, current_skills): + path = R/folder/name/'report.json'; report=json.loads(path.read_text()) + control=json.loads((R/f'{baseline}_{cutoff}.json').read_text()) + assert report['checkpoint_sha256']==expected and report['expert_descriptor_sha256']==expert_id and report['n_failed']==0 + rows.append(dict(cutoff=cutoff, skill=report['skill_score'], frozen_control_skill=control['skill_score'], + delta_frozen=report['skill_score']-control['skill_score'], current_skill=current_skill, + delta_current=report['skill_score']-current_skill, groups=report['groups'], checkpoint_sha256=expected, + expert_descriptor_sha256=expert_id, eval_seconds=report['eval_seconds'])) + call(f'record{step} {cutoff}', ['python3', str(R/'direct_v1/record.py'), str(path), '--label', f'E152 {a.run} {step} {cutoff}', '--outcome', 'Declared expert-version/corpus-coverage factorial. Only6340gateparameters trained; all four immutable experts forecast every instance. Source/control/current comparisons precede any full replay.']) + result=dict(step=step, rows=rows, positive_frozen=sum(x['delta_frozen']>0 for x in rows), + mean_delta_frozen=sum(x['delta_frozen'] for x in rows)/4, + positive_current=sum(x['delta_current']>0 for x in rows), mean_delta_current=sum(x['delta_current'] for x in rows)/4, + current_descriptor_sha256=current['checkpoint_sha256']) + result['selection_gate_passed']=result['positive_frozen']>=3 and result['mean_delta_frozen']>0 and result['positive_current']>=3 and result['mean_delta_current']>0 + state['results'].append(result); save() + for control in arm['controls']: + while any(not (R/folder/f'{control}_ema{step}'/'report.json').exists() for _,folder in PANELS): + control_receipt=R/f'{control}_selection_receipt.json' + if control_receipt.exists() and json.loads(control_receipt.read_text())['status'] in ['failed','training failed']: + state['status']='failed'; save(); raise SystemExit('Matched control evaluation failed: '+control) + time.sleep(3) + output=R/f'{a.run}{step//1000}k_vs_{control}_four_cutoff_comparison.json' + if output.exists(): + cached=json.loads(output.read_text()); assert cached['candidate']==name and cached['control']==f'{control}_ema{step}' + assert all(row['candidate_checkpoint']==expected for row in cached['rows']) + else: + call(f'matched {control} at{step}', ['python3', str(R/'recovery/matched_report.py'), '--candidate', name, '--control', f'{control}_ema{step}', '--label', f'E152 {a.run} vs {control} at{step}', '--cutoffs', '0,1,2,3', '--out', str(output), '--outcome', 'Fixed factorial contrast; no automatic package, transfer or publication.']) + with (R/'direct_v1/EXPERIMENTS.md').open('a') as f: + f.write('\n'+datetime.datetime.now(datetime.timezone.utc).isoformat()+': E152 '+a.run+' '+json.dumps(result)+'. Full replay/publication require separate review and fresh current-publication comparison.\n') + if a.run=='ensemble_gate_refresh_full': + call(f'factorial interaction{step}', ['python3',str(R/'ensemble_gate_factorial/interaction.py'),'--step',str(step)]) +state['status']='complete; research review required'; save(); print(json.dumps(state), flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/watch_weights.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/watch_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..a1025ea78df9791b6eae5c98ca9d17d90be087ba --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial/watch_weights.py @@ -0,0 +1,27 @@ +"""Run descriptive CPU weight summaries only at the existing declared endpoints.""" +import argparse,hashlib,json,os,subprocess,time +from study import R,ARMS +ap=argparse.ArgumentParser();ap.add_argument('--run',choices=list(ARMS),required=True);a=ap.parse_args() +started=time.monotonic();receipt=R/(a.run+'_weight_watch_receipt.json');state=dict(pid=os.getpid(),run=a.run,status='waiting primary6000 four-cutoff selection',steps=[]) +def save(): + state['seconds']=time.monotonic()-started;tmp=receipt.with_suffix('.tmp');tmp.write_text(json.dumps(state,indent=2));os.replace(tmp,receipt) +for step in [6000,12000]: + state['status']=f'waiting declared{step} selection';save() + path=R/(a.run+'_selection_receipt.json') + while True: + if path.exists(): + selection=json.loads(path.read_text()) + if any(v['step']==step for v in selection['results']):break + if selection['status'] in ['failed','training failed']:state['status']='source failed';save();raise SystemExit(1) + time.sleep(3) + output=R/f'{a.run}{step//1000}k_weight_structure.json' + if output.exists(): + cached=json.loads(output.read_text());assert cached['step']==step and cached['run']==a.run + assert cached['gate_checkpoint_sha256']==hashlib.sha256((R/'runs'/a.run/f'ema{step:06d}.pt').read_bytes()).hexdigest() + continue + state['status']=f'describe{step}';save();tick=time.monotonic() + with (R/f'{a.run}{step//1000}k_weight_structure.log').open('w') as log: + result=subprocess.run(['python3',str(R/'ensemble_gate_factorial/describe_weights.py'),'--run',a.run,'--step',str(step)],stdout=log,stderr=subprocess.STDOUT) + state['steps'].append(dict(step=step,returncode=result.returncode,seconds=time.monotonic()-tick));save() + if result.returncode:state['status']='diagnostic failed';save();raise SystemExit(result.returncode) +state['status']='complete; descriptive only, no changed parameters or forecasts';save();print(json.dumps(state)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial_cpu_checks.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial_cpu_checks.json new file mode 100644 index 0000000000000000000000000000000000000000..52f3b228cbe5a2f0eb12926eed769969838fd517 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial_cpu_checks.json @@ -0,0 +1,27 @@ +{ + "utc": "2026-10-23T22:20:33.590042+00:00", + "fixture_seed": 983, + "training_seed": 751, + "initial_sha256": "9d1401cd4d5b5f1c3ddd25a4a74e15e5db7ef708116cdf5c4fa7e90580b58da1", + "same_seed_recreates_initial_bitwise": true, + "unchanged_files": { + "model.py": "5b88c1a45e9ebade46b70ca31e082f24b2f2e71179b90431d62853d042a9eaf4", + "data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "normalization.py": "77226d599c15fbe6e442d0fd7cc5c43387b6f3669830e4b1f5754d9cdb4268c1", + "frequency.py": "eb08437794e3c2493f3760aa39ad8bde268a8351d33fb868bc0f553bc13eb720", + "predict.py": "492d57d5f97079867bb1c199cfcebe649fe0042fb041a0cbfda54ab6fe75df2f", + "infer.sh": "3b7de83c16d6d6cd3347c89bf6fdae5f64d6e731562597c6e98e67e2ac5c4acb", + "ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436" + }, + "frozen_expert_forward_ast_identical": true, + "original_old_pack_stream_bitwise": true, + "sampled_old_rows": 512, + "all95_sources_and_probabilities_identical": true, + "synthetic_fraction": 0.2, + "full_pack_sampler_state_recovery_bitwise": true, + "full_pack_fixture_rows": 64, + "reused_feature_gradient_audit": "/workspace/research/ensemble_gate_cpu_checks.json", + "seconds": 40.27279006689787, + "optimizer_updates": 0, + "validation_data_read": false +} \ No newline at end of file diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial_gpu_checks.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial_gpu_checks.json new file mode 100644 index 0000000000000000000000000000000000000000..cf056ca0671f091ecb8370df2e18675ca3ae4525 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/ensemble_gate_factorial_gpu_checks.json @@ -0,0 +1,54 @@ +{ + "fixture_seed": 1009, + "training_seed": 751, + "initial_checkpoint_sha256": "9d1401cd4d5b5f1c3ddd25a4a74e15e5db7ef708116cdf5c4fa7e90580b58da1", + "expert_descriptor_sha256": "a1b4ab426901be8e1ee299eeeb3f041bac7cea3d4e59c4608824fc3d05c83e03", + "expert_hashes": [ + "0b11b7351a4a92d1d18c71a4159ec445be3a94ace8c7a9fa0edafad87d14e960", + "308389b7217c080af9eb185559d4ee3cafa0f3e0f8c4dd8f5526b68198c89988", + "1a2fb20a9fb5cae6526f2e36ea47559626bece78fd9c284899836505030ae9fe", + "d7cfcd72c3cb84aa69e447b76c4c3ab98c21b7c600a463f0b805f4b4300baf33" + ], + "synthetic_replay_checks": [ + { + "config_id": "synthetic_H", + "rows": 12, + "horizon": 384, + "batch": 4, + "all_four_experts_bitwise": true, + "initial_ensemble_bitwise": true + }, + { + "config_id": "synthetic_15T", + "rows": 12, + "horizon": 960, + "batch": 4, + "all_four_experts_bitwise": true, + "initial_ensemble_bitwise": true + } + ], + "maximum_shape": [ + 64, + 4096, + 1024 + ], + "frozen_expert_parameters": 256643928, + "trainable_parameters": 6340, + "temporary_gate_head_std": 0.01, + "all_gate_layers_finite_nonzero_gradients": true, + "experts_have_no_gradients": true, + "loss": 0.19952183961868286, + "minimum_weight": 0.23992976546287537, + "maximum_weight": 0.2656008303165436, + "peak_allocated_mib": 2048.408203125, + "peak_reserved_mib": 2478.0, + "free_before_mib": 21861.6875, + "includes_gate_adam_and_ema_placeholders": true, + "expert_forward_seconds": 0.7720213478896767, + "gate_forward_backward_seconds": 0.14125064807012677, + "lock_wait_seconds": 62.070755757857114, + "seconds": 119.03930641920306, + "optimizer_updates": 0, + "validation_data_read": false, + "initial_checkpoint_unchanged": true +} \ No newline at end of file diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/gate_corpus_metadata.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/gate_corpus_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..20cfff6962c779a7137f5dd07c3824259783cc4a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/gate_corpus_metadata.json @@ -0,0 +1,199 @@ +{ + "dirs": [ + "BEIJING_SUBWAY_30MIN", + "HZMETRO", + "LOS_LOOP", + "PEMS03", + "PEMS04", + "PEMS07", + "PEMS08", + "PEMS_BAY", + "Q-TRAFFIC", + "SHMETRO", + "alibaba_cluster_trace_2018", + "australian_electricity_demand", + "azure_vm_traces_2017", + "bdg-2_bear", + "bdg-2_fox", + "bdg-2_panther", + "bdg-2_rat", + "bitcoin_with_missing", + "borealis", + "borg_cluster_data_2011", + "buildings_900k", + "bull", + "cdc_fluview_ilinet", + "cdc_fluview_who_nrevss", + "china_air_quality", + "cif_2016_12", + "cif_2016_6", + "cmip6_2000", + "cmip6_2005", + "cmip6_2010", + "cockatoo", + "covid19_energy", + "covid_mobility", + "elecdemand", + "elf", + "era5_2010", + "era5_2011", + "era5_2012", + "era5_2013", + "era5_2014", + "era5_2015", + "era5_2016", + "era5_2017", + "era5_2018", + "extended_web_traffic_with_missing", + "favorita_sales", + "favorita_transactions", + "gfc12_load", + "gfc14_load", + "gfc17_load", + "godaddy", + "hog", + "ideal", + "kaggle_web_traffic_weekly", + "kdd2022", + "largest_2017", + "largest_2018", + "largest_2019", + "largest_2020", + "largest_2021", + "lcl", + "london_smart_meters_with_missing", + "m1_monthly", + "m1_quarterly", + "m1_yearly", + "m5", + "monash_m3_monthly", + "monash_m3_other", + "monash_m3_quarterly", + "nn5_daily_with_missing", + "nn5_weekly", + "oikolab_weather", + "pdb", + "project_tycho", + "residential_load_power", + "residential_pv_power", + "rideshare_with_missing", + "sceaux", + "smart", + "solar_power", + "spain", + "subseasonal", + "subseasonal_precip", + "sunspot_with_missing", + "taxi_30min", + "tourism_quarterly", + "tourism_yearly", + "traffic_hourly", + "traffic_weekly", + "uber_tlc_daily", + "uber_tlc_hourly", + "vehicle_trips_with_missing", + "wiki-rolling_nips", + "wind_farms_with_missing", + "wind_power" + ], + "counts": { + "BEIJING_SUBWAY_30MIN": 552, + "HZMETRO": 160, + "LOS_LOOP": 207, + "PEMS03": 358, + "PEMS04": 921, + "PEMS07": 851, + "PEMS08": 510, + "PEMS_BAY": 325, + "Q-TRAFFIC": 4101, + "SHMETRO": 576, + "alibaba_cluster_trace_2018": 14804, + "australian_electricity_demand": 5, + "azure_vm_traces_2017": 4360, + "bdg-2_bear": 91, + "bdg-2_fox": 135, + "bdg-2_panther": 105, + "bdg-2_rat": 280, + "bitcoin_with_missing": 18, + "borealis": 15, + "borg_cluster_data_2011": 8805, + "buildings_900k": 2744, + "bull": 41, + "cdc_fluview_ilinet": 326, + "cdc_fluview_who_nrevss": 296, + "china_air_quality": 2532, + "cif_2016_12": 57, + "cif_2016_6": 15, + "cmip6_2000": 3288, + "cmip6_2005": 3288, + "cmip6_2010": 3288, + "cockatoo": 1, + "covid19_energy": 1, + "covid_mobility": 362, + "elecdemand": 1, + "elf": 1, + "era5_2010": 2752, + "era5_2011": 2752, + "era5_2012": 2752, + "era5_2013": 2752, + "era5_2014": 2752, + "era5_2015": 2752, + "era5_2016": 2752, + "era5_2017": 2752, + "era5_2018": 2752, + "extended_web_traffic_with_missing": 9387, + "favorita_sales": 17820, + "favorita_transactions": 54, + "gfc12_load": 20, + "gfc14_load": 1, + "gfc17_load": 8, + "godaddy": 6270, + "hog": 24, + "ideal": 217, + "kaggle_web_traffic_weekly": 145063, + "kdd2022": 134, + "largest_2017": 231, + "largest_2018": 232, + "largest_2019": 232, + "largest_2020": 232, + "largest_2021": 232, + "lcl": 713, + "london_smart_meters_with_missing": 820, + "m1_monthly": 617, + "m1_quarterly": 198, + "m1_yearly": 106, + "m5": 12546, + "monash_m3_monthly": 1428, + "monash_m3_other": 174, + "monash_m3_quarterly": 756, + "nn5_daily_with_missing": 111, + "nn5_weekly": 111, + "oikolab_weather": 8, + "pdb": 1, + "project_tycho": 1258, + "residential_load_power": 188, + "residential_pv_power": 186, + "rideshare_with_missing": 2304, + "sceaux": 1, + "smart": 5, + "solar_power": 1, + "spain": 1, + "subseasonal": 1458, + "subseasonal_precip": 862, + "sunspot_with_missing": 1, + "taxi_30min": 42825, + "tourism_quarterly": 427, + "tourism_yearly": 419, + "traffic_hourly": 862, + "traffic_weekly": 862, + "uber_tlc_daily": 262, + "uber_tlc_hourly": 262, + "vehicle_trips_with_missing": 329, + "wiki-rolling_nips": 29157, + "wind_farms_with_missing": 184, + "wind_power": 1 + }, + "per_directory_point_cap": 24000000, + "seed": "sha256(directory) little-endian first 4 bytes", + "min_length": 16 +} \ No newline at end of file diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/recovery/schedules.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/recovery/schedules.py new file mode 100644 index 0000000000000000000000000000000000000000..4c8378f374144b802d2cd5a98afd71efc1ba0a4c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/recovery/schedules.py @@ -0,0 +1,13 @@ +"""Explicit training-only learning-rate schedules; default arithmetic unchanged.""" +import math + + +def learning_rate(step, steps, peak, reset_at=-1, anneal_from_step=None, + anneal_from_lr=None, anneal_final_lr=None): + if anneal_from_step is not None: + assert steps > anneal_from_step + assert 0 < anneal_final_lr <= anneal_from_lr + progress=max(0.,min(1.,(step-anneal_from_step)/(steps-anneal_from_step))) + return anneal_final_lr+.5*(anneal_from_lr-anneal_final_lr)*(1+math.cos(math.pi*progress)) + warm_step=step-reset_at if reset_at>=0 and step>reset_at else step + return peak*min(1,warm_step/400)*(.2+.4*(1+math.cos(math.pi*step/steps))) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/recovery/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/recovery/train.py new file mode 100644 index 0000000000000000000000000000000000000000..359586abd55c5af836739e7fd7bccfcd653ce7e0 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/gate_training/recovery/train.py @@ -0,0 +1,331 @@ +"""Resumable continuation of our existing permitted-corpus experiments.""" +import argparse,copy,fcntl,inspect,json,math,os,sys,time +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +# Future queued jobs may inherit only the shell's minimal environment. Keep the +# audited compilation/cache setup explicit before torch or its workers import it. +if '--compile-loss' in sys.argv: + _compiler_environment = dict( + TORCHINDUCTOR_COMPILE_THREADS='2', MAX_JOBS='2', + PYTHONPATH=str(Path(__file__).parent.parent/'compiler_support'), + TRITON_CACHE_MANAGER='sibling_cache:SiblingFileCacheManager', + TRITON_CACHE_DIR='/tmp/timeseries-triton-cache', + TORCHINDUCTOR_CACHE_DIR='/tmp/timeseries-inductor-cache') + os.environ.update(_compiler_environment) + sys.path.insert(0, _compiler_environment['PYTHONPATH']) +import numpy as np +import torch + +ap=argparse.ArgumentParser() +ap.add_argument('--code-dir',required=True);ap.add_argument('--packed',required=True) +ap.add_argument('--source-weights-from');ap.add_argument('--out',required=True) +ap.add_argument('--initialize-from',required=True);ap.add_argument('--initialize-ema') +ap.add_argument('--start-step',type=int,default=0);ap.add_argument('--resume') +ap.add_argument('--steps',type=int,required=True);ap.add_argument('--batch',type=int,required=True) +ap.add_argument('--lr',type=float,required=True);ap.add_argument('--seed',type=int,required=True) +ap.add_argument('--context',type=int);ap.add_argument('--sample-context',type=int,default=4096) +ap.add_argument('--save-every',type=int,default=1000);ap.add_argument('--stop-file') +ap.add_argument('--recovery-every',type=int,default=250) +ap.add_argument('--halt-after',type=int) +ap.add_argument('--loss-mode',choices=['individual','paired']) +ap.add_argument('--compile-loss',action='store_true') +ap.add_argument('--reset-at',type=int,default=-1);ap.add_argument('--reset-seed',type=int,default=179) +ap.add_argument('--anneal-from-step',type=int);ap.add_argument('--anneal-from-lr',type=float) +ap.add_argument('--anneal-final-lr',type=float) +ap.add_argument('--teacher-package');ap.add_argument('--teacher-coefficient',type=float) +ap.add_argument('--compile-teacher',action='store_true') +ap.add_argument('--visibility-curriculum',action='store_true') +ap.add_argument('--gate-package') +ap.add_argument('--micro-batch',type=int) +a=ap.parse_args() +# Hold a process-lifetime lock before loading a model or touching GPU state. +_run_out=Path(a.out);_run_out.mkdir(parents=True,exist_ok=True) +_run_lock=open(_run_out/'.training.lock','a') +try:fcntl.flock(_run_lock,fcntl.LOCK_EX|fcntl.LOCK_NB) +except BlockingIOError:raise SystemExit('Another trainer already owns this output directory: '+str(_run_out)) +if not a.resume: + _saved=list(_run_out.glob('ema*.pt'))+list(_run_out.glob('step*.pt')) + if (_run_out/'recovery.pt').exists():_saved.append(_run_out/'recovery.pt') + if _saved: + raise SystemExit('Refusing fresh training into an output with saved checkpoints; use a new directory or explicit --resume: '+str(_run_out)) +sys.path.insert(0,a.code_dir) +from model import DirectForecaster,loss_fn +from data import Sampler +from schedules import learning_rate +torch.set_num_threads(2);torch.manual_seed(a.seed);torch.backends.cuda.matmul.allow_tf32=True +out=Path(a.out);out.mkdir(parents=True,exist_ok=True);a.trainable_scope='all' +if Path(a.code_dir).name in ('long_memory_synth','paired_long_memory','multiscale_ar','random_capacity','patch8_long_memory','distill_ensemble','random_capacity_long_seasonal','random_capacity_long_seasonal_distill','random_capacity_seasonal_width','random_capacity_seasonal_history','random_capacity_seasonal_spectral','random_capacity_seasonal_integrated','random_capacity_1536_six_teacher','visibility_curriculum','random_capacity_deep'):a.synthetic_ar_time_constants=[1,10000] +if Path(a.code_dir).name in ('full_paired','patch8','temporal_mixup','postloss','paired_long_memory','multiscale_ar','random_capacity','overflow_control','coarse_aggregate','patch8_long_memory','patch4','metric_scale','robust_normalization','split_patch','weekly_synth','distill_ensemble'):a.requested_horizon_seed=a.seed+300003 +if Path(a.code_dir).name=='multiscale_ar': + a.synthetic_ar_components=4;a.multiscale_ar_seed=a.seed+700003 +if Path(a.code_dir).name=='volatility_synth':a.stochastic_volatility_seed=a.seed+500003 +if Path(a.code_dir).name=='coarse_aggregate': + a.coarse_aggregation_seed=a.seed+900003;a.coarse_aggregation_probability=.2;a.coarse_aggregation_frequencies=['D','W'] +if Path(a.code_dir).name=='temporal_mixup':a.temporal_mixup_seed=a.seed+600003 +if Path(a.code_dir).name=='postloss': + a.fixed_postprocessing_loss=True;a.normalization_overflow_fallback=True +if Path(a.code_dir).name in ('overflow_control','metric_scale','random_capacity','weekly_synth','distill_ensemble'):a.normalization_overflow_fallback=True +if Path(a.code_dir).name=='weekly_synth': + a.weekly_synthetic_seed=a.seed+1000003;a.weekly_replacement_probability=1/11 +if Path(a.code_dir).name in ('spectral_synth','random_capacity_seasonal_spectral'): + a.spectral_synthetic_seed=a.seed+1100003;a.spectral_replacement_probability=.5 + a.spectral_length_scale=[1,10000];a.spectral_families=['Matern0.5','Matern1.5','Matern2.5','RBF'] + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True +if Path(a.code_dir).name in ('long_seasonal','spectral_phase','spectral_phase_individual','phase_joint','seasonal_dispersion','seasonal_history','seasonal_width','direct_trend_head','random_capacity_long_seasonal','random_capacity_long_seasonal_distill','random_capacity_seasonal_width','random_capacity_seasonal_history','random_capacity_seasonal_spectral','random_capacity_seasonal_integrated','random_capacity_1536_six_teacher','visibility_curriculum','random_capacity_deep','ensemble_gate','ensemble_gate_factorial','six_expert_gate'): + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True +if Path(a.code_dir).name in ('spectral_phase','spectral_phase_individual'): + a.spectral_phase_summary_rule='Fixed Hann-window Fourier projection: recent4096,8x power-of-two FFT grid, top4 local17-bin peaks, minimum4cycles/span128/finite0.9, amplitude cap30, power confidence cap1; zero query and direct median head initialized from own E107 parent. No inference fitting.' +if Path(a.code_dir).name=='spectral_phase_individual': + a.spectral_phase_individual_span_rule='Per row longest eligible right-aligned dyadic window128,256,512,1024,2048,4096 with finitefraction>=0.9; fixed missing-prefix padding, independent of batch rectangle' +if Path(a.code_dir).name=='random_capacity_buildings': + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True + a.synthetic_ar_time_constants=[1,10000] + a.source_probability_multipliers={'buildings_900k':4.} + a.source_probability_rule='original packed_sample capped-point temperature0.25, climate0.35, low-frequency3, then buildings_900k x4 and renormalize; same20percent synthetic' +if Path(a.code_dir).name=='random_capacity_original_ar': + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True + a.synthetic_ar_coefficient_law='uniform(0.2,0.995), original generator; unchanged AR branch probability and asymptotic variance scaling' +if Path(a.code_dir).name=='log_horizon': + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True + a.requested_horizon_law='half full; half geometric quantile remap of the original uniform integer endpoint draw from min(16,max(1,H//4)) to H, then patch16 rounding; identical RNG consumption' +if Path(a.code_dir).name in ('seasonal_history','random_capacity_seasonal_history'): + a.learned_seasonal_history_context=16384;a.recent_encoder_and_rule_context=4096 + a.history_extension_rule='extend originally full4096 real contexts before the same cutoff, preserving original recent contexts, targets, aggregation, sampler RNG and horizon RNG; synthetic extra prefix missing' +if Path(a.code_dir).name in ('lowfreq_windows','lowfreq_age'): + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True + a.lowfreq_window_seed=a.seed+1200003;a.lowfreq_window_probability=.5 + a.lowfreq_window_rule='period2=1,period1<=52;finite-target endpoint;log-uniform horizon4..min(H,max(8,2p),span-8) with available-length fallback;context cap min(C,max(64,32p));at least4finite history' +if Path(a.code_dir).name=='lowfreq_age': + a.synthetic_generation_origin='For successfully shortened selected low-frequency synthetic rows only, use the first nc+nh observations of the same generated path, split at nc; unchanged masks, lengths, periods, real/unselected rows and all RNG streams; no regeneration or extra draws' +if Path(a.code_dir).name in ('integrated_level','random_capacity_seasonal_integrated'): + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True + a.integrated_level_seed=a.seed+1300003;a.integrated_level_probability=.25 + a.integrated_level_rule='Add zero-initialized Gaussian random-walk levels to one quarter of synthetic paths before intermittent/positivity transforms; per-path innovation sigma10**Uniform(-3,-1); original generator, real windows and their RNGs unchanged' + a.synthetic_ar_coefficient_law=('exp(-10**(-Uniform(0,4))), slowARcontrol' if Path(a.code_dir).name=='random_capacity_seasonal_integrated' else 'uniform(0.2,0.995), original generator; unchanged AR branch probability and asymptotic variance scaling') +if Path(a.code_dir).name=='signed_power_synth': + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True + a.signed_power_seed=a.seed+1400003;a.signed_power_probability=.5 + a.signed_power_exponent_range=[.5,2.] + a.signed_power_rule='Pointwise sign(x)*abs(x)**gamma after original synthetic intermittent/positivity operations; one gamma=exp(Uniform(-log2,log2)) per selected path, float64 arithmetic then float32 storage; no observed-path statistics; original RNGs and real/unselected paths unchanged' + a.synthetic_ar_coefficient_law='uniform(0.2,0.995), original generator; unchanged AR branch probability and asymptotic variance scaling' +if Path(a.code_dir).name=='metric_scale':a.loss_seasonality='lag1 for exact daily[7,365] and weekly[52,1] period pairs; unchanged otherwise' +if Path(a.code_dir).name=='robust_normalization':a.normalization_kind='finite median plus/minus6 mean absolute deviations winsorized mean/RMS, float64; original normalized history clipped30' +if Path(a.code_dir).name=='wide_graft_frozen':a.trainable_scope='new feature stream and cross-stream blocks; inherited parameter blocks frozen' +if a.visibility_curriculum: + assert Path(a.code_dir).name=='visibility_curriculum' and not a.teacher_package and not a.gate_package + from visibility import visible_batch + a.visibility_curriculum_rule='steps1..16000:lastC/4,firstmax(16,H/4);16001..32000:lastC/2,firstmax(16,H/2);32001..96000:unchanged; sample/prefetch full original windows and crop only current loss arrays' +if a.micro_batch is not None: + assert 0=0 and start_step>=a.reset_at else a.seed +sampler,rng=make_sampler(stream_seed) +def next_batch(): + c=int(rng.choice([512,1024,2048,a.sample_context],p=[.1,.15,.35,.4])) + h=int(rng.choice([32,128,512,1024],p=[.1,.2,.2,.5])) + x,y,p=sampler.sample(a.batch,c,h) + return x[:,-model.max_context:].copy(),y,p +pool=ThreadPoolExecutor(1) +if a.resume: + recovery=torch.load(a.resume,map_location='cpu',weights_only=False) + rng.bit_generator.state=recovery['batch_rng_state'];sampler.rng.bit_generator.state=recovery['sampler_rng_state'] + for name,state in recovery.get('sampler_rng_states',{}).items():getattr(sampler,name).bit_generator.state=state + torch.set_rng_state(recovery['torch_rng_state']);torch.cuda.set_rng_state_all(recovery['cuda_rng_state']) + pending=recovery['prefetched_batch'];del recovery + future=pool.submit(lambda:pending) +else:future=pool.submit(next_batch) +parameters=sum(p.numel() for p in model.parameters()) +(out/'config.json').write_text(json.dumps({**vars(a),'model':model.config,'parameters':parameters},indent=2)) +print(json.dumps({'parameters':parameters,'starting_step':start_step,'stream_seed':stream_seed,'restored_complete_training_state':bool(a.resume)}),flush=True) +started=time.monotonic();losses=[] +def atomic_save(obj,path): + torch.save(obj,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) +def save(step,include_selection_weights=True): + global future + pending_batch=future.result() + common={'config':model.config,'step':step,'args':vars(a),'lr_multipliers':multipliers, + 'parent_checkpoints':list(dict.fromkeys(lineage_parents+(teacher.checkpoints if teacher else [])+(experts.checkpoints if experts else [])))} + if include_selection_weights: + for prefix,state in [('step',model.state_dict()),('ema',ema)]: + atomic_save({**common,'model':state,'ema':prefix=='ema'},out/f'{prefix}{step:06d}.pt') + atomic_save({**common,'model':model.state_dict(),'optimizer':opt.state_dict(),'ema_state':ema, + 'prefetched_batch':pending_batch,'batch_rng_state':copy.deepcopy(rng.bit_generator.state), + 'sampler_rng_state':copy.deepcopy(sampler.rng.bit_generator.state), + 'sampler_rng_states':{name:copy.deepcopy(value.bit_generator.state) for name,value in vars(sampler).items() if isinstance(value,np.random.Generator)}, + 'torch_rng_state':torch.get_rng_state(),'cuda_rng_state':torch.cuda.get_rng_state_all()},out/'recovery.pt') + future=pool.submit(lambda:pending_batch) +for step in range(start_step+1,a.steps+1): + if a.reset_at>=0 and step==a.reset_at+1 and start_step=a.halt_after) + selection_checkpoint=step%a.save_every==0 or step==a.steps or stop + # Persist a complete state before a fresh/resumed job warms its remaining compiled shapes. + if selection_checkpoint or step%a.recovery_every==0 or step==start_step+1: + save(step,include_selection_weights=selection_checkpoint) + if stop:break +pool.shutdown() +print(json.dumps({'completed_step':step,'training_process_loop_seconds':time.monotonic()-started}),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/parent_manifest.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/parent_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..cdcb43849862b02b3a0793b10f4b1ab7f66851c0 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/parent_manifest.json @@ -0,0 +1,1812 @@ +{ + "name": "direct-seasonal-six-member-equal-blend", + "contract": "timeseries-forecast/v1", + "parameters": 549426472, + "pretrained_assets": [], + "sources_used": [ + "gifteval_pretrain/BEIJING_SUBWAY_30MIN", + "gifteval_pretrain/HZMETRO", + "gifteval_pretrain/LOS_LOOP", + "gifteval_pretrain/PEMS03", + "gifteval_pretrain/PEMS04", + "gifteval_pretrain/PEMS07", + "gifteval_pretrain/PEMS08", + "gifteval_pretrain/PEMS_BAY", + "gifteval_pretrain/Q-TRAFFIC", + "gifteval_pretrain/SHMETRO", + "gifteval_pretrain/alibaba_cluster_trace_2018", + "gifteval_pretrain/australian_electricity_demand", + "gifteval_pretrain/azure_vm_traces_2017", + "gifteval_pretrain/bdg-2_bear", + "gifteval_pretrain/bdg-2_fox", + "gifteval_pretrain/bdg-2_panther", + "gifteval_pretrain/bdg-2_rat", + "gifteval_pretrain/bitcoin_with_missing", + "gifteval_pretrain/borealis", + "gifteval_pretrain/borg_cluster_data_2011", + "gifteval_pretrain/buildings_900k", + "gifteval_pretrain/bull", + "gifteval_pretrain/cdc_fluview_ilinet", + "gifteval_pretrain/cdc_fluview_who_nrevss", + "gifteval_pretrain/china_air_quality", + "gifteval_pretrain/cif_2016_12", + "gifteval_pretrain/cif_2016_6", + "gifteval_pretrain/cmip6_2000", + "gifteval_pretrain/cmip6_2005", + "gifteval_pretrain/cmip6_2010", + "gifteval_pretrain/cockatoo", + "gifteval_pretrain/covid19_energy", + "gifteval_pretrain/covid_mobility", + "gifteval_pretrain/elecdemand", + "gifteval_pretrain/elf", + "gifteval_pretrain/era5_2010", + "gifteval_pretrain/era5_2011", + "gifteval_pretrain/era5_2012", + "gifteval_pretrain/era5_2013", + "gifteval_pretrain/era5_2014", + "gifteval_pretrain/era5_2015", + "gifteval_pretrain/era5_2016", + "gifteval_pretrain/era5_2017", + "gifteval_pretrain/era5_2018", + "gifteval_pretrain/extended_web_traffic_with_missing", + "gifteval_pretrain/favorita_sales", + "gifteval_pretrain/favorita_transactions", + "gifteval_pretrain/gfc12_load", + "gifteval_pretrain/gfc14_load", + "gifteval_pretrain/gfc17_load", + "gifteval_pretrain/godaddy", + "gifteval_pretrain/hog", + "gifteval_pretrain/ideal", + "gifteval_pretrain/kaggle_web_traffic_weekly", + "gifteval_pretrain/kdd2022", + "gifteval_pretrain/largest_2017", + "gifteval_pretrain/largest_2018", + "gifteval_pretrain/largest_2019", + "gifteval_pretrain/largest_2020", + "gifteval_pretrain/largest_2021", + "gifteval_pretrain/lcl", + "gifteval_pretrain/london_smart_meters_with_missing", + "gifteval_pretrain/m1_monthly", + "gifteval_pretrain/m1_quarterly", + "gifteval_pretrain/m1_yearly", + "gifteval_pretrain/m5", + "gifteval_pretrain/monash_m3_monthly", + "gifteval_pretrain/monash_m3_other", + "gifteval_pretrain/monash_m3_quarterly", + "gifteval_pretrain/nn5_daily_with_missing", + "gifteval_pretrain/nn5_weekly", + "gifteval_pretrain/oikolab_weather", + "gifteval_pretrain/pdb", + "gifteval_pretrain/project_tycho", + "gifteval_pretrain/residential_load_power", + "gifteval_pretrain/residential_pv_power", + "gifteval_pretrain/rideshare_with_missing", + "gifteval_pretrain/sceaux", + "gifteval_pretrain/smart", + "gifteval_pretrain/solar_power", + "gifteval_pretrain/spain", + "gifteval_pretrain/subseasonal", + "gifteval_pretrain/subseasonal_precip", + "gifteval_pretrain/sunspot_with_missing", + "gifteval_pretrain/taxi_30min", + "gifteval_pretrain/tourism_quarterly", + "gifteval_pretrain/tourism_yearly", + "gifteval_pretrain/traffic_hourly", + "gifteval_pretrain/traffic_weekly", + "gifteval_pretrain/uber_tlc_daily", + "gifteval_pretrain/uber_tlc_hourly", + "gifteval_pretrain/vehicle_trips_with_missing", + "gifteval_pretrain/wiki-rolling_nips", + "gifteval_pretrain/wind_farms_with_missing", + "gifteval_pretrain/wind_power", + "synthetic:both original and sign-reflected orientations of each sampled allowed or locally generated window; paired quantile loss, seed 197", + "synthetic:both original and sign-reflected orientations of each sampled allowed or locally generated window; paired quantile loss, seed 307", + "synthetic:both original and sign-reflected orientations of each sampled allowed or locally generated window; paired quantile loss, seed 401", + "synthetic:both original and sign-reflected orientations of each sampled allowed or locally generated window; paired quantile loss, seed 809", + "synthetic:both original and sign-reflected orientations of each sampled window, seed 197", + "synthetic:independent sign reflection of sampled allowed-corpus and locally generated windows; seeds 43,47,59,79,89,197", + "synthetic:own Fourier/trend/AR/intermittent/changepoint generator at weekly periods52,1, replacing a Bernoulli1/11 share of the original synthetic rows with unchanged total synthetic fraction; independent seed 1000200", + "synthetic:own Fourier/trend/intermittent generator with AR time constant log-uniform from 1 to 10000 steps and zero initial state; seed 307", + "synthetic:own Fourier/trend/intermittent generator with AR time constant log-uniform from 1 to 10000 steps and zero initial state; seed 79", + "synthetic:own Fourier/trend/intermittent generator with AR time constant log-uniform from 1 to 10000 steps and zero initial state; seed 809", + "synthetic:own direct_v1 Fourier seasons, damped trends, AR noise, changepoints and intermittent demand; seeds 23,43,47,59,79,89,197", + "synthetic:own direct_v1 Fourier seasons, damped trends, AR noise, changepoints and intermittent demand; seeds 23,43,47,59,79,89,197,401", + "synthetic:own direct_v1 Fourier seasons, damped trends, AR noise, changepoints and intermittent demand; seeds 23,43,47,59,79,89,197,503,577,661", + "synthetic:own direct_v1 Fourier seasons, damped trends, AR noise, changepoints and intermittent demand; seeds 307", + "synthetic:own direct_v1 Fourier seasons, damped trends, AR noise, changepoints and intermittent demand; seeds 307,809", + "synthetic:own random requested-horizon prefixes, half of rows retain the full horizon and half use a patch-rounded prefix between one-quarter and the full horizon; independent seed 300200", + "synthetic:own random requested-horizon prefixes, half of rows retain the full horizon and half use a patch-rounded prefix between one-quarter and the full horizon; independent seed 300310", + "synthetic:own random requested-horizon prefixes, half of rows retain the full horizon and half use a patch-rounded prefix between one-quarter and the full horizon; independent seed 300404", + "synthetic:own random requested-horizon prefixes, half of rows retain the full horizon and half use a patch-rounded prefix between one-quarter and the full horizon; independent seed 300812", + "synthetic:own stationary Gaussian residuals generated by FFT, equal Matern0.5/1.5/2.5 and RBF spectral families, length scale log-uniform1to10000, theoretical unit marginal variance, FFT size next power of two at least4times window; replacing half of original synthetic residuals with all other generator components unchanged; independent seed 1100200" + ], + "members": [ + { + "weights": "member0.pt", + "weights_sha256": "0b11b7351a4a92d1d18c71a4159ec445be3a94ace8c7a9fa0edafad87d14e960", + "parameters": 36899168, + "config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true, + "seasonal_dispersion_features": true, + "seasonal_width_features": true + }, + "model_code": "model0.py" + }, + { + "weights": "member1.pt", + "weights_sha256": "308389b7217c080af9eb185559d4ee3cafa0f3e0f8c4dd8f5526b68198c89988", + "parameters": 36665488, + "config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "model_code": "model1.py" + }, + { + "weights": "member2.pt", + "weights_sha256": "1a2fb20a9fb5cae6526f2e36ea47559626bece78fd9c284899836505030ae9fe", + "parameters": 36601928, + "config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 4, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "input_patch": 8 + }, + "model_code": "model2.py" + }, + { + "weights": "member3.pt", + "weights_sha256": "d7cfcd72c3cb84aa69e447b76c4c3ab98c21b7c600a463f0b805f4b4300baf33", + "parameters": 146477344, + "config": { + "d": 1024, + "heads": 16, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "model_code": "model3.py" + }, + { + "weights": "member4.pt", + "weights_sha256": "2877a38b94a7d77a53a9df410349cecc2f6ab134c83a76744924543bbe73eb17", + "parameters": 146206864, + "config": { + "d": 1024, + "heads": 16, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "model_code": "model4.py" + }, + { + "weights": "member5.pt", + "weights_sha256": "4b309f0721378f97db815dd511b8b54711348270c48e9eae0103dba506f66708", + "parameters": 146575680, + "config": { + "d": 1024, + "heads": 16, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true + }, + "model_code": "model5.py" + } + ], + "checkpoint_sha256": "20f014ca61a9cfa4f275d9d7abfd297561ac37fddcdae9ba2ef60d3fca106cf8", + "checkpoint_digest_method": "SHA-256 of config.json, including ordered member weight hashes", + "training_lineage": [ + { + "checkpoint": "seasonal_width_transfer12k.pt", + "sha256": "0b11b7351a4a92d1d18c71a4159ec445be3a94ace8c7a9fa0edafad87d14e960", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true, + "seasonal_dispersion_features": true, + "seasonal_width_features": true + }, + "conversion": { + "method": "matched direct-width-head training delta, separately zero-extending base and control", + "formula": "zero_extend(E117first)+E129-zero_extend(E119)", + "coefficient": 1.0, + "base_zero_parameters": [ + "dispersion_query.weight", + "width_head.bias", + "width_head.weight" + ], + "control_zero_parameters": [ + "width_head.bias", + "width_head.weight" + ], + "dispersion_query": "candidate-minus-control only; no E128 correction", + "parent_hashes": { + "/workspace/research/long_seasonal_transfer12k.pt": "8a2b252b733cc79c31778ea27ba00fbe61206fef50454514b667c54a928d80a4", + "/workspace/research/runs/seasonal_width/ema012000.pt": "8a8c75cafcc7b42266aaab7d8458cb383b65313ce6da8c396e76760f7ab6e33c", + "/workspace/research/runs/seasonal_dispersion/ema012000.pt": "b0204fa8dd3371d9160fc00545d6b065ccb23bb18e345b3b63cd39c024c9acf5" + }, + "base_extension_forward_bitwise_equal": true, + "finite_ordered_fixture": true, + "check_seed": 769, + "seconds": 2.078599537955597, + "optimizer_updates": 0, + "validation_data_read": false + }, + "parents": [ + "long_seasonal_transfer12k.pt", + "runs/seasonal_width/ema012000.pt", + "runs/seasonal_dispersion/ema012000.pt" + ] + }, + { + "checkpoint": "long_seasonal_transfer12k.pt", + "sha256": "8a2b252b733cc79c31778ea27ba00fbe61206fef50454514b667c54a928d80a4", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true + }, + "conversion": { + "method": "matched training delta after zero extension of new seasonal query/head parameters", + "formula": "extend_zero(base) + candidate - extend_zero(control)", + "coefficient": 1.0, + "new_parameters_from_candidate": [ + "long_head.bias", + "long_head.weight", + "long_query.weight" + ], + "parent_hashes": { + "/workspace/research/spectral_add_delta6k.pt": "c3dfc433d51355228fc13d04913db1a7edf83030c33283b150bdcc50f5ae6ea2", + "/workspace/research/runs/long_seasonal/ema012000.pt": "d512cdac520239f0c10e021721424d87cee30086fa70f6cbc41f21e2e04988c3", + "/workspace/research/runs/overflow_control/ema012000.pt": "f11d056b95f1c5eeef174265ebc51742952600e0dae1fa52900860447d5be819" + }, + "base_extension_forward_bitwise_equal": true, + "check_seed": 571, + "seconds": 2.5279976530000567, + "optimizer_updates": 0, + "validation_data_read": false + }, + "parents": [ + "spectral_add_delta6k.pt", + "runs/long_seasonal/ema012000.pt", + "runs/overflow_control/ema012000.pt" + ] + }, + { + "checkpoint": "runs/seasonal_width/ema012000.pt", + "sha256": "8a8c75cafcc7b42266aaab7d8458cb383b65313ce6da8c396e76760f7ab6e33c", + "step": 12000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null, + "teacher_coefficient": null, + "compile_teacher": false, + "visibility_curriculum": false + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true, + "seasonal_dispersion_features": true, + "seasonal_width_features": true + }, + "parents": [ + "seasonal_width_initial.pt", + "seasonal_dispersion_initial.pt" + ] + }, + { + "checkpoint": "runs/seasonal_dispersion/ema012000.pt", + "sha256": "b0204fa8dd3371d9160fc00545d6b065ccb23bb18e345b3b63cd39c024c9acf5", + "step": 12000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null, + "teacher_coefficient": null + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true, + "seasonal_dispersion_features": true + }, + "parents": [ + "seasonal_dispersion_initial.pt", + "long_seasonal_initial.pt" + ] + }, + { + "checkpoint": "spectral_add_delta6k.pt", + "sha256": "c3dfc433d51355228fc13d04913db1a7edf83030c33283b150bdcc50f5ae6ea2", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/weekly_slow_ar_delta6k.pt": "c8adf9cadf97dac5e120d8d4d2c8c025bffa2e8b55d8664bf900cce55d00a70b", + "/workspace/research/runs/spectral_synth/ema006000.pt": "683f3824d3c1f605d17bb08d3eef127a54c67eca3867cfbcf1158710a55c4b24", + "/workspace/research/runs/overflow_control/ema006000.pt": "b19875c52ed5024383fb69ccc48cb07a5629ad8011abf134c7dcfcdc50fae2af" + }, + "seconds": 1.4204325219616294 + }, + "parents": [ + "weekly_slow_ar_delta6k.pt", + "runs/spectral_synth/ema006000.pt", + "runs/overflow_control/ema006000.pt" + ] + }, + { + "checkpoint": "runs/long_seasonal/ema012000.pt", + "sha256": "d512cdac520239f0c10e021721424d87cee30086fa70f6cbc41f21e2e04988c3", + "step": 12000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null, + "teacher_coefficient": null + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true + }, + "parents": [ + "long_seasonal_initial.pt", + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "runs/overflow_control/ema012000.pt", + "sha256": "f11d056b95f1c5eeef174265ebc51742952600e0dae1fa52900860447d5be819", + "step": 12000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "seasonal_width_initial.pt", + "sha256": "94ba155b90c6b510bccf92358cc225afe8f317285a19637ab5ca68072bbb83d1", + "step": 0, + "seed": 661, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "long_seasonal_features": true, + "seasonal_dispersion_features": true, + "seasonal_width_features": true + }, + "conversion": { + "method": "zero-initialized direct seasonal width head", + "parent_sha256": "5f07cac4fe7de3e878a01cb90384e79905fdb3156122b568e82c5923526aca3c", + "initial_function_bitwise_equal": true + }, + "parents": [ + "seasonal_dispersion_initial.pt" + ] + }, + { + "checkpoint": "seasonal_dispersion_initial.pt", + "sha256": "5f07cac4fe7de3e878a01cb90384e79905fdb3156122b568e82c5923526aca3c", + "step": 0, + "seed": 577, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "long_seasonal_features": true, + "seasonal_dispersion_features": true + }, + "conversion": { + "method": "zero-initialized phase-specific cycle-centered standard-deviation query", + "parent_sha256": "470ef98d69d00b17defbf41c70a92b22574154cdb6e0317993bccf113e4af93b", + "initial_function_bitwise_equal": true + }, + "parents": [ + "long_seasonal_initial.pt" + ] + }, + { + "checkpoint": "long_seasonal_initial.pt", + "sha256": "470ef98d69d00b17defbf41c70a92b22574154cdb6e0317993bccf113e4af93b", + "step": 0, + "seed": 503, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "long_seasonal_features": true + }, + "conversion": { + "method": "zero-initialized sixteen-cycle centered seasonal query/head additions", + "parent_sha256": "22c08571978be31ba57368eb983089a40a44d56d4ae5e17da41afd2a761a258c", + "initial_function_bitwise_equal": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "weekly_slow_ar_delta6k.pt", + "sha256": "c8adf9cadf97dac5e120d8d4d2c8c025bffa2e8b55d8664bf900cce55d00a70b", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/postloss_slow_ar_delta6k.pt": "0ae7875b49b99a44c295dc2b8243327aeacadc25b2354988abb2c37250359a49", + "/workspace/research/runs/weekly_synth/ema006000.pt": "de053e5baf9641e9245519990d6e5193fc91392cb76e72ceffee1ce63f578fca", + "/workspace/research/runs/overflow_control/ema006000.pt": "b19875c52ed5024383fb69ccc48cb07a5629ad8011abf134c7dcfcdc50fae2af" + }, + "seconds": 2.0751679679378867 + }, + "parents": [ + "postloss_slow_ar_delta6k.pt", + "runs/weekly_synth/ema006000.pt", + "runs/overflow_control/ema006000.pt" + ] + }, + { + "checkpoint": "runs/spectral_synth/ema006000.pt", + "sha256": "683f3824d3c1f605d17bb08d3eef127a54c67eca3867cfbcf1158710a55c4b24", + "step": 6000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null, + "teacher_coefficient": null, + "spectral_synthetic_seed": 1100200, + "spectral_replacement_probability": 0.5, + "spectral_length_scale": [ + 1, + 10000 + ], + "spectral_families": [ + "Matern0.5", + "Matern1.5", + "Matern2.5", + "RBF" + ] + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt", + "runs/confidence_query/ema006000.pt", + "runs/horizon_jitter/ema012000.pt", + "runs/large_corpus_control/ema012000.pt" + ] + }, + { + "checkpoint": "runs/overflow_control/ema006000.pt", + "sha256": "b19875c52ed5024383fb69ccc48cb07a5629ad8011abf134c7dcfcdc50fae2af", + "step": 6000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "horizon_delta12k.pt", + "sha256": "22c08571978be31ba57368eb983089a40a44d56d4ae5e17da41afd2a761a258c", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/runs/confidence_query/ema006000.pt": "0bad97e8994aac49ea173443db0a4fa8d72d33f9eb9e2660f06de75f7f1403eb", + "/workspace/research/runs/horizon_jitter/ema012000.pt": "830179d763916a1065fc615d2c5e22f4a3b5b19390dde707ab0f057e13cadff6", + "/workspace/research/runs/large_corpus_control/ema012000.pt": "7f9ba5e01ac59c51a3b63d3067b442e23e15d0abc51ddbcccdd04d6083ae4add" + }, + "seconds": 1.2663014469435439 + }, + "parents": [ + "runs/confidence_query/ema006000.pt", + "runs/horizon_jitter/ema012000.pt", + "runs/large_corpus_control/ema012000.pt" + ] + }, + { + "checkpoint": "postloss_slow_ar_delta6k.pt", + "sha256": "0ae7875b49b99a44c295dc2b8243327aeacadc25b2354988abb2c37250359a49", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/runs/postloss/ema003000.pt": "82c785d40998e155a20290c9965c346c26cd397fa0f3cf36278377ad2aed5c7d", + "/workspace/research/runs/long_memory_synth_recovery/ema006000.pt": "fea5b5290a3a9be5618eaeaf67e918e4f677d5be908d562040ce4bdfeb549bd9", + "/workspace/research/runs/partial_targets/ema006000.pt": "67562486b099a350da53c3caa5ff0932fe7fecdfe72c1879b064b2a9bb173dfb" + }, + "seconds": 1.0092943429481238 + }, + "parents": [ + "runs/postloss/ema003000.pt", + "runs/long_memory_synth_recovery/ema006000.pt", + "runs/partial_targets/ema006000.pt" + ] + }, + { + "checkpoint": "runs/weekly_synth/ema006000.pt", + "sha256": "de053e5baf9641e9245519990d6e5193fc91392cb76e72ceffee1ce63f578fca", + "step": 6000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true, + "weekly_synthetic_seed": 1000200, + "weekly_replacement_probability": 0.09090909090909091, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "runs/confidence_query/ema006000.pt", + "sha256": "0bad97e8994aac49ea173443db0a4fa8d72d33f9eb9e2660f06de75f7f1403eb", + "step": 6000, + "seed": 89, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 0.0002, + "steps": 6000 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true + }, + "parents": [ + "runs/recency_features/ema024000.pt" + ] + }, + { + "checkpoint": "runs/horizon_jitter/ema012000.pt", + "sha256": "830179d763916a1065fc615d2c5e22f4a3b5b19390dde707ab0f057e13cadff6", + "step": 12000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "partial_target_lengths": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/large_corpus_control/ema012000.pt", + "sha256": "7f9ba5e01ac59c51a3b63d3067b442e23e15d0abc51ddbcccdd04d6083ae4add", + "step": 12000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/postloss/ema003000.pt", + "sha256": "82c785d40998e155a20290c9965c346c26cd397fa0f3cf36278377ad2aed5c7d", + "step": 3000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "fixed_postprocessing_loss": true, + "normalization_overflow_fallback": true + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "runs/long_memory_synth_recovery/ema006000.pt", + "sha256": "fea5b5290a3a9be5618eaeaf67e918e4f677d5be908d562040ce4bdfeb549bd9", + "step": 6000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "context": null, + "sample_context": 4096, + "synthetic_ar_time_constants": [ + 1, + 10000 + ] + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "partial_target_lengths": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/partial_targets/ema006000.pt", + "sha256": "67562486b099a350da53c3caa5ff0932fe7fecdfe72c1879b064b2a9bb173dfb", + "step": 6000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "partial_target_lengths": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/recency_features/ema024000.pt", + "sha256": "1530fbb577a87ca4eb39da83d6fee9b8ee5bc924202e021e3a7b56493112f564", + "step": 24000, + "seed": 59, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/patch16_trial/ema006000.pt" + ] + }, + { + "checkpoint": "runs/recency_features/ema012000.pt", + "sha256": "8ccb6870a025e1097331a3a288b1183741a413f3460fbf3352d0c589c6a4394c", + "step": 12000, + "seed": 59, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/patch16_trial/ema006000.pt" + ] + }, + { + "checkpoint": "runs/patch16_trial/ema006000.pt", + "sha256": "0ff54447074e0271d2e331c7d3e6e9e0fdd73353e4d8cef0175ff627385f71c3", + "step": 6000, + "seed": 47, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024 + }, + "parents": [ + "patch16_init.pt" + ] + }, + { + "checkpoint": "patch16_init.pt", + "sha256": "d69531bfde5bf801e7f36c515bf15fd0cae0bd84f7d1479d35f4a7b67f26b508", + "step": 6000, + "seed": 43, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024 + }, + "conversion": { + "from_checkpoint": "/run-state/workspace/research/runs/large_sign/ema006000.pt", + "from_sha256": "96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547", + "method": "fold input/query halves by summation; retain first 16 output rows; preserve physical positional units" + }, + "parents": [ + "runs/large_sign/ema006000.pt" + ] + }, + { + "checkpoint": "runs/large_sign/ema006000.pt", + "sha256": "96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547", + "step": 6000, + "seed": 43, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 32, + "max_context": 4096, + "max_horizon": 1024 + }, + "parents": [ + "runs/direct_large/step024000.pt" + ] + }, + { + "checkpoint": "runs/direct_large/step024000.pt", + "sha256": "b7e4f38aebcd2cf38ce484edaad8d19851317fb3b8df485e2faa0d0423cbcb48", + "step": 24000, + "seed": 23, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 128, + "lr": 0.0002, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 32, + "max_context": 4096, + "max_horizon": 1024 + }, + "initialization": "random initialization in this workspace" + }, + { + "checkpoint": "runs/patch8/ema006000.pt", + "sha256": "308389b7217c080af9eb185559d4ee3cafa0f3e0f8c4dd8f5526b68198c89988", + "step": 6000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "patch8_initial.pt" + ] + }, + { + "checkpoint": "patch8_initial.pt", + "sha256": "e7da4d47a9cc984a9423296679d7c9127ef2d679be950b9e8d3758e6fca074cc", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "from_checkpoint": "/run-state/workspace/research/horizon_delta12k.pt", + "from_sha256": "22c08571978be31ba57368eb983089a40a44d56d4ae5e17da41afd2a761a258c", + "method": "fold input/query/recency halves by summation; retain first8 output rows; preserve physical position units", + "exact_function_preservation": false + }, + "parents": [ + "horizon_delta12k.pt", + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "runs/split_patch/ema012000.pt", + "sha256": "1a2fb20a9fb5cae6526f2e36ea47559626bece78fd9c284899836505030ae9fe", + "step": 12000, + "seed": 401, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 32, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300404 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 4, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "input_patch": 8 + }, + "parents": [ + "split_patch_initial.pt" + ] + }, + { + "checkpoint": "split_patch_initial.pt", + "sha256": "0719b4dce554764ef69181d8b19d8da11849ef32b35391ffee6700e639a73114", + "step": 0, + "seed": null, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 4, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "input_patch": 8 + }, + "conversion": { + "method": "retain input8; sum query/recency halves and keep first4 output rows; same physical position coordinates", + "exact_function_preservation": false, + "parent_sha256": "308389b7217c080af9eb185559d4ee3cafa0f3e0f8c4dd8f5526b68198c89988" + }, + "parents": [ + "runs/patch8/ema006000.pt", + "runs/patch8/ema006000.pt" + ] + }, + { + "checkpoint": "runs/random_capacity_1024/ema096000.pt", + "sha256": "d7cfcd72c3cb84aa69e447b76c4c3ab98c21b7c600a463f0b805f4b4300baf33", + "step": 96000, + "seed": 307, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 48, + "lr": 0.0002, + "steps": 96000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": true, + "synthetic_ar_time_constants": [ + 1, + 10000 + ], + "requested_horizon_seed": 300310, + "normalization_overflow_fallback": true + }, + "model_config": { + "d": 1024, + "heads": 16, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "random_capacity_1024_initial.pt" + ] + }, + { + "checkpoint": "random_capacity_1024_initial.pt", + "sha256": "c9693619ca6277c26fef3b2bde37ff6796bec97b3af9f94588bbc5ddd329ec90", + "step": 0, + "seed": 307, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 1024, + "heads": 16, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "initialization": "random initialization in this workspace" + }, + { + "checkpoint": "runs/capacity_patch8_candidate/ema006000.pt", + "sha256": "2877a38b94a7d77a53a9df410349cecc2f6ab134c83a76744924543bbe73eb17", + "step": 6000, + "seed": 809, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 32, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": true, + "synthetic_ar_time_constants": [ + 1, + 10000 + ], + "requested_horizon_seed": 300812, + "normalization_overflow_fallback": true, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null, + "teacher_coefficient": null, + "compile_teacher": false, + "visibility_curriculum": false + }, + "model_config": { + "d": 1024, + "heads": 16, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "capacity_patch8_initial.pt", + "runs/random_capacity_1024/ema096000.pt" + ] + }, + { + "checkpoint": "capacity_patch8_initial.pt", + "sha256": "3fef8f613e5fad3633e4fafe697453e2fe3691678fa581c8a2fea3e6da3de2c1", + "step": 96000, + "seed": 307, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 48, + "lr": 0.0002, + "steps": 96000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": true, + "synthetic_ar_time_constants": [ + 1, + 10000 + ], + "requested_horizon_seed": 300310, + "normalization_overflow_fallback": true + }, + "model_config": { + "d": 1024, + "heads": 16, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "from_checkpoint": "/run-state/workspace/research/runs/random_capacity_1024/ema096000.pt", + "from_sha256": "d7cfcd72c3cb84aa69e447b76c4c3ab98c21b7c600a463f0b805f4b4300baf33", + "method": "fold input/query/recency halves by summation; retain first8 output rows; preserve physical position units", + "exact_function_preservation": false + }, + "parents": [ + "runs/random_capacity_1024/ema096000.pt", + "runs/random_capacity_1024/ema096000.pt" + ] + }, + { + "checkpoint": "runs/random_capacity_long_seasonal/ema048000.pt", + "sha256": "4b309f0721378f97db815dd511b8b54711348270c48e9eae0103dba506f66708", + "step": 48000, + "seed": 307, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 48, + "lr": 0.0002, + "steps": 96000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": true, + "synthetic_ar_time_constants": [ + 1, + 10000 + ], + "requested_horizon_seed": 300310, + "normalization_overflow_fallback": true, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null, + "teacher_coefficient": null, + "compile_teacher": false, + "visibility_curriculum": false + }, + "model_config": { + "d": 1024, + "heads": 16, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true + }, + "parents": [ + "random_capacity_long_seasonal_initial.pt", + "random_capacity_1024_initial.pt" + ] + }, + { + "checkpoint": "random_capacity_long_seasonal_initial.pt", + "sha256": "f7e35a6341ffc6c1ce53cfd8934256dde937171f5002f1fc34b1fd169f1a15d6", + "step": 0, + "seed": 307, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 1024, + "heads": 16, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true + }, + "conversion": { + "method": "zero-initialize E107 seasonal query/head on own untrained E79random146M backbone", + "parent_sha256": "c9693619ca6277c26fef3b2bde37ff6796bec97b3af9f94588bbc5ddd329ec90", + "fixture_seed": 677, + "initial_function_bitwise_equal": true, + "optimizer_updates": 0 + }, + "parents": [ + "random_capacity_1024_initial.pt" + ] + } + ], + "ensemble_weights_by_horizon": { + "below720": [ + 0.25, + 0.25, + 0.25, + 0.125, + 0, + 0.125 + ], + "at_least720": [ + 0.25, + 0.25, + 0.25, + 0, + 0.125, + 0.125 + ] + }, + "every_member_forecasts_every_instance": true, + "member_history_caps": [ + { + "input_and_summary": 4096, + "encoder_and_normalization": 4096, + "fixed_rules": 4096 + }, + { + "input_and_summary": 4096, + "encoder_and_normalization": 4096, + "fixed_rules": 4096 + }, + { + "input_and_summary": 4096, + "encoder_and_normalization": 4096, + "fixed_rules": 4096 + }, + { + "input_and_summary": 4096, + "encoder_and_normalization": 4096, + "fixed_rules": 4096 + }, + { + "input_and_summary": 4096, + "encoder_and_normalization": 4096, + "fixed_rules": 4096 + }, + { + "input_and_summary": 4096, + "encoder_and_normalization": 4096, + "fixed_rules": 4096 + } + ], + "postprocessing_order": "each member: sign averaging, positivity, aligned seasonal rule, continuity, zero0.4, finite-value replacement; then form ordered E154 horizon-rule quarter mean and E156 seasonal48 quarter mean, and average those two in FP32 with equal weight", + "runtime_code_sha256": { + "infer.sh": "5fe66b4fe9a4787285d830cfd96975701e97286a75ba7c3687bd8891475edf68", + "seasonal.py": "b946e63048196ab5ea8b249137d48c80d8510943caccd0f180e4fb86d9b24b37", + "predict.py": "7e3bf8bbbcfefbc654c22d6923fadd8f73cb056316abe7928ca8d6b66db7deb8", + "continuity.py": "dbb08d2229ad80ad00f638b0b9f2f6ca13c663e0fd6730058e5fee8ff54545d5", + "model3.py": "44eeb23c037e91b8f67e432615ce46540a7ac4242919785f9c4218de23121499", + "zero_mass.py": "f079d509009bcda409b80eb64467c869b838cfbab11b2bd4c660c2875b6642fe", + "ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "model5.py": "3eaa4aed0a1c62b80d94be6c3084b10a594e9fce17444eac17ca3f1b0b5c549e", + "model0.py": "0d9557eca352e3c493f47c310355aa576da2e75c8f7cb5b69786c3d162644f38", + "model2.py": "89bb87b2501b117ac02daf001a68f389ec488931ce18905445d15874760685be", + "model1.py": "c27748fa4b1186b513f76eca26052753b8dcd1794994e5989addaf371ca70f2e", + "model.py": "c27748fa4b1186b513f76eca26052753b8dcd1794994e5989addaf371ca70f2e", + "model4.py": "44eeb23c037e91b8f67e432615ce46540a7ac4242919785f9c4218de23121499" + }, + "notes": "All members originate from random initialization in this workspace. Only declared pretraining sources and local generators were used. Validation is selection/diagnostics only. No inference-time fitting or parameter adaptation." +} diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/promote.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/promote.py new file mode 100644 index 0000000000000000000000000000000000000000..4dd36a4630051ccf4933d09da4fe4279397a3eff --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/promote.py @@ -0,0 +1,56 @@ +"""Publish E172 only after complete replay, exact component checks and current-best gain.""" +import datetime,hashlib,json,os,subprocess +from pathlib import Path +R=Path('/workspace/research');read=lambda path:json.loads(Path(path).read_text()) +package=R/'candidate-gate-six-blend';report_path=R/'valid-report-gate-six-blend.json' +report=read(report_path);validated=read(package/'model_manifest.json') +suite=read(R/'gate_six_blend_validation_receipt.json');selection=read(R/'gate_six_blend_receipt.json');d=read(R/'gate_six_blend/declaration.json') +assert selection['selection_gate_passed'] and suite['status']=='complete; review required' +assert all(row['returncode']==0 for row in suite['steps']) +checks=read(R/'gate_six_blend_package_checks.json') +assert sum(row['configurations'] for row in checks)==3 +assert all(row['bitwise_equal_after_relocation'] and row['finite_and_monotone'] for row in checks) +composition=read(R/'gate_six_blend_composition_checks.json') +assert len(composition['comparisons'])==3 and all(row['bitwise_equal_to_fixed_parent_gate_blend'] for row in composition['comparisons']) +synthetic=read(R/'gate_six_blend_runtime_checks.json') +assert len(synthetic['checks'])==2 +assert all(row['bitwise_composition'] and row['finite_ordered'] and row['every_member_forecasts_every_instance'] and row['gate_forecasts_every_instance'] for row in synthetic['checks']) +assert validated['checkpoint_sha256']==report['checkpoint_sha256']==synthetic['descriptor_sha256'] +assert validated['pretrained_assets']==[] and validated['parameters']==549432812 +assert validated['every_member_forecasts_every_instance'] and validated['gate_forecasts_every_instance'] +assert validated['gate_blend_coefficient']==.5 and validated['gate_training_step']==6000 +assert validated['gate_weights_sha256']==synthetic['gate_checkpoint_sha256']==d['gate_checkpoint_sha256'] +assert [m['weights_sha256'] for m in validated['members']]==d['member_checkpoint_hashes'] +state=read(R/'CURRENT_RESEARCH_STATE.json');current=state['published'];old=read('/workspace/submission/validation_report.json') +assert read('/workspace/submission/model_manifest.json')['checkpoint_sha256']==current['checkpoint_sha256'] +assert report['n_configs']==97 and report['n_instances']==151170 and report['n_failed']==0 +assert report['skill_score']>old['skill_score'] +cutoffs=['valid_screen','valid_backcast','valid_backcast2','valid_backcast3'];probes=[read(R/f'gate_six_blend_{cutoff}.json') for cutoff in cutoffs] +deltas=[probe['skill_score']-value for probe,value in zip(probes,[current['main_skill']]+current['earlier_skills'])] +assert len(deltas)==4 and sum(value>0 for value in deltas)>=3 and sum(deltas)>0 +parent=R/'candidate-seasonal-six-member-blend';gate=R/'candidate-gate-six-blend-standalone' +assert read(parent/'model_manifest.json')['checkpoint_sha256']==d['parent_descriptor'] +assert read(gate/'model_manifest.json')['gate_weights_sha256']==d['gate_checkpoint_sha256'] +def digest(path): + with Path(path).open('rb') as handle:return hashlib.file_digest(handle,'sha256').hexdigest() +for name,sha in validated['runtime_code_sha256'].items(): + assert digest(package/name)==sha + runtime_source=R/'gate_six_blend/runtime'/name + if runtime_source.exists():assert digest(runtime_source)==sha +for entry in validated['members']:assert digest(package/entry['weights'])==entry['weights_sha256'] +assert digest(package/'gate.pt')==d['gate_checkpoint_sha256'] +subprocess.run(['python3',str(R/'compare_reports.py'),'--candidate',str(report_path),'--parent',current['full_report'],'--out',str(R/'gate_six_blend_current_publication_comparison.json')],check=True) +outcome=f"One fixed equal blend of E159 and E152primary6k gate improves full validation skill from{old['skill_score']:.12f} to{report['skill_score']:.12f}; all97/151170/0fail. Allsix own experts and fixedgate execute everyinstance. Independent synthetic/real composition, actual forward counts and relocation pass. Shared-H100 inference{report['inference_seconds']:.3f}s. Adaptive validation selection, not held-out reward." +subprocess.run(['python3',str(R/'direct_v1/record.py'),str(report_path),'--label','E172 fixed six-expert plus gate half-blend full replay — selected','--outcome',outcome],check=True) +with (R/'direct_v1/EXPERIMENTS.md').open('a') as output: + output.write('\nE172 verifiedsuite '+json.dumps(suite)+'. Synthetic '+json.dumps(synthetic)+'. Currentpublicationcutoffdeltas '+json.dumps(deltas)+'. All immutable teachers/gate expert snapshots remain unchanged.\n') +command=['python3',str(R/'gate_six_blend/publish.py'),'--parent',str(parent),'--gate',str(gate),'--report',str(report_path),'--out','/workspace/submission'] +subprocess.run(command,check=True) +published=read('/workspace/submission/model_manifest.json') +assert published['checkpoint_sha256']==validated['checkpoint_sha256'] and published['runtime_code_sha256']==validated['runtime_code_sha256'] +now=datetime.datetime.now(datetime.timezone.utc).isoformat();state=read(R/'CURRENT_RESEARCH_STATE.json');state.setdefault('previous_published',[]).append(state['published']) +state['published']=dict(experiment='E172 fixed equal blend of E159six-expert forecast and E152primary6k learnedgate, allsix experts andgate computed',package='/workspace/submission',checkpoint_sha256=report['checkpoint_sha256'],parameters=published['parameters'],main_skill=probes[0]['skill_score'],earlier_skills=[probe['skill_score'] for probe in probes[1:]],full_validation_skill=report['skill_score'],full_report=str(report_path),status='published after fullreplay and allchecks',publisher=command[1],publisher_arguments=command[2:],published_utc=now,journal_refreshed_utc=now,validation_receipt=str(R/'gate_six_blend_validation_receipt.json'),package_checks=str(R/'gate_six_blend_package_checks.json'),composition_checks=str(R/'gate_six_blend_composition_checks.json'),synthetic_checks=str(R/'gate_six_blend_runtime_checks.json'),runtime_optimization='shared six-expert meta-device loading plus6340parameter gate; preserve independent ordered parent/gate forecasts before equalmean',runtime_predict_sha256=published['runtime_code_sha256']['predict.py'],notes='Adaptive validation selection only. Immutable E96/E130/E148/E159teachers and expert snapshots remain unchanged.') +state['selection_probes']['E172'].update(status='published after completechecks',published_utc=now,full_skill=report['skill_score']) +p=R/'CURRENT_RESEARCH_STATE.json';temporary=p.with_suffix('.tmp');temporary.write_text(json.dumps(state,indent=2));os.replace(temporary,p) +with (R/'SESSION_20261023_PROGRESS.md').open('a') as output:output.write('\n'+now+': E172 atomically published. '+outcome+' Descriptor'+report['checkpoint_sha256']+'.\n') +print(json.dumps(dict(experiment='E172',utc=now,skill=report['skill_score'],descriptor=report['checkpoint_sha256'])),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/run.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/run.py new file mode 100644 index 0000000000000000000000000000000000000000..175fb2c77054e2ba0d400db1f65bc9f91250dcae --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/run.py @@ -0,0 +1,31 @@ +"""E172 one fixed half-blend, cached validation only, never automatic publication.""" +import datetime,json,subprocess,time +from pathlib import Path +R=Path('/workspace/research');study=R/'gate_six_blend';started=time.monotonic() +d=json.loads((study/'declaration.json').read_text());current=json.loads((R/'CURRENT_RESEARCH_STATE.json').read_text())['published'] +assert current['checkpoint_sha256']==d['parent_descriptor'] +names=['seasonal_width_transfer12k','patch8_ema6000','split_patch_ema12000','random_capacity_1024_ema96000','capacity_patch8_candidate_ema6000','random_capacity_long_seasonal_ema48000'] +rows=[] +for cutoff,folder in [('valid_screen','evals'),('valid_backcast','backcast_evals'),('valid_backcast2','backcast2_evals'),('valid_backcast3','backcast3_evals')]: + out=R/f'gate_six_blend_{cutoff}.json';assert not out.exists() + parent=json.loads((R/f'seasonal_six_member_blend_{cutoff}.json').read_text()) + assert parent['member_checkpoint_hashes']==d['member_checkpoint_hashes'] + gate=R/folder/'ensemble_gate_refresh_ema6000';gate_report=json.loads((gate/'report.json').read_text()) + assert gate_report['checkpoint_sha256']==d['gate_checkpoint_sha256'] and gate_report['expert_descriptor_sha256']==d['gate_expert_descriptor'] and gate_report['n_failed']==0 + command=['python3',str(study/'probe.py'),'--valid',str(R/cutoff),'--out',str(out),'--gate',str(gate)] + for name,sha in zip(names,d['member_checkpoint_hashes']): + report=json.loads((R/folder/name/'report.json').read_text());assert report['checkpoint_sha256']==sha and report['n_failed']==0 + command+=['--pred',str(R/folder/name)] + subprocess.run(command,check=True) + probe=json.loads(out.read_text());assert probe['gate_checkpoint_sha256']==d['gate_checkpoint_sha256'] + rows.append(dict(cutoff=cutoff,skill=probe['skill_score'],control_skill=parent['skill_score'],delta=probe['skill_score']-parent['skill_score'], + groups=probe['groups'],group_deltas={key:{name:value-parent['groups'][key][name] for name,value in group.items()} for key,group in probe['groups'].items()},cpu_seconds=probe['cpu_seconds'])) +assert json.loads((R/'CURRENT_RESEARCH_STATE.json').read_text())['published']['checkpoint_sha256']==current['checkpoint_sha256'] +result=dict(utc=datetime.datetime.now(datetime.timezone.utc).isoformat(),declaration=d,rows=rows, + positive_cutoffs=sum(row['delta']>0 for row in rows),mean_delta=sum(row['delta'] for row in rows)/4, + seconds=time.monotonic()-started,optimizer_updates=0,new_neural_inference=False) +result['selection_gate_passed']=result['positive_cutoffs']>=3 and result['mean_delta']>0 +(R/'gate_six_blend_receipt.json').write_text(json.dumps(result,indent=2)) +with (R/'direct_v1/EXPERIMENTS.md').open('a') as output:output.write('\n'+result['utc']+': E172 fixed half-blend cached comparison '+json.dumps(result)+'. No automaticpublication.\n') +print(json.dumps({k:v for k,v in result.items() if k not in ['declaration','rows']}),flush=True) +for row in rows:print(json.dumps(row),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/validate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/validate.py new file mode 100644 index 0000000000000000000000000000000000000000..ce3389f5de65903945c6e6b9086c4650a4f8020a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/E172/validate.py @@ -0,0 +1,27 @@ +"""E172 full public replay after one fixed cached-cutoff comparison; never auto-publish.""" +import json,os,subprocess,time +from pathlib import Path +R=Path('/workspace/research');selection=json.loads((R/'gate_six_blend_receipt.json').read_text());assert selection['selection_gate_passed'] +current=json.loads((R/'CURRENT_RESEARCH_STATE.json').read_text())['published'] +deltas=[row['skill']-value for row,value in zip(selection['rows'],[current['main_skill']]+current['earlier_skills'])] +assert len(deltas)==4 and sum(value>0 for value in deltas)>=3 and sum(deltas)>0 +package=R/'candidate-gate-six-blend';report=R/'valid-report-gate-six-blend.json';pred=R/'valid-pred-gate-six-blend' +manifest=json.loads((package/'model_manifest.json').read_text());assert manifest['parameters']==549432812 +assert manifest['gate_weights_sha256']==selection['declaration']['gate_checkpoint_sha256'] +assert [entry['weights_sha256'] for entry in manifest['members']]==selection['declaration']['member_checkpoint_hashes'] +started=time.monotonic();receipt=R/'gate_six_blend_validation_receipt.json';assert not receipt.exists() +state=dict(pid=os.getpid(),status='running',package=str(package),steps=[],current_parent=current['checkpoint_sha256'],current_cutoff_deltas=deltas) +def save(): + state['seconds']=time.monotonic()-started;temporary=receipt.with_suffix('.tmp');temporary.write_text(json.dumps(state,indent=2));os.replace(temporary,receipt) +commands=[('synthetic_independent_composition_and_all_forward_calls',['python3',str(R/'gate_six_blend/check_runtime.py')]), + ('relocation',['python3',str(R/'verify_package_examples.py'),'--package',str(package),'--receipt',str(R/'gate_six_blend_package_checks.json')]), + ('full_public_replay',['python3',str(R/'run_package_validation.py'),'--package',str(package),'--out',str(pred),'--report',str(report)]), + ('independent_original_gate_real_replay',['python3',str(R/'run_composition_member.py'),'--package',str(R/'candidate-gate-six-blend-standalone'),'--out',str(R/'composition-pred-gate-six-blend-standalone'),'--receipt',str(R/'gate_six_blend_standalone_composition_replay.json')]), + ('real_composition',['python3',str(R/'gate_six_blend/check_composition.py')]), + ('descriptive_comparison',['python3',str(R/'compare_reports.py'),'--candidate',str(report),'--parent',current['full_report'],'--out',str(R/'gate_six_blend_comparison.json')])] +for label,command in commands: + state['current_step']=label;save();tick=time.monotonic();completed=subprocess.run(command) + state['steps'].append(dict(name=label,returncode=completed.returncode,seconds=time.monotonic()-tick));save() + if completed.returncode:state['status']='failed';save();raise SystemExit(completed.returncode) +full=json.loads(report.read_text());assert full['n_failed']==0 and full['n_configs']==97 and full['n_instances']==151170 +state.update(status='complete; review required',skill=full['skill_score']);save();print(json.dumps(state),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/blend_publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/blend_publish.py new file mode 100644 index 0000000000000000000000000000000000000000..4d8dc6acbf326b792c98ab331aec1d5817571881 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/blend_publish.py @@ -0,0 +1,108 @@ +"""Assemble and atomically publish a complete six-member, fixed-horizon-rule package.""" +import argparse +import ctypes +import hashlib +import json +import os +import shutil +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ap = argparse.ArgumentParser() +ap.add_argument('--member', action='append', required=True) +ap.add_argument('--out', required=True) +ap.add_argument('--report') +ap.add_argument('--experiments', default='/workspace/research/direct_v1/EXPERIMENTS.md') +a = ap.parse_args() +assert len(a.member) == 6 +final = Path(a.out) +stage = final.parent / f'.{final.name}-staging-{os.getpid()}' +shutil.rmtree(stage, ignore_errors=True) +stage.mkdir(parents=True) + +def digest(path): + h = hashlib.sha256() + with Path(path).open('rb') as f: + for block in iter(lambda: f.read(8 * 1024 * 1024), b''): + h.update(block) + return h.hexdigest() + +for name in ('infer.sh', 'predict.py', 'model.py', 'seasonal.py', 'continuity.py', + 'zero_mass.py', 'ts_io.py'): + shutil.copy2(HERE / 'runtime' / name, stage / name) +shutil.copy2('/opt/runtime/requirements.txt', stage / 'requirements.txt') +shutil.copy2(a.experiments, stage / 'EXPERIMENTS.md') +members, sources, lineage = [], set(), {} +for i, source in enumerate(map(Path, a.member)): + manifest = json.loads((source / 'model_manifest.json').read_text()) + assert manifest['pretrained_assets'] == [] + for shared in ['seasonal.py','continuity.py','zero_mass.py']: + assert digest(source/shared)==digest(stage/shared),'Members must retain identical fixed postprocessing rules' + name = f'member{i}.pt' + model_code = f'model{i}.py' + shutil.copy2(source / 'model.py', stage / model_code) + assert digest(stage / model_code) == manifest['runtime_code_sha256']['model.py'] + shutil.copy2(source / 'weights.pt', stage / name) + assert digest(stage / name) == manifest['weights_sha256'] + members.append({'weights': name, 'weights_sha256': manifest['weights_sha256'], + 'parameters': manifest['parameters'], 'config': manifest['config'], 'model_code': model_code}) + sources.update(manifest['sources_used']) + for item in manifest['training_lineage']: + lineage.setdefault(item['sha256'], item) + dst = stage / 'provenance' / f'member{i}' + dst.mkdir(parents=True) + shutil.copy2(source / 'model_manifest.json', dst / 'model_manifest.json') + shutil.copytree(source / 'provenance', dst / 'training') +shutil.copy2(__file__, stage / 'provenance' / 'publish.py') +for script in HERE.glob('*.py'): + shutil.copy2(script, stage / 'provenance' / ('blend_' + script.name)) +descriptor = {'members': members, 'horizon_threshold': 720, 'blend_coefficient': .5, + 'weights_below_threshold': [.25,.25,.25,.125,0,.125], + 'weights_at_or_above_threshold': [.25,.25,.25,0,.125,.125], + 'composition': 'Every member forecasts every instance. A=(F0+F1+F2+F[4 if H>=720 else3])/4 and B=(F0+F1+F2+F5)/4 are ordered FP32 quarter means after fixed member rules; output=(A+B)/2 in FP32'} +(stage / 'config.json').write_text(json.dumps(descriptor, indent=2) + '\n') +identifier = digest(stage / 'config.json') +manifest = { + 'name': 'direct-seasonal-six-member-equal-blend', 'contract': 'timeseries-forecast/v1', + 'parameters': sum(m['parameters'] for m in members), 'pretrained_assets': [], + 'sources_used': sorted(sources), 'members': members, + 'checkpoint_sha256': identifier, + 'checkpoint_digest_method': 'SHA-256 of config.json, including ordered member weight hashes', + 'training_lineage': list(lineage.values()), 'ensemble_weights_by_horizon': {'below720':[.25,.25,.25,.125,0,.125], 'at_least720':[.25,.25,.25,0,.125,.125]}, + 'every_member_forecasts_every_instance': True, + 'member_history_caps': [{'input_and_summary': m['config']['max_context'], 'encoder_and_normalization': m['config'].get('encoder_context',m['config']['max_context']), 'fixed_rules': m['config'].get('encoder_context',m['config']['max_context'])} for m in members], + 'postprocessing_order': 'each member: sign averaging, positivity, aligned seasonal rule, continuity, zero0.4, finite-value replacement; then form ordered E154 horizon-rule quarter mean and E156 seasonal48 quarter mean, and average those two in FP32 with equal weight', + 'runtime_code_sha256': {p.name: digest(p) for p in stage.iterdir() if p.suffix in ('.py', '.sh')}, + 'notes': 'All members originate from random initialization in this workspace. Only declared pretraining sources and local generators were used. Validation is selection/diagnostics only. No inference-time fitting or parameter adaptation.', +} +(stage / 'model_manifest.json').write_text(json.dumps(manifest, indent=2) + '\n') +if a.report: + report = json.loads(Path(a.report).read_text()) + assert report['checkpoint_sha256'] == identifier + shutil.copy2(a.report, stage / 'validation_report.json') +else: + report = {'status': 'candidate validation pending'} + (stage / 'validation_report.json').write_text(json.dumps(report) + '\n') +if final.resolve() == Path('/workspace/submission').resolve(): + assert a.report and report['n_configs'] == 97 and report['n_instances'] == 151170 + assert report['n_failed'] == 0 +patch_sizes = ', '.join(str(m['config'].get('input_patch', m['config']['patch'])) + '/' + str(m['config']['patch']) for m in members) +(stage / 'README.md').write_text(f'''# Six-member seasonal foundation forecaster + +Run `bash infer.sh INPUT_DIR OUTPUT_DIR`. All runtime assets are included, with versions pinned in requirements.txt. The package contains six locally trained models totaling {manifest['parameters']:,} parameters. Every member forecasts every instance. First form two ordered FP32 quarter means: A uses members0,1,2 plus member3 for horizons below720, or member4 otherwise; B uses members0,1,2,5. The final quantiles are the equal FP32 average (A+B)/2. All six contributions are computed before this fixed composition. This one equal blend was selected on validation, with no coefficient or horizon-threshold sweep and no fitting on input contexts. + +Each member retains its declared context limits, listed in model_manifest.json under member_history_caps. A model with a separate encoder_context uses longer history only for learned seasonal summaries; its encoder, normalization and fixed forecast rules use the shorter declared limit. Their history/forecast patch sizes are {patch_sizes}, in member order. Each member retains its own original model implementation and normalization; overflow handling follows each member's own implementation. Each member uses finite-history normalization and the same fixed sign averaging, positivity, seasonal, continuity and zero-mass rules. The seasonal template aligns four cycles to the latest cycle's mean and amplitude. The trend summary uses a fixed width of 128 observations. The zero projection threshold is 0.4 context standard deviations. No additional zero projection is applied after averaging. There is no inference-time training, fitting or parameter adaptation. + +model_manifest.json declares every source, member hash and training lineage. config.json contains relative member paths and their hashes. The original member manifests and all trainer/generator code are archived in provenance/. No pretrained assets were used. Normalization uses the supplied context and needs no external statistics. + +EXPERIMENTS.md records hypotheses, negative results, compute, group metrics and hashes. validation_report.json records the package evaluation. Validation and earlier-cutoff scores are not the held-out reward scale. +''') +if final.exists(): + libc = ctypes.CDLL(None, use_errno=True) + if libc.renameat2(-100, os.fsencode(stage), -100, os.fsencode(final), 2): + raise OSError(ctypes.get_errno(), os.strerror(ctypes.get_errno())) + shutil.rmtree(stage) +else: + os.replace(stage, final) +print(json.dumps({'out': str(final), 'checkpoint_sha256': identifier, + 'parameters': manifest['parameters']})) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/model_manifest.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/model_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..42e69b5c2324df1b3378a803d7b73e49b05f944e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/model_manifest.json @@ -0,0 +1,1482 @@ +{ + "name": "direct-seasonal-foundation", + "contract": "timeseries-forecast/v1", + "parameters": 36899168, + "pretrained_assets": [], + "sources_used": [ + "gifteval_pretrain/BEIJING_SUBWAY_30MIN", + "gifteval_pretrain/HZMETRO", + "gifteval_pretrain/LOS_LOOP", + "gifteval_pretrain/PEMS03", + "gifteval_pretrain/PEMS04", + "gifteval_pretrain/PEMS07", + "gifteval_pretrain/PEMS08", + "gifteval_pretrain/PEMS_BAY", + "gifteval_pretrain/Q-TRAFFIC", + "gifteval_pretrain/SHMETRO", + "gifteval_pretrain/alibaba_cluster_trace_2018", + "gifteval_pretrain/australian_electricity_demand", + "gifteval_pretrain/azure_vm_traces_2017", + "gifteval_pretrain/bdg-2_bear", + "gifteval_pretrain/bdg-2_fox", + "gifteval_pretrain/bdg-2_panther", + "gifteval_pretrain/bdg-2_rat", + "gifteval_pretrain/bitcoin_with_missing", + "gifteval_pretrain/borealis", + "gifteval_pretrain/borg_cluster_data_2011", + "gifteval_pretrain/buildings_900k", + "gifteval_pretrain/bull", + "gifteval_pretrain/cdc_fluview_ilinet", + "gifteval_pretrain/cdc_fluview_who_nrevss", + "gifteval_pretrain/china_air_quality", + "gifteval_pretrain/cif_2016_12", + "gifteval_pretrain/cif_2016_6", + "gifteval_pretrain/cmip6_2000", + "gifteval_pretrain/cmip6_2005", + "gifteval_pretrain/cmip6_2010", + "gifteval_pretrain/cockatoo", + "gifteval_pretrain/covid19_energy", + "gifteval_pretrain/covid_mobility", + "gifteval_pretrain/elecdemand", + "gifteval_pretrain/elf", + "gifteval_pretrain/era5_2010", + "gifteval_pretrain/era5_2011", + "gifteval_pretrain/era5_2012", + "gifteval_pretrain/era5_2013", + "gifteval_pretrain/era5_2014", + "gifteval_pretrain/era5_2015", + "gifteval_pretrain/era5_2016", + "gifteval_pretrain/era5_2017", + "gifteval_pretrain/era5_2018", + "gifteval_pretrain/extended_web_traffic_with_missing", + "gifteval_pretrain/favorita_sales", + "gifteval_pretrain/favorita_transactions", + "gifteval_pretrain/gfc12_load", + "gifteval_pretrain/gfc14_load", + "gifteval_pretrain/gfc17_load", + "gifteval_pretrain/godaddy", + "gifteval_pretrain/hog", + "gifteval_pretrain/ideal", + "gifteval_pretrain/kaggle_web_traffic_weekly", + "gifteval_pretrain/kdd2022", + "gifteval_pretrain/largest_2017", + "gifteval_pretrain/largest_2018", + "gifteval_pretrain/largest_2019", + "gifteval_pretrain/largest_2020", + "gifteval_pretrain/largest_2021", + "gifteval_pretrain/lcl", + "gifteval_pretrain/london_smart_meters_with_missing", + "gifteval_pretrain/m1_monthly", + "gifteval_pretrain/m1_quarterly", + "gifteval_pretrain/m1_yearly", + "gifteval_pretrain/m5", + "gifteval_pretrain/monash_m3_monthly", + "gifteval_pretrain/monash_m3_other", + "gifteval_pretrain/monash_m3_quarterly", + "gifteval_pretrain/nn5_daily_with_missing", + "gifteval_pretrain/nn5_weekly", + "gifteval_pretrain/oikolab_weather", + "gifteval_pretrain/pdb", + "gifteval_pretrain/project_tycho", + "gifteval_pretrain/residential_load_power", + "gifteval_pretrain/residential_pv_power", + "gifteval_pretrain/rideshare_with_missing", + "gifteval_pretrain/sceaux", + "gifteval_pretrain/smart", + "gifteval_pretrain/solar_power", + "gifteval_pretrain/spain", + "gifteval_pretrain/subseasonal", + "gifteval_pretrain/subseasonal_precip", + "gifteval_pretrain/sunspot_with_missing", + "gifteval_pretrain/taxi_30min", + "gifteval_pretrain/tourism_quarterly", + "gifteval_pretrain/tourism_yearly", + "gifteval_pretrain/traffic_hourly", + "gifteval_pretrain/traffic_weekly", + "gifteval_pretrain/uber_tlc_daily", + "gifteval_pretrain/uber_tlc_hourly", + "gifteval_pretrain/vehicle_trips_with_missing", + "gifteval_pretrain/wiki-rolling_nips", + "gifteval_pretrain/wind_farms_with_missing", + "gifteval_pretrain/wind_power", + "synthetic:both original and sign-reflected orientations of each sampled allowed or locally generated window; paired quantile loss, seed 197", + "synthetic:both original and sign-reflected orientations of each sampled window, seed 197", + "synthetic:independent sign reflection of sampled allowed-corpus and locally generated windows; seeds 43,47,59,79,89,197", + "synthetic:own Fourier/trend/AR/intermittent/changepoint generator at weekly periods52,1, replacing a Bernoulli1/11 share of the original synthetic rows with unchanged total synthetic fraction; independent seed 1000200", + "synthetic:own Fourier/trend/intermittent generator with AR time constant log-uniform from 1 to 10000 steps and zero initial state; seed 79", + "synthetic:own direct_v1 Fourier seasons, damped trends, AR noise, changepoints and intermittent demand; seeds 23,43,47,59,79,89,197,503,577,661", + "synthetic:own random requested-horizon prefixes, half of rows retain the full horizon and half use a patch-rounded prefix between one-quarter and the full horizon; independent seed 300200", + "synthetic:own stationary Gaussian residuals generated by FFT, equal Matern0.5/1.5/2.5 and RBF spectral families, length scale log-uniform1to10000, theoretical unit marginal variance, FFT size next power of two at least4times window; replacing half of original synthetic residuals with all other generator components unchanged; independent seed 1100200" + ], + "weights_sha256": "0b11b7351a4a92d1d18c71a4159ec445be3a94ace8c7a9fa0edafad87d14e960", + "config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true, + "seasonal_dispersion_features": true, + "seasonal_width_features": true + }, + "training_lineage": [ + { + "checkpoint": "seasonal_width_transfer12k.pt", + "sha256": "0b11b7351a4a92d1d18c71a4159ec445be3a94ace8c7a9fa0edafad87d14e960", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true, + "seasonal_dispersion_features": true, + "seasonal_width_features": true + }, + "conversion": { + "method": "matched direct-width-head training delta, separately zero-extending base and control", + "formula": "zero_extend(E117first)+E129-zero_extend(E119)", + "coefficient": 1.0, + "base_zero_parameters": [ + "dispersion_query.weight", + "width_head.bias", + "width_head.weight" + ], + "control_zero_parameters": [ + "width_head.bias", + "width_head.weight" + ], + "dispersion_query": "candidate-minus-control only; no E128 correction", + "parent_hashes": { + "/workspace/research/long_seasonal_transfer12k.pt": "8a2b252b733cc79c31778ea27ba00fbe61206fef50454514b667c54a928d80a4", + "/workspace/research/runs/seasonal_width/ema012000.pt": "8a8c75cafcc7b42266aaab7d8458cb383b65313ce6da8c396e76760f7ab6e33c", + "/workspace/research/runs/seasonal_dispersion/ema012000.pt": "b0204fa8dd3371d9160fc00545d6b065ccb23bb18e345b3b63cd39c024c9acf5" + }, + "base_extension_forward_bitwise_equal": true, + "finite_ordered_fixture": true, + "check_seed": 769, + "seconds": 2.078599537955597, + "optimizer_updates": 0, + "validation_data_read": false + }, + "parents": [ + "long_seasonal_transfer12k.pt", + "runs/seasonal_width/ema012000.pt", + "runs/seasonal_dispersion/ema012000.pt" + ] + }, + { + "checkpoint": "long_seasonal_transfer12k.pt", + "sha256": "8a2b252b733cc79c31778ea27ba00fbe61206fef50454514b667c54a928d80a4", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true + }, + "conversion": { + "method": "matched training delta after zero extension of new seasonal query/head parameters", + "formula": "extend_zero(base) + candidate - extend_zero(control)", + "coefficient": 1.0, + "new_parameters_from_candidate": [ + "long_head.bias", + "long_head.weight", + "long_query.weight" + ], + "parent_hashes": { + "/workspace/research/spectral_add_delta6k.pt": "c3dfc433d51355228fc13d04913db1a7edf83030c33283b150bdcc50f5ae6ea2", + "/workspace/research/runs/long_seasonal/ema012000.pt": "d512cdac520239f0c10e021721424d87cee30086fa70f6cbc41f21e2e04988c3", + "/workspace/research/runs/overflow_control/ema012000.pt": "f11d056b95f1c5eeef174265ebc51742952600e0dae1fa52900860447d5be819" + }, + "base_extension_forward_bitwise_equal": true, + "check_seed": 571, + "seconds": 2.5279976530000567, + "optimizer_updates": 0, + "validation_data_read": false + }, + "parents": [ + "spectral_add_delta6k.pt", + "runs/long_seasonal/ema012000.pt", + "runs/overflow_control/ema012000.pt" + ] + }, + { + "checkpoint": "runs/seasonal_width/ema012000.pt", + "sha256": "8a8c75cafcc7b42266aaab7d8458cb383b65313ce6da8c396e76760f7ab6e33c", + "step": 12000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null, + "teacher_coefficient": null, + "compile_teacher": false, + "visibility_curriculum": false + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true, + "seasonal_dispersion_features": true, + "seasonal_width_features": true + }, + "parents": [ + "seasonal_width_initial.pt", + "seasonal_dispersion_initial.pt" + ] + }, + { + "checkpoint": "runs/seasonal_dispersion/ema012000.pt", + "sha256": "b0204fa8dd3371d9160fc00545d6b065ccb23bb18e345b3b63cd39c024c9acf5", + "step": 12000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null, + "teacher_coefficient": null + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true, + "seasonal_dispersion_features": true + }, + "parents": [ + "seasonal_dispersion_initial.pt", + "long_seasonal_initial.pt" + ] + }, + { + "checkpoint": "spectral_add_delta6k.pt", + "sha256": "c3dfc433d51355228fc13d04913db1a7edf83030c33283b150bdcc50f5ae6ea2", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/weekly_slow_ar_delta6k.pt": "c8adf9cadf97dac5e120d8d4d2c8c025bffa2e8b55d8664bf900cce55d00a70b", + "/workspace/research/runs/spectral_synth/ema006000.pt": "683f3824d3c1f605d17bb08d3eef127a54c67eca3867cfbcf1158710a55c4b24", + "/workspace/research/runs/overflow_control/ema006000.pt": "b19875c52ed5024383fb69ccc48cb07a5629ad8011abf134c7dcfcdc50fae2af" + }, + "seconds": 1.4204325219616294 + }, + "parents": [ + "weekly_slow_ar_delta6k.pt", + "runs/spectral_synth/ema006000.pt", + "runs/overflow_control/ema006000.pt" + ] + }, + { + "checkpoint": "runs/long_seasonal/ema012000.pt", + "sha256": "d512cdac520239f0c10e021721424d87cee30086fa70f6cbc41f21e2e04988c3", + "step": 12000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null, + "teacher_coefficient": null + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true + }, + "parents": [ + "long_seasonal_initial.pt", + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "runs/overflow_control/ema012000.pt", + "sha256": "f11d056b95f1c5eeef174265ebc51742952600e0dae1fa52900860447d5be819", + "step": 12000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "seasonal_width_initial.pt", + "sha256": "94ba155b90c6b510bccf92358cc225afe8f317285a19637ab5ca68072bbb83d1", + "step": 0, + "seed": 661, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "long_seasonal_features": true, + "seasonal_dispersion_features": true, + "seasonal_width_features": true + }, + "conversion": { + "method": "zero-initialized direct seasonal width head", + "parent_sha256": "5f07cac4fe7de3e878a01cb90384e79905fdb3156122b568e82c5923526aca3c", + "initial_function_bitwise_equal": true + }, + "parents": [ + "seasonal_dispersion_initial.pt" + ] + }, + { + "checkpoint": "seasonal_dispersion_initial.pt", + "sha256": "5f07cac4fe7de3e878a01cb90384e79905fdb3156122b568e82c5923526aca3c", + "step": 0, + "seed": 577, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "long_seasonal_features": true, + "seasonal_dispersion_features": true + }, + "conversion": { + "method": "zero-initialized phase-specific cycle-centered standard-deviation query", + "parent_sha256": "470ef98d69d00b17defbf41c70a92b22574154cdb6e0317993bccf113e4af93b", + "initial_function_bitwise_equal": true + }, + "parents": [ + "long_seasonal_initial.pt" + ] + }, + { + "checkpoint": "long_seasonal_initial.pt", + "sha256": "470ef98d69d00b17defbf41c70a92b22574154cdb6e0317993bccf113e4af93b", + "step": 0, + "seed": 503, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "long_seasonal_features": true + }, + "conversion": { + "method": "zero-initialized sixteen-cycle centered seasonal query/head additions", + "parent_sha256": "22c08571978be31ba57368eb983089a40a44d56d4ae5e17da41afd2a761a258c", + "initial_function_bitwise_equal": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "weekly_slow_ar_delta6k.pt", + "sha256": "c8adf9cadf97dac5e120d8d4d2c8c025bffa2e8b55d8664bf900cce55d00a70b", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/postloss_slow_ar_delta6k.pt": "0ae7875b49b99a44c295dc2b8243327aeacadc25b2354988abb2c37250359a49", + "/workspace/research/runs/weekly_synth/ema006000.pt": "de053e5baf9641e9245519990d6e5193fc91392cb76e72ceffee1ce63f578fca", + "/workspace/research/runs/overflow_control/ema006000.pt": "b19875c52ed5024383fb69ccc48cb07a5629ad8011abf134c7dcfcdc50fae2af" + }, + "seconds": 2.0751679679378867 + }, + "parents": [ + "postloss_slow_ar_delta6k.pt", + "runs/weekly_synth/ema006000.pt", + "runs/overflow_control/ema006000.pt" + ] + }, + { + "checkpoint": "runs/spectral_synth/ema006000.pt", + "sha256": "683f3824d3c1f605d17bb08d3eef127a54c67eca3867cfbcf1158710a55c4b24", + "step": 6000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null, + "teacher_coefficient": null, + "spectral_synthetic_seed": 1100200, + "spectral_replacement_probability": 0.5, + "spectral_length_scale": [ + 1, + 10000 + ], + "spectral_families": [ + "Matern0.5", + "Matern1.5", + "Matern2.5", + "RBF" + ] + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt", + "runs/confidence_query/ema006000.pt", + "runs/horizon_jitter/ema012000.pt", + "runs/large_corpus_control/ema012000.pt" + ] + }, + { + "checkpoint": "runs/overflow_control/ema006000.pt", + "sha256": "b19875c52ed5024383fb69ccc48cb07a5629ad8011abf134c7dcfcdc50fae2af", + "step": 6000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "horizon_delta12k.pt", + "sha256": "22c08571978be31ba57368eb983089a40a44d56d4ae5e17da41afd2a761a258c", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/runs/confidence_query/ema006000.pt": "0bad97e8994aac49ea173443db0a4fa8d72d33f9eb9e2660f06de75f7f1403eb", + "/workspace/research/runs/horizon_jitter/ema012000.pt": "830179d763916a1065fc615d2c5e22f4a3b5b19390dde707ab0f057e13cadff6", + "/workspace/research/runs/large_corpus_control/ema012000.pt": "7f9ba5e01ac59c51a3b63d3067b442e23e15d0abc51ddbcccdd04d6083ae4add" + }, + "seconds": 1.2663014469435439 + }, + "parents": [ + "runs/confidence_query/ema006000.pt", + "runs/horizon_jitter/ema012000.pt", + "runs/large_corpus_control/ema012000.pt" + ] + }, + { + "checkpoint": "postloss_slow_ar_delta6k.pt", + "sha256": "0ae7875b49b99a44c295dc2b8243327aeacadc25b2354988abb2c37250359a49", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/runs/postloss/ema003000.pt": "82c785d40998e155a20290c9965c346c26cd397fa0f3cf36278377ad2aed5c7d", + "/workspace/research/runs/long_memory_synth_recovery/ema006000.pt": "fea5b5290a3a9be5618eaeaf67e918e4f677d5be908d562040ce4bdfeb549bd9", + "/workspace/research/runs/partial_targets/ema006000.pt": "67562486b099a350da53c3caa5ff0932fe7fecdfe72c1879b064b2a9bb173dfb" + }, + "seconds": 1.0092943429481238 + }, + "parents": [ + "runs/postloss/ema003000.pt", + "runs/long_memory_synth_recovery/ema006000.pt", + "runs/partial_targets/ema006000.pt" + ] + }, + { + "checkpoint": "runs/weekly_synth/ema006000.pt", + "sha256": "de053e5baf9641e9245519990d6e5193fc91392cb76e72ceffee1ce63f578fca", + "step": 6000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true, + "weekly_synthetic_seed": 1000200, + "weekly_replacement_probability": 0.09090909090909091, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "runs/confidence_query/ema006000.pt", + "sha256": "0bad97e8994aac49ea173443db0a4fa8d72d33f9eb9e2660f06de75f7f1403eb", + "step": 6000, + "seed": 89, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 0.0002, + "steps": 6000 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true + }, + "parents": [ + "runs/recency_features/ema024000.pt" + ] + }, + { + "checkpoint": "runs/horizon_jitter/ema012000.pt", + "sha256": "830179d763916a1065fc615d2c5e22f4a3b5b19390dde707ab0f057e13cadff6", + "step": 12000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "partial_target_lengths": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/large_corpus_control/ema012000.pt", + "sha256": "7f9ba5e01ac59c51a3b63d3067b442e23e15d0abc51ddbcccdd04d6083ae4add", + "step": 12000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/postloss/ema003000.pt", + "sha256": "82c785d40998e155a20290c9965c346c26cd397fa0f3cf36278377ad2aed5c7d", + "step": 3000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "fixed_postprocessing_loss": true, + "normalization_overflow_fallback": true + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "runs/long_memory_synth_recovery/ema006000.pt", + "sha256": "fea5b5290a3a9be5618eaeaf67e918e4f677d5be908d562040ce4bdfeb549bd9", + "step": 6000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "context": null, + "sample_context": 4096, + "synthetic_ar_time_constants": [ + 1, + 10000 + ] + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "partial_target_lengths": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/partial_targets/ema006000.pt", + "sha256": "67562486b099a350da53c3caa5ff0932fe7fecdfe72c1879b064b2a9bb173dfb", + "step": 6000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "partial_target_lengths": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/recency_features/ema024000.pt", + "sha256": "1530fbb577a87ca4eb39da83d6fee9b8ee5bc924202e021e3a7b56493112f564", + "step": 24000, + "seed": 59, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/patch16_trial/ema006000.pt" + ] + }, + { + "checkpoint": "runs/recency_features/ema012000.pt", + "sha256": "8ccb6870a025e1097331a3a288b1183741a413f3460fbf3352d0c589c6a4394c", + "step": 12000, + "seed": 59, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/patch16_trial/ema006000.pt" + ] + }, + { + "checkpoint": "runs/patch16_trial/ema006000.pt", + "sha256": "0ff54447074e0271d2e331c7d3e6e9e0fdd73353e4d8cef0175ff627385f71c3", + "step": 6000, + "seed": 47, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024 + }, + "parents": [ + "patch16_init.pt" + ] + }, + { + "checkpoint": "patch16_init.pt", + "sha256": "d69531bfde5bf801e7f36c515bf15fd0cae0bd84f7d1479d35f4a7b67f26b508", + "step": 6000, + "seed": 43, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024 + }, + "conversion": { + "from_checkpoint": "/run-state/workspace/research/runs/large_sign/ema006000.pt", + "from_sha256": "96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547", + "method": "fold input/query halves by summation; retain first 16 output rows; preserve physical positional units" + }, + "parents": [ + "runs/large_sign/ema006000.pt" + ] + }, + { + "checkpoint": "runs/large_sign/ema006000.pt", + "sha256": "96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547", + "step": 6000, + "seed": 43, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 32, + "max_context": 4096, + "max_horizon": 1024 + }, + "parents": [ + "runs/direct_large/step024000.pt" + ] + }, + { + "checkpoint": "runs/direct_large/step024000.pt", + "sha256": "b7e4f38aebcd2cf38ce484edaad8d19851317fb3b8df485e2faa0d0423cbcb48", + "step": 24000, + "seed": 23, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 128, + "lr": 0.0002, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 32, + "max_context": 4096, + "max_horizon": 1024 + }, + "initialization": "random initialization in this workspace" + } + ], + "symmetric_averaging": true, + "seasonal_gate": { + "variance_ratio_threshold": 0.25, + "maximum_weight": 0.98, + "cycles_averaged": 4, + "template_mode": "aligned", + "amplitude_ratio_clip": [ + 0.5, + 2.0 + ], + "latest_cycle_minimum_coverage": 0.75, + "variance_noise_correction": "mean squared seasonal differences / 2" + }, + "continuity": { + "decay_steps": 24, + "variance_ratio_threshold": 0.5, + "maximum_weight": 0.95, + "lookback": 512, + "slope_median_differences": 8 + }, + "notes": "All training lineage originates from random initialization here, using only the declared corpus and locally generated series. Validation was used only for selection and diagnostics. Context transformations are fixed formulas; there is no inference-time fitting or parameter adaptation.", + "runtime_code_sha256": { + "predict.py": "9bde896945a2cd8f892e7eeb6328ed2dfda09293532f3a4a64d929c9943614ef", + "seasonal.py": "b946e63048196ab5ea8b249137d48c80d8510943caccd0f180e4fb86d9b24b37", + "ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "model.py": "0d9557eca352e3c493f47c310355aa576da2e75c8f7cb5b69786c3d162644f38", + "continuity.py": "dbb08d2229ad80ad00f638b0b9f2f6ca13c663e0fd6730058e5fee8ff54545d5", + "infer.sh": "5fe66b4fe9a4787285d830cfd96975701e97286a75ba7c3687bd8891475edf68", + "zero_mass.py": "f079d509009bcda409b80eb64467c869b838cfbab11b2bd4c660c2875b6642fe" + }, + "checkpoint_composition": { + "method": "matched direct-width-head training delta, separately zero-extending base and control", + "formula": "zero_extend(E117first)+E129-zero_extend(E119)", + "coefficient": 1.0, + "base_zero_parameters": [ + "dispersion_query.weight", + "width_head.bias", + "width_head.weight" + ], + "control_zero_parameters": [ + "width_head.bias", + "width_head.weight" + ], + "dispersion_query": "candidate-minus-control only; no E128 correction", + "parent_hashes": { + "/workspace/research/long_seasonal_transfer12k.pt": "8a2b252b733cc79c31778ea27ba00fbe61206fef50454514b667c54a928d80a4", + "/workspace/research/runs/seasonal_width/ema012000.pt": "8a8c75cafcc7b42266aaab7d8458cb383b65313ce6da8c396e76760f7ab6e33c", + "/workspace/research/runs/seasonal_dispersion/ema012000.pt": "b0204fa8dd3371d9160fc00545d6b065ccb23bb18e345b3b63cd39c024c9acf5" + }, + "base_extension_forward_bitwise_equal": true, + "finite_ordered_fixture": true, + "check_seed": 769, + "seconds": 2.078599537955597, + "optimizer_updates": 0, + "validation_data_read": false + }, + "normalization_overflow_fallback": { + "trigger": "nonfinite float32 context mean or scale", + "arithmetic": "float64 context statistics on affected rows; original arithmetic on ordinary rows", + "inference_fitting": false + }, + "trend_summary": { + "fixed_averaging_width": 128, + "matches_all_pretraining_context_widths": true, + "independent_of_batch_padding": true + }, + "zero_mass_projection": { + "threshold_in_context_standard_deviations": 0.4, + "nonnegative_context_required": true, + "minimum_exact_zeros": 4, + "minimum_zero_fraction": 0.1, + "context_cap": 4096 + }, + "recency_features": { + "query_projection_parameters": 32768, + "latest_vs_four_cycle_level": true, + "amplitude_ratio_clip": [ + 0.5, + 2.0 + ], + "minimum_observed_cycles": 3 + }, + "seasonal_dispersion_features": { + "features": "log1p unbiased standard deviation across matching phases of four and sixteen individually centered cycles, for each of two periods", + "active_rule": "period>=2,at least2recent and8total matching-phase observations", + "query_projection_parameters": 32768, + "initialization": "zero projection preserves the own parent model exactly", + "trainable_scope": "all parameters", + "fixed_output_rescaling": false + }, + "seasonal_width_features": { + "head_parameters": 16416, + "delta": "active*(log1p(cycle-centered matching-phase standard deviation over16cycles)-log2)", + "multiplier": "exp(clamp(sum(tanh(learned_gate)*delta),-log4,log4))", + "bounds": [ + 0.25, + 4.0 + ], + "active_rule": "period>=2,n4>=2,n16>=8", + "all_eight_width_increments_share_multiplier": true, + "zero_initialization_preserves_parent": true, + "trainable_scope": "all parameters" + }, + "long_seasonal_features": { + "cycles": [ + 4, + 16 + ], + "each_cycle_centered": true, + "minimum_total_cycles": 8, + "minimum_recent_cycles": 2, + "query_features": [ + "centered16-minus4 phase mean", + "observed16-cycle fraction" + ], + "median_shift": "sum of two learned tanh gates times template differences", + "same_shift_all_quantiles": true, + "maximum_context": 4096, + "parameters_fixed_at_inference": true + }, + "confidence_features": { + "query_projection_parameters": 3072, + "backbone_frozen_during_projection_training": true, + "training_objective": "weighted quantile and median loss after averaging both sign orientations", + "statistics": [ + "mean absolute difference", + "root mean square difference" + ], + "lags": "one and the two frequency-derived periods", + "lookback": "512 for lag one; eight cycles for seasonal lags", + "minimum_valid_pairs": 8, + "insufficient_pair_defaults": [ + 1, + 1.4142135623730951 + ], + "statistic_clip": 10, + "transform": "log1p", + "stage_scope": "Frozen-backbone details refer to projection introduction; subsequent updates are recorded in training_lineage.training_settings." + }, + "partial_target_training": { + "available_horizon": "last finite training-label position rounded up to the patch boundary", + "decoder_future_key_mask": true, + "per_row_horizon_metadata": true, + "inference_uses_requested_horizon_only": true + }, + "training_provenance_code_sha256": { + "confidence_query/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "confidence_query/model.py": "b4f11ba2018e2b50879cdc33acf0138301548971508b58035a7c96a29aaa6f2d", + "confidence_query/train.py": "fc8a7555a5a6b0a6f91e80ac8cc9cbbfddaa2b26468c57f49dfb17671b22ce93", + "direct_large/data.py": "6e6db217936f8dd79380d2ceff3eaa8598a44f1b60b17acae7bfde2363116847", + "direct_large/evaluate.py": "eaea99e8cd44c9f7c70a45fa9abf51354ae5449dbad273fcb55e48ad02652223", + "direct_large/model.py": "146d93a3f95b13bda8b1b437bc36621b91356cf946e94f62999f89e7fb348071", + "direct_large/pack.py": "3bcc4ce9eb3361ad741ceebd7efce7a2fb86fb49543f52c72aabd0e3e8cd17ce", + "direct_large/predict.py": "930a9f18f9f5da47c03859698c9d2f5567d1e1c73fd61edac1ed20b3a6f9bb50", + "direct_large/publish.py": "3c167f33e8571731c26f1cb70168eda54ef9cb4c76423dfd374240b75ca5f106", + "direct_large/record.py": "b3b00b0ed14bc3af00c7b1ad97195238ecb8f06e96bc41f0c07913bc3f6ed949", + "direct_large/train.py": "b9ad6b2adddeaf12961b529d6535dd33f6d044a31979b5c9e49dceafbadd3ac0", + "direct_large/ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "direct_large/validation_subset.py": "8d3eb9d3f3aa124368761ef402ff066935c0be31a62b25b8551a45dcb922e28d", + "full_paired/check.py": "90ac1c78846439d51ab8acd62a19bd536c7c394bd02e94f6d5ff17c0af8bd116", + "full_paired/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "full_paired/model.py": "c27748fa4b1186b513f76eca26052753b8dcd1794994e5989addaf371ca70f2e", + "horizon_jitter/data.py": "5044cf648323420095ed6058d29f837c07ff5559b606df8b00cc8d1e95c8b58e", + "horizon_jitter/model.py": "186bb282236f23cc665a012194d26e58f51004c680393352ec053f5308f1240f", + "horizon_jitter/train.py": "4e9cbca1293f18f7eea2c72dba127815c0934a13c86e8f6cc881a749676d41a6", + "large_corpus/data.py": "27c078cb0ed085717a364f556b5ff976fd803d5af37612cf3a03a0a3ca12a678", + "large_corpus/model.py": "e3a1bc01e89a0d6d750ede2cc969272ad01e1ca580b174af7dee00db029f1cf7", + "large_corpus/train.py": "3baca16c3945e6ef241ccbc9c13644539e3c265f71095cbbaa61a3d338e4fafe", + "large_sign/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "large_sign/evaluate.py": "eaea99e8cd44c9f7c70a45fa9abf51354ae5449dbad273fcb55e48ad02652223", + "large_sign/model.py": "3fff6445a1982a1b3c92f06a9b5f1bb627dda6a291b0b2364bcfb1a6457830d7", + "large_sign/pack.py": "3bcc4ce9eb3361ad741ceebd7efce7a2fb86fb49543f52c72aabd0e3e8cd17ce", + "large_sign/predict.py": "930a9f18f9f5da47c03859698c9d2f5567d1e1c73fd61edac1ed20b3a6f9bb50", + "large_sign/publish.py": "3c167f33e8571731c26f1cb70168eda54ef9cb4c76423dfd374240b75ca5f106", + "large_sign/record.py": "b3b00b0ed14bc3af00c7b1ad97195238ecb8f06e96bc41f0c07913bc3f6ed949", + "large_sign/train.py": "a597f40ab87cce04e96dc654d12e56cdf40ffd87f00034d8bc4d56dff4eb7c68", + "large_sign/ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "large_sign/validation_subset.py": "8d3eb9d3f3aa124368761ef402ff066935c0be31a62b25b8551a45dcb922e28d", + "long_memory_synth/data.py": "2955ec414de97f7ec91c8863873b7ae50ebe8f0ccb7fe48c41599e69da88ec34", + "long_memory_synth/model.py": "186bb282236f23cc665a012194d26e58f51004c680393352ec053f5308f1240f", + "long_memory_synth/train.py": "75918ac02d30ad8289632bc8a3ce1386c949fd670522799af59536d4cab0b9e9", + "long_seasonal/check.py": "e55fe780892204889e210d1591ae3f0b964d72ec1916b9b5e768b938aba28fc1", + "long_seasonal/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "long_seasonal/launch.py": "68c56b8abde125eb8de866807f8deb946c30e4c52866bc0cafcab82198b58def", + "long_seasonal/long_features.py": "270d84ff1208085f65856e8c489998e6248af5c5ea1c3c47b5161f7d6b621b13", + "long_seasonal/model.py": "3eaa4aed0a1c62b80d94be6c3084b10a594e9fce17444eac17ca3f1b0b5c549e", + "long_seasonal/transfer.py": "301df5a793988edbe50b3384c5777d8679161142943578bc7723a552ed4f3d04", + "overflow_control/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "overflow_control/model.py": "44eeb23c037e91b8f67e432615ce46540a7ac4242919785f9c4218de23121499", + "partial_delta/merge.py": "63984a0f46f7d48817037f5bf5a1c9319e45a9b1924cde62c667ac49ce47532e", + "partial_targets/data.py": "27c078cb0ed085717a364f556b5ff976fd803d5af37612cf3a03a0a3ca12a678", + "partial_targets/model.py": "186bb282236f23cc665a012194d26e58f51004c680393352ec053f5308f1240f", + "partial_targets/train.py": "3baca16c3945e6ef241ccbc9c13644539e3c265f71095cbbaa61a3d338e4fafe", + "patch16/convert.py": "11e1d30100ab25311020ac1f4ab8227ec66156836df5de613300867977091c45", + "patch16/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "patch16/evaluate.py": "eaea99e8cd44c9f7c70a45fa9abf51354ae5449dbad273fcb55e48ad02652223", + "patch16/model.py": "8031c597b354eb2cf464140bee40c3ec8dff86c775b5c55c5ce910302b443582", + "patch16/pack.py": "3bcc4ce9eb3361ad741ceebd7efce7a2fb86fb49543f52c72aabd0e3e8cd17ce", + "patch16/predict.py": "930a9f18f9f5da47c03859698c9d2f5567d1e1c73fd61edac1ed20b3a6f9bb50", + "patch16/publish.py": "3c167f33e8571731c26f1cb70168eda54ef9cb4c76423dfd374240b75ca5f106", + "patch16/record.py": "b3b00b0ed14bc3af00c7b1ad97195238ecb8f06e96bc41f0c07913bc3f6ed949", + "patch16/train.py": "3156710f76111a31447cbe638ee27fe2811d060917aa083aab0b5134d98accf8", + "patch16/ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "patch16/validation_subset.py": "8d3eb9d3f3aa124368761ef402ff066935c0be31a62b25b8551a45dcb922e28d", + "postloss/check_numerical_fix.py": "527dffcd94ec1a02b214dd300261d189b06c386f0b8c4d4df3320098f5fc0e68", + "postloss/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "postloss/diagnose_nonfinite.py": "82d10c5751ea1d21ecd36cd5eb54c00aabcaf78a8562b259551d028d452be47b", + "postloss/gpu_check.py": "c0a7e23d9f74cdab4fa04e1a4b9f89c64bb58f5e24228aa5e0f2cf554fef2d1f", + "postloss/launch_completion.py": "ef584b22259e3bc741b16ef876a6120bfcee08e2b9237a7990ed560a0dbf77ae", + "postloss/model.py": "d4b76fb1a63789e091b114dd947abe30be3e47c2e2e9d41cecb3e3353af86ac5", + "postloss/model_before_numerical_fix.py": "1ad846ac7adc16298b9643a79f4ee1b94f4db82fa716c6db77a2fcbb2160c261", + "postloss/restart.py": "5baa9a0947a0d30f7773113c05bd1f53b8ed1817aeaa2365078b06df9ce2fbca", + "postloss/torch_post.py": "0762fc5d330a4039798a81788e4adb8bfe206aba2aa29a1b53ecad0bd3bff217", + "recency_features/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "recency_features/model.py": "e3a1bc01e89a0d6d750ede2cc969272ad01e1ca580b174af7dee00db029f1cf7", + "recency_features/train.py": "a654b9a27b6c27141e1d4e517ab28fcae3f2c23d061742fa2f6c01e3d23c8a00", + "recovery/brief.py": "14826a63bbdf9eeebc8e784cbbe9bc2670e5ea74daf008a17a8578dee95453fb", + "recovery/capacity_curves.py": "2bdc6635705b70a868e115cd13eb529563acacf6f47c71f250a50dce8e943be4", + "recovery/exposure_audit.py": "54c194a626b8876ece84686b39b22360155c9fada7248a393ca9b7d6ee38002b", + "recovery/launch_matched_cutoffs.py": "7d5b9b569df284c143bb4fe50033ed6be21ff1b54cb4405723b2ebcdefe6e562", + "recovery/matched_report.py": "82696104e2e7da9cee48611e42aebc0f5c4916f2273fdeb9a3158c4dd3700b04", + "recovery/median_error_structure.py": "f6e126496eba2e0aa1fce1efeac7e926f0fbc28005ab81c0f1c9cf73ecd93782", + "recovery/pack_composition.py": "66c198e44b55fc4dce50dec505a0127eb9d97390e04d0f97c271ace11ad0f49f", + "recovery/quantile_coverage.py": "7a4057d1aa38c5e7de0ca601db0003a8fd3a9a2e6123b2fdb81fa8aedbc34787", + "recovery/reclaim_completed_cache.py": "d0a23e5a73b362f03a3be0d9fcc8dd5292d17da0489484a9c52af84bd05d9638", + "recovery/refresh_journal.py": "6ccbbbf7494f3b310f2e4d47e572487b62494ae52ef6598de93ce8ae28c8a7a5", + "recovery/relaunch_20261022b.py": "f90ddd77928a793c8e151ba74cfa9cc84c8aefad0c0d943a833c74bc07b79313", + "recovery/relaunch_20261023.py": "a4c40c5674b0d05cfe9bb1fffe907f02dec16c53cbddb8b86efbba1b96649097", + "recovery/schedules.py": "7748fd6b2bbbe64037472faf7e6583d03cf339138d2f3c07b1bac9e65bf2d4f5", + "recovery/seasonal_history_support.py": "fe2da1a695715c3add9472f0bfebc946783b179b1a8415f85565a937885f7076", + "recovery/snapshot.py": "2bca59056f90a58dc18ee9d9f3f9d6b74a62d04c8eea5a1e0ae5a745ba942bbf", + "recovery/synthetic_window_audit.py": "912e38fd094f35fb528a77388d8076600207b369bb3b2c2133a24c3c485019a1", + "recovery/train.py": "76946cbda4b20c1d9922914955ccd221f2ccc574a0d452012431cf2c6a66f38f", + "recovery/watch_matched_cutoffs.py": "177dbe6d8b5186dd3ce1c4b261a55cd5cfb44f6ed2922ef64b489deb2117fa6b", + "seasonal_dispersion/check.py": "aec0a137044f8da807fa7f4212f196dd99c7d823f0c93d526592f3659481721f", + "seasonal_dispersion/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "seasonal_dispersion/durability.py": "5e249e02a5a2b0b61f3c78693f273b851d98db3e964e004dcd19c920679c6a1f", + "seasonal_dispersion/launch.py": "5befe970b37e12829e8cc97f201568c95a2d06311a2730e6599b4372cc9a55b1", + "seasonal_dispersion/model.py": "35d591ca15c0875d6562a45618fd7483796eaec8d4c8306408e716c72693c4b3", + "seasonal_width/check.py": "6fd58bfeca5cb16aa70bfa66a93ec0ede4d43d554e976368c143afe986377c1e", + "seasonal_width/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "seasonal_width/launch.py": "7473cd5ee8b9094439a7375c58f4069ece047e0c7c9c77064856355fc09be9b3", + "seasonal_width/model.py": "0d9557eca352e3c493f47c310355aa576da2e75c8f7cb5b69786c3d162644f38", + "seasonal_width_transfer/assemble.py": "7313ef4be82840bb0e89b989375a348e633ac24f5a63fb1e15e9730492acd2eb", + "seasonal_width_transfer/check_runtime.py": "1a5e7113c3ab3452dce6eee5f26d9283e48da825c15e2c595be43756bde0b443", + "seasonal_width_transfer/merge.py": "a67ab547f82b3f86935c47ef82c6f196e3cd80af3b3860247125dc742076cdd3", + "seasonal_width_transfer/promote.py": "73bb7adf33bf2553503e71565604c198762519c64d1199730cf240946edd3d50", + "seasonal_width_transfer/run.py": "0bb371e4e7585fd36d2afc499412d1cf166194395c56519d230ba7d2d1298ee3", + "seasonal_width_transfer/validate.py": "6d13c787616e012d47888c9821779e00c0b8c2aa554b4e4e98a04f3dbeb95dd9", + "spectral_synth/check.py": "c308c87af0a6756fafefa460751cc370ed44ee98f3f52364b1ed6879a3c4e110", + "spectral_synth/data.py": "1780475ef9573c9731cf67f46c1a339ab2fa466c28bbbee5948322ae3f33ca29", + "spectral_synth/launch.py": "5888c115ae4b38b307ac1ac1bb4a9c200a1aa35850819dab55eaeb47946c38e2", + "spectral_synth/model.py": "44eeb23c037e91b8f67e432615ce46540a7ac4242919785f9c4218de23121499", + "spectral_synth/spectral.py": "347aa6d352df72ff18ef35a267b8e0479546263b26174d5256d4e9903cce5f71", + "spectral_transfer/run.py": "33fb544faca0633cd96440e2e4fa3c0e38c8e8cde8a215bfaf8357ed224bfcd8", + "weekly_synth/check.py": "a122b553d9ddc01a506a36713a0df478b03d7fe0b3f9ee1fa34c22c3e982adbf", + "weekly_synth/data.py": "774d0d5216fa263db9d809289dd3daa877f0bcea6ed44a628dd9f8e53829815f", + "weekly_synth/launch.py": "b28347982ecf6d87b45970824d0961027297296e8a6d4372414caeae28427e9d", + "weekly_synth/model.py": "44eeb23c037e91b8f67e432615ce46540a7ac4242919785f9c4218de23121499" + } +} diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/confidence_query/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/confidence_query/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/confidence_query/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/confidence_query/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/confidence_query/model.py new file mode 100644 index 0000000000000000000000000000000000000000..b881039b3752b3396e06415a8d01d24956fa29a7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/confidence_query/model.py @@ -0,0 +1,190 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + if self.recency is not None: + pos=torch.arange(c,device=z.device)[None,:];extras=[] + for j in range(2): + period=periods[:,j:j+1] + recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + n=ctx.shape[0] + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1]) + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/confidence_query/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/confidence_query/train.py new file mode 100644 index 0000000000000000000000000000000000000000..fd9d2a3a0502cee1a67c41c832266c7f87cc5a80 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/confidence_query/train.py @@ -0,0 +1,54 @@ +"""Train only confidence-query features on a frozen model, using paired-sign forecast loss.""" +import argparse,json,math,time,os +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) +ap.add_argument('--initialize-from',required=True);ap.add_argument('--steps',type=int,default=6000) +ap.add_argument('--batch',type=int,default=128);ap.add_argument('--lr',type=float,default=2e-4) +ap.add_argument('--seed',type=int,default=89);ap.add_argument('--save-every',type=int,default=1000);a=ap.parse_args() +torch.set_num_threads(1);torch.manual_seed(a.seed);torch.backends.cuda.matmul.allow_tf32=True +out=Path(a.out);out.mkdir(parents=True,exist_ok=True) +ck=torch.load(a.initialize_from,map_location='cpu',weights_only=False) +config={**ck['config'],'confidence_features':True};model=DirectForecaster(**config).cuda() +missing,unexpected=model.load_state_dict(ck['model'],strict=False) +assert not unexpected and all(k.startswith('confidence.') for k in missing) +for name,param in model.named_parameters():param.requires_grad_(name.startswith('confidence.')) +params=[p for p in model.parameters() if p.requires_grad] +opt=torch.optim.AdamW(params,lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) +ema={k:v.detach().clone() for k,v in model.state_dict().items()};sampler=Sampler(a.packed,seed=a.seed) +(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)) +rng=np.random.default_rng(a.seed) +def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) +def save(step): + for prefix,weights in [('step',model.state_dict()),('ema',ema)]: + state={'model':weights,'config':model.config,'step':step,'args':vars(a),'ema':prefix=='ema'} + path=out/f'{prefix}{step:06d}.pt';torch.save(state,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) +save(0);pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] +for step in range(1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch);x,y,p=[torch.from_numpy(x).cuda() for x in arrays] + lr=a.lr*min(1,step/200)*(.2+.8*.5*(1+math.cos(math.pi*step/a.steps))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(params,1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items(): + if k.startswith('confidence.'):ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + if step%a.save_every==0 or step==a.steps:save(step) +pool.shutdown() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/direct_large/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/direct_large/data.py new file mode 100644 index 0000000000000000000000000000000000000000..2378e33d7352ba5ad97d566148782e63e64b367c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/direct_large/data.py @@ -0,0 +1,71 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + return ctx,tgt,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/direct_large/evaluate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/direct_large/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..05f086d4d84def4a48165f9e65d2948877675e56 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/direct_large/evaluate.py @@ -0,0 +1,16 @@ +import sys,json,argparse,time,hashlib +from pathlib import Path +import torch +from predict import load_model,run +sys.path.insert(0,'/workspace/evaluation') +from score import score,json_safe + +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);ap.add_argument('--valid',default='/workspace/research/valid_screen');ap.add_argument('--baseline',default='/workspace/research/valid_screen/baseline.json');a=ap.parse_args() +torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cuda.matmul.allow_tf32=False +t0=time.time();out=Path(a.out);v=Path(a.valid) +run(load_model(a.weights),v/'input',out) +base=json.loads(Path(a.baseline).read_text())['configs'] +rep=score(v/'truth',out,base) +rep['checkpoint_sha256']=hashlib.sha256(Path(a.weights).read_bytes()).hexdigest();rep['eval_seconds']=time.time()-t0 +(out/'report.json').write_text(json.dumps(json_safe(rep),indent=1)) +print(json.dumps({k:rep[k] for k in ('skill_score','rel_mase_gmean','rel_wql_gmean','n_failed','groups','eval_seconds')},indent=1)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/direct_large/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/direct_large/model.py new file mode 100644 index 0000000000000000000000000000000000000000..7a224cc12a159446a1e427b2052b53d1d1f7e83e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/direct_large/model.py @@ -0,0 +1,142 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional(torch.arange(-nt,0,device=z.device),self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + q=self.query(base.reshape(b,h//p,p*9))+positional(torch.arange(h//p,device=z.device),self.d)[None]+emb + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + pin=torch.maximum(levels*err,(levels-1)*err).mean(-1) + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + return per.mean() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/direct_large/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/direct_large/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/direct_large/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/direct_large/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/direct_large/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..e20c6630475d6b4fa6906eb4ed9454b7b5aeec2c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/direct_large/predict.py @@ -0,0 +1,43 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):q=model.predict(x,p,h).float().cpu().numpy() + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/direct_large/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/direct_large/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf95c9aec5936076b881c340edb960786f2d40d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/direct_large/publish.py @@ -0,0 +1,31 @@ +"""Assemble a relocatable package, then atomically exchange complete directories.""" +import json,os,shutil,ctypes,hashlib,argparse +from pathlib import Path +import torch +HERE=Path(__file__).resolve().parent + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',default='/workspace/submission');ap.add_argument('--report',required=True);ap.add_argument('--experiments',default=str(HERE/'EXPERIMENTS.md'));a=ap.parse_args() + final=Path(a.out);staging=final.parent/f'.{final.name}-staging-{os.getpid()}' + shutil.rmtree(staging,ignore_errors=True);staging.mkdir(parents=True) + for file in ('model.py','predict.py','infer.sh','ts_io.py'): + shutil.copy(HERE/file,staging/file) + shutil.copy(a.weights,staging/'weights.pt');shutil.copy('/opt/runtime/requirements.txt',staging/'requirements.txt') + ck=torch.load(a.weights,map_location='cpu',weights_only=False);digest=hashlib.sha256((staging/'weights.pt').read_bytes()).hexdigest() + sources=json.loads(Path('/workspace/research/packed_sample/meta.json').read_text())['dirs'] + manifest={'name':'direct-seasonal-quantile-v1','contract':'timeseries-forecast/v1','parameters':sum(x.numel() for x in ck['model'].values()),'pretrained_assets':[],'sources_used':[f'gifteval_pretrain/{d}' for d in sources]+['synthetic:direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; data.py generator seed 17'],'weights_sha256':digest,'training_step':ck['step'],'config':ck['config'],'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.'} + (staging/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') + (staging/'config.json').write_text(json.dumps(ck['config'],indent=2)+'\n') + shutil.copy(a.experiments,staging/'EXPERIMENTS.md');shutil.copy(a.report,staging/'validation_report.json') + # Include generator/sampler provenance, which is not imported by inference. + (staging/'provenance').mkdir() + for file in ('pack.py','data.py','train.py'):shutil.copy(HERE/file,staging/'provenance'/file) + (staging/'README.md').write_text('# Direct seasonal quantile foundation forecaster\n\nRun `bash infer.sh INPUT_DIR OUTPUT_DIR`. This package contains all inference assets and uses only its supplied input directory. The 6.76M 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.\n\nThe 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.\n') + if final.exists(): + libc=ctypes.CDLL(None,use_errno=True) + if libc.renameat2(-100,os.fsencode(staging),-100,os.fsencode(final),2):raise OSError(ctypes.get_errno(),os.strerror(ctypes.get_errno())) + shutil.rmtree(staging) + else:os.replace(staging,final) + print(json.dumps(manifest,indent=1)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/direct_large/record.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/direct_large/record.py new file mode 100644 index 0000000000000000000000000000000000000000..1850a33f46fa3ee4d78cac4a5d6152404801a131 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/direct_large/record.py @@ -0,0 +1,9 @@ +import argparse,json,math +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('report');ap.add_argument('--label',required=True);ap.add_argument('--outcome',default='Screened for model selection.');a=ap.parse_args() +r=json.loads(Path(a.report).read_text());p=Path(__file__).with_name('EXPERIMENTS.md') +lines=[f'\n## {a.label}',f'- Checkpoint SHA-256: `{r.get("checkpoint_sha256","see model_manifest.json")}`.',f'- Evaluation: {r["n_configs"]} configurations, {r["n_instances"]} instances, {r["n_failed"]} failed configurations; {r.get("eval_seconds","not separately timed")} seconds.',f'- Overall skill {r["skill_score"]:.6f}; relative MASE {r["rel_mase_gmean"]:.6f}; relative WQL {r["rel_wql_gmean"]:.6f}.'] +for group,entries in r['groups'].items(): + lines.append(f'- {group} skill: '+', '.join(f'{k}={1-math.sqrt(v["rel_mase_gmean"]*v["rel_wql_gmean"]):.4f}' for k,v in entries.items())+'.') +lines.append('- Outcome: '+a.outcome) +with p.open('a') as f:f.write('\n'.join(lines)+'\n') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/direct_large/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/direct_large/train.py new file mode 100644 index 0000000000000000000000000000000000000000..a2ccc736bfef804259199a2dd315347d9854b680 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/direct_large/train.py @@ -0,0 +1,67 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(6);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/direct_large/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/direct_large/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/direct_large/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/direct_large/validation_subset.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/direct_large/validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..4df83e69c4f9a3365955e5d17ffcfc0af71372b7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/direct_large/validation_subset.py @@ -0,0 +1,18 @@ +"""Model-selection-only subset spanning all 97 configurations, seed 2026.""" +import sys,json,copy +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +import ts_io + +root=Path('/workspace/data/valid');out=Path('/workspace/research/valid_screen') +idx=json.loads((root/'input/index.json').read_text());new=copy.deepcopy(idx);rng=np.random.default_rng(2026) +for cfg in new['configs']: + cid=cfg['config_id'];case=ts_io.CaseFile(root/'input/cases'/f'{cid}.h5') + ids=np.sort(rng.choice(case.n,min(case.n,192),replace=False)) + ts_io.write_case_subset(case,ids,out/'input/cases'/f'{cid}.h5') + lab,se,meta=ts_io.read_truth_file(root/'truth/cases'/f'{cid}.h5') + ts_io.write_truth_file(out/'truth/cases'/f'{cid}.h5',lab[ids],se[ids],meta) + cfg['n_instances']=len(ids);case.close() +for kind in ('input','truth'):(out/kind/'index.json').write_text(json.dumps(new,indent=1)) +print('screen instances',sum(c['n_instances'] for c in new['configs'])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/full_paired/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/full_paired/check.py new file mode 100644 index 0000000000000000000000000000000000000000..fda928e16338305fd9912f7bc08cacff58bd8aa4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/full_paired/check.py @@ -0,0 +1,34 @@ +import importlib.util,json,time +from pathlib import Path +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +r=Path('/workspace/research');torch.set_num_threads(1);torch.manual_seed(197);start=time.monotonic() +ck=torch.load(r/'horizon_delta12k.pt',map_location='cpu',weights_only=False) +spec=importlib.util.spec_from_file_location('parent_model',r/'confidence_inference/model.py') +old=importlib.util.module_from_spec(spec);spec.loader.exec_module(old) +parent=old.DirectForecaster(**ck['config']);parent.load_state_dict(ck['model']) +m=DirectForecaster(**ck['config']);m.load_state_dict(ck['model']) +x=torch.randn(4,512);x[0,:50]=float('nan');p=torch.tensor([[24,168]]*4);y=torch.randn(4,128);y[0,32:]=float('nan') +with torch.inference_mode(): + assert all(torch.equal(a,b) for a,b in zip(m(x,p,48),parent(x,p,48))) + short=m(x,p,32)[0];long=m(x,p,128,forecast_lengths=torch.full((4,),32))[0][:,:32] + assert torch.allclose(short,long,atol=3e-6,rtol=1e-6),(short-long).abs().max() + paired=float(loss_fn(m,x,y,p,paired=True));reverse=float(loss_fn(m,-x,-y,p,paired=True)) + assert abs(paired-reverse)<1e-7,(paired,reverse) +a=Sampler(r/'packed_sample',197);b=Sampler(r/'packed_sample',197) +for c,h in [(512,32),(4096,1024)]: + assert all(np.array_equal(v,w,equal_nan=True) for v,w in zip(a.sample(16,c,h),b.sample(16,c,h))) +assert a.rng.bit_generator.state==b.rng.bit_generator.state and a.horizon_rng.bit_generator.state==b.horizon_rng.bit_generator.state +cpu=time.monotonic()-start;del parent,ck,a,b +m=m.cuda();ema={k:v.detach().clone() for k,v in m.state_dict().items()} +moments=[torch.zeros_like(v) for v in m.parameters() for _ in range(2)] +torch.backends.cuda.matmul.allow_tf32=True;torch.cuda.reset_peak_memory_stats();start=time.monotonic() +x=torch.randn(64,4096,device='cuda');y=torch.randn(64,1024,device='cuda');p=torch.tensor([[24,168]]*64,device='cuda') +with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(m,x,y,p,paired=True) +loss.backward();torch.cuda.synchronize() +assert torch.isfinite(loss) and all(v.grad is not None and torch.isfinite(v.grad).all() for v in m.parameters()) +z={'cpu_seconds':cpu,'initial_forecast_bitwise_parent':True,'unused_future_tokens_do_not_change_requested_prefix':True,'paired_loss_sign_symmetric':True,'matched_sampler_main_and_horizon_rng':True,'gpu_fixture_seconds':time.monotonic()-start,'allocated_mib':torch.cuda.max_memory_allocated()/2**20,'reserved_mib':torch.cuda.max_memory_reserved()/2**20,'optimizer_updates':0} +(r/'full_paired_checks.json').write_text(json.dumps(z,indent=2));print(json.dumps(z),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/full_paired/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/full_paired/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/full_paired/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/full_paired/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/full_paired/model.py new file mode 100644 index 0000000000000000000000000000000000000000..dedcdff4698028a8ba655865f8425d0dc3ef0dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/full_paired/model.py @@ -0,0 +1,204 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/horizon_jitter/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/horizon_jitter/data.py new file mode 100644 index 0000000000000000000000000000000000000000..3d632af7e96a71f30b7964a2b3fd73bc1c3f3f3e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/horizon_jitter/data.py @@ -0,0 +1,86 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/horizon_jitter/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/horizon_jitter/model.py new file mode 100644 index 0000000000000000000000000000000000000000..4ffe50d9aadf21d73949e2052ceb7f3642bf65d3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/horizon_jitter/model.py @@ -0,0 +1,180 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(ctx,periods,target.shape[-1],forecast_lengths=lengths) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/horizon_jitter/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/horizon_jitter/train.py new file mode 100644 index 0000000000000000000000000000000000000000..768d33da4421b24bd760d7d9680d0c2cd9bd84e4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/horizon_jitter/train.py @@ -0,0 +1,74 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler,truncate_targets + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + horizon_rng=np.random.default_rng(a.seed+startstep+300003) + def nextbatch(): + 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])) + return truncate_targets(sampler.sample(a.batch,c,h),horizon_rng,a.patch) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_corpus/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_corpus/data.py new file mode 100644 index 0000000000000000000000000000000000000000..a51e912d3c4b63a3ec0cd85133bf0e7aa3429569 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_corpus/data.py @@ -0,0 +1,73 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_corpus/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_corpus/model.py new file mode 100644 index 0000000000000000000000000000000000000000..f8271c5b0bf9a5edb961e1c7839761fe50a2e40b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_corpus/model.py @@ -0,0 +1,171 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024,recency_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + if self.recency is not None: + pos=torch.arange(c,device=z.device)[None,:];extras=[] + for j in range(2): + period=periods[:,j:j+1] + recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_corpus/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_corpus/train.py new file mode 100644 index 0000000000000000000000000000000000000000..2e77612e443d78dd80bcb6a0cc6d01169f61a3a4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_corpus/train.py @@ -0,0 +1,73 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_sign/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_sign/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_sign/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_sign/evaluate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_sign/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..05f086d4d84def4a48165f9e65d2948877675e56 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_sign/evaluate.py @@ -0,0 +1,16 @@ +import sys,json,argparse,time,hashlib +from pathlib import Path +import torch +from predict import load_model,run +sys.path.insert(0,'/workspace/evaluation') +from score import score,json_safe + +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);ap.add_argument('--valid',default='/workspace/research/valid_screen');ap.add_argument('--baseline',default='/workspace/research/valid_screen/baseline.json');a=ap.parse_args() +torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cuda.matmul.allow_tf32=False +t0=time.time();out=Path(a.out);v=Path(a.valid) +run(load_model(a.weights),v/'input',out) +base=json.loads(Path(a.baseline).read_text())['configs'] +rep=score(v/'truth',out,base) +rep['checkpoint_sha256']=hashlib.sha256(Path(a.weights).read_bytes()).hexdigest();rep['eval_seconds']=time.time()-t0 +(out/'report.json').write_text(json.dumps(json_safe(rep),indent=1)) +print(json.dumps({k:rep[k] for k in ('skill_score','rel_mase_gmean','rel_wql_gmean','n_failed','groups','eval_seconds')},indent=1)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_sign/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_sign/model.py new file mode 100644 index 0000000000000000000000000000000000000000..60aeb14b5f4fa298521ddce8a3276d076c1bb631 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_sign/model.py @@ -0,0 +1,154 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional(torch.arange(-nt,0,device=z.device),self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + q=self.query(base.reshape(b,h//p,p*9))+positional(torch.arange(h//p,device=z.device),self.d)[None]+emb + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_sign/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_sign/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_sign/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_sign/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_sign/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..e20c6630475d6b4fa6906eb4ed9454b7b5aeec2c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_sign/predict.py @@ -0,0 +1,43 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):q=model.predict(x,p,h).float().cpu().numpy() + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_sign/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_sign/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf95c9aec5936076b881c340edb960786f2d40d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_sign/publish.py @@ -0,0 +1,31 @@ +"""Assemble a relocatable package, then atomically exchange complete directories.""" +import json,os,shutil,ctypes,hashlib,argparse +from pathlib import Path +import torch +HERE=Path(__file__).resolve().parent + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',default='/workspace/submission');ap.add_argument('--report',required=True);ap.add_argument('--experiments',default=str(HERE/'EXPERIMENTS.md'));a=ap.parse_args() + final=Path(a.out);staging=final.parent/f'.{final.name}-staging-{os.getpid()}' + shutil.rmtree(staging,ignore_errors=True);staging.mkdir(parents=True) + for file in ('model.py','predict.py','infer.sh','ts_io.py'): + shutil.copy(HERE/file,staging/file) + shutil.copy(a.weights,staging/'weights.pt');shutil.copy('/opt/runtime/requirements.txt',staging/'requirements.txt') + ck=torch.load(a.weights,map_location='cpu',weights_only=False);digest=hashlib.sha256((staging/'weights.pt').read_bytes()).hexdigest() + sources=json.loads(Path('/workspace/research/packed_sample/meta.json').read_text())['dirs'] + manifest={'name':'direct-seasonal-quantile-v1','contract':'timeseries-forecast/v1','parameters':sum(x.numel() for x in ck['model'].values()),'pretrained_assets':[],'sources_used':[f'gifteval_pretrain/{d}' for d in sources]+['synthetic:direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; data.py generator seed 17'],'weights_sha256':digest,'training_step':ck['step'],'config':ck['config'],'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.'} + (staging/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') + (staging/'config.json').write_text(json.dumps(ck['config'],indent=2)+'\n') + shutil.copy(a.experiments,staging/'EXPERIMENTS.md');shutil.copy(a.report,staging/'validation_report.json') + # Include generator/sampler provenance, which is not imported by inference. + (staging/'provenance').mkdir() + for file in ('pack.py','data.py','train.py'):shutil.copy(HERE/file,staging/'provenance'/file) + (staging/'README.md').write_text('# Direct seasonal quantile foundation forecaster\n\nRun `bash infer.sh INPUT_DIR OUTPUT_DIR`. This package contains all inference assets and uses only its supplied input directory. The 6.76M 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.\n\nThe 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.\n') + if final.exists(): + libc=ctypes.CDLL(None,use_errno=True) + if libc.renameat2(-100,os.fsencode(staging),-100,os.fsencode(final),2):raise OSError(ctypes.get_errno(),os.strerror(ctypes.get_errno())) + shutil.rmtree(staging) + else:os.replace(staging,final) + print(json.dumps(manifest,indent=1)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_sign/record.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_sign/record.py new file mode 100644 index 0000000000000000000000000000000000000000..1850a33f46fa3ee4d78cac4a5d6152404801a131 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_sign/record.py @@ -0,0 +1,9 @@ +import argparse,json,math +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('report');ap.add_argument('--label',required=True);ap.add_argument('--outcome',default='Screened for model selection.');a=ap.parse_args() +r=json.loads(Path(a.report).read_text());p=Path(__file__).with_name('EXPERIMENTS.md') +lines=[f'\n## {a.label}',f'- Checkpoint SHA-256: `{r.get("checkpoint_sha256","see model_manifest.json")}`.',f'- Evaluation: {r["n_configs"]} configurations, {r["n_instances"]} instances, {r["n_failed"]} failed configurations; {r.get("eval_seconds","not separately timed")} seconds.',f'- Overall skill {r["skill_score"]:.6f}; relative MASE {r["rel_mase_gmean"]:.6f}; relative WQL {r["rel_wql_gmean"]:.6f}.'] +for group,entries in r['groups'].items(): + lines.append(f'- {group} skill: '+', '.join(f'{k}={1-math.sqrt(v["rel_mase_gmean"]*v["rel_wql_gmean"]):.4f}' for k,v in entries.items())+'.') +lines.append('- Outcome: '+a.outcome) +with p.open('a') as f:f.write('\n'.join(lines)+'\n') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_sign/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_sign/train.py new file mode 100644 index 0000000000000000000000000000000000000000..d089166fb1612ddf4955fcd2f096cb0b33624dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_sign/train.py @@ -0,0 +1,70 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(3);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_sign/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_sign/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_sign/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_sign/validation_subset.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_sign/validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..4df83e69c4f9a3365955e5d17ffcfc0af71372b7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/large_sign/validation_subset.py @@ -0,0 +1,18 @@ +"""Model-selection-only subset spanning all 97 configurations, seed 2026.""" +import sys,json,copy +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +import ts_io + +root=Path('/workspace/data/valid');out=Path('/workspace/research/valid_screen') +idx=json.loads((root/'input/index.json').read_text());new=copy.deepcopy(idx);rng=np.random.default_rng(2026) +for cfg in new['configs']: + cid=cfg['config_id'];case=ts_io.CaseFile(root/'input/cases'/f'{cid}.h5') + ids=np.sort(rng.choice(case.n,min(case.n,192),replace=False)) + ts_io.write_case_subset(case,ids,out/'input/cases'/f'{cid}.h5') + lab,se,meta=ts_io.read_truth_file(root/'truth/cases'/f'{cid}.h5') + ts_io.write_truth_file(out/'truth/cases'/f'{cid}.h5',lab[ids],se[ids],meta) + cfg['n_instances']=len(ids);case.close() +for kind in ('input','truth'):(out/kind/'index.json').write_text(json.dumps(new,indent=1)) +print('screen instances',sum(c['n_instances'] for c in new['configs'])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/long_memory_synth/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/long_memory_synth/data.py new file mode 100644 index 0000000000000000000000000000000000000000..95410ba700e638fc2e1375b14dece4df57c10110 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/long_memory_synth/data.py @@ -0,0 +1,73 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=np.exp(-10**(-r.uniform(0,4)));noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/long_memory_synth/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/long_memory_synth/model.py new file mode 100644 index 0000000000000000000000000000000000000000..4ffe50d9aadf21d73949e2052ceb7f3642bf65d3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/long_memory_synth/model.py @@ -0,0 +1,180 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(ctx,periods,target.shape[-1],forecast_lengths=lengths) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/long_memory_synth/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/long_memory_synth/train.py new file mode 100644 index 0000000000000000000000000000000000000000..61de733eea03837247278d9010c2ed8b955d7359 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/long_memory_synth/train.py @@ -0,0 +1,74 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + a.synthetic_ar_time_constants=[1,10000] + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/long_seasonal/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/long_seasonal/check.py new file mode 100644 index 0000000000000000000000000000000000000000..beba62576fae73576eef907b81c674e96622670d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/long_seasonal/check.py @@ -0,0 +1,145 @@ +"""Check exact initialization, fixed feature arithmetic and allowed-data gradients.""" +import argparse +import hashlib +import importlib.util +import json +import sys +import time +from pathlib import Path + +import numpy as np +import torch + +R = Path('/workspace/research') +sys.path.insert(0, str(R / 'long_seasonal')) +from model import DirectForecaster, centered_seasonal_difference, loss_fn +from data import Sampler + +ap = argparse.ArgumentParser() +ap.add_argument('--gpu', action='store_true') +a = ap.parse_args() +torch.set_num_threads(2) +torch.manual_seed(503) +started = time.monotonic() +spec = importlib.util.spec_from_file_location('long_control_model', R / 'overflow_control/model.py') +control_code = importlib.util.module_from_spec(spec) +spec.loader.exec_module(control_code) +parent_path = R / 'horizon_delta12k.pt' +parent = torch.load(parent_path, map_location='cpu', weights_only=False) +config = dict(parent['config'], long_seasonal_features=True) +candidate = DirectForecaster(**config) +missing, unexpected = candidate.load_state_dict(parent['model'], strict=False) +assert set(missing) == {'long_query.weight', 'long_head.weight', 'long_head.bias'} +assert not unexpected +assert all(torch.count_nonzero(candidate.state_dict()[key]) == 0 for key in missing) +control = control_code.DirectForecaster(**parent['config']) +control.load_state_dict(parent['model']) +assert all(torch.equal(value, candidate.state_dict()[key]) for key, value in parent['model'].items()) + +if a.gpu: + import fcntl + lock = open(R / '.evaluation.lock', 'a') + fcntl.flock(lock, fcntl.LOCK_EX) + device = 'cuda' + torch.backends.cuda.matmul.allow_tf32 = False + candidate = candidate.cuda() + control = control.cuda() + rng = np.random.default_rng(509) + x = torch.tensor(rng.normal(size=(8, 512)).astype(np.float32), device=device) + x[0, :23] = float('nan') + x[1] = 0 + p = torch.tensor([[24,168],[7,365],[12,1],[52,1],[4,1],[1,1],[96,672],[2,14]], device=device) + with torch.inference_mode(), torch.autocast('cuda', dtype=torch.bfloat16): + expected = control(x, p, 128) + actual = candidate(x, p, 128) + assert all(torch.equal(v, w) for v, w in zip(expected, actual)) + del control, expected, actual, x, p + torch.cuda.empty_cache() + torch.cuda.reset_peak_memory_stats() + sampler = Sampler(R / 'packed_sample', seed=509, source_weights_from=R / 'packed_sample') + arrays = sampler.sample(64, 4096, 1024) + tensors = [torch.from_numpy(v).cuda() for v in arrays] + placeholders = [torch.zeros_like(v) for v in candidate.parameters() for _ in range(3)] + with torch.autocast('cuda', dtype=torch.bfloat16): + loss = loss_fn(candidate, *tensors, paired=True) + loss.backward() + assert torch.isfinite(loss) + assert all(v.grad is None or torch.isfinite(v.grad).all() for v in candidate.parameters()) + gradients = {key: float(dict(candidate.named_parameters())[key].grad.norm()) for key in missing} + assert gradients['long_head.weight'] > 0 and gradients['long_query.weight'] > 0 + result = dict(seed=509, gpu_initial_function_bitwise_equal=True, + max_shape=[64,4096,1024], loss=float(loss.detach()), added_gradient_norms=gradients, + reserved_mib=torch.cuda.max_memory_reserved()/2**20, + allocated_mib=torch.cuda.max_memory_allocated()/2**20, + includes_ema_and_adam_placeholders=True, seconds=time.monotonic()-started, + optimizer_updates=0, validation_data_read=False) + (R / 'long_seasonal_gpu_checks.json').write_text(json.dumps(result, indent=2)) + print(json.dumps(result)) + raise SystemExit() + +rng = np.random.default_rng(503) +z = rng.normal(size=(4, 96)).astype(np.float32) +valid = rng.random(z.shape) > .12 +z[~valid] = 0 +periods = np.array([[4,7],[2,3],[12,1],[24,168]], dtype=np.int64) +delta, extra = centered_seasonal_difference(torch.from_numpy(z), torch.from_numpy(valid), + torch.from_numpy(periods), 23) +expected = np.zeros((4,23,2), np.float32) +support = np.zeros_like(expected) +for row in range(4): + for j in range(2): + period = int(periods[row,j]) + for t in range(23): + observations, recent = [], [] + for cycle in range(16): + end = max(0, 96-cycle*period) + start = max(0, 96-(cycle+1)*period) + index = 96-period+t%period-cycle*period + if index < 0 or not valid[row,index]: + continue + mean = z[row,start:end][valid[row,start:end]].mean(dtype=np.float64) + value = float(z[row,index])-mean + observations.append(value) + if cycle < 4: + recent.append(value) + if period>=2 and len(observations)>=8 and len(recent)>=2: + expected[row,t,j] = np.mean(observations)-np.mean(recent) + support[row,t,j] = len(observations)/16 +assert np.max(np.abs(delta.numpy()-expected)) < 1e-6 +assert np.array_equal(extra.numpy()[:,:,[1,3]], support) +# Adding a different constant to each complete cycle leaves centered templates unchanged. +z0 = torch.tensor(rng.normal(size=(1,64)).astype(np.float32)) +offsets = torch.tensor(rng.normal(size=(1,16,1)).astype(np.float32)) +z1 = (z0.view(1,16,4)+offsets).view(1,64) +p = torch.tensor([[4,4]]) +ones = torch.ones_like(z0,dtype=torch.bool) +v0 = centered_seasonal_difference(z0,ones,p,16)[0] +v1 = centered_seasonal_difference(z1,ones,p,16)[0] +assert torch.max(torch.abs(v0-v1)) < 1e-6 +for c,h in [(32,6),(96,23),(512,128)]: + ctx = torch.tensor(rng.normal(size=(4,c)).astype(np.float32)) + ctx[0,:c//3] = float('nan') + ctx[1] = 0 + ctx[2] = float('nan') + with torch.inference_mode(): + expected = control(ctx,torch.from_numpy(periods),h) + actual = candidate(ctx,torch.from_numpy(periods),h) + assert all(torch.equal(v,w) for v,w in zip(expected,actual)) +assert (R/'long_seasonal/data.py').read_bytes()==(R/'overflow_control/data.py').read_bytes() +out = R / 'long_seasonal_initial.pt' +assert not out.exists(), 'Do not overwrite an existing declared initial checkpoint' +checkpoint = dict(model=candidate.state_dict(), config=config, step=0, + args=dict(packed=str(R/'packed_sample'), seed=503), + parent_checkpoints=[str(parent_path)], + conversion=dict(method='zero-initialized sixteen-cycle centered seasonal query/head additions', + parent_sha256=hashlib.sha256(parent_path.read_bytes()).hexdigest(), + initial_function_bitwise_equal=True)) +torch.save(checkpoint,out) +result = dict(seed=503, independent_feature_arithmetic=True, centered_cycle_offset_invariance=True, + initial_function_bitwise_equal=True, inherited_weights_bitwise_equal=True, + sampler_byte_identical=True, added_parameters=sum(candidate.state_dict()[k].numel() for k in missing), + total_parameters=sum(v.numel() for v in candidate.parameters()), + checkpoint_sha256=hashlib.sha256(out.read_bytes()).hexdigest(), + seconds=time.monotonic()-started, optimizer_updates=0, validation_data_read=False) +(R/'long_seasonal_checks.json').write_text(json.dumps(result,indent=2)) +print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/long_seasonal/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/long_seasonal/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/long_seasonal/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/long_seasonal/launch.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/long_seasonal/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..d7fd732aae9def625f17a4d15dd2dbe3f4cd9317 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/long_seasonal/launch.py @@ -0,0 +1,31 @@ +"""Queue the audited learned sixteen-cycle summary after nested-volume training.""" +def main(): + import json + import os + import subprocess + from pathlib import Path + R=Path('/workspace/research') + checks=json.loads((R/'long_seasonal_checks.json').read_text()) + assert checks['initial_function_bitwise_equal'] and checks['inherited_weights_bitwise_equal'] + assert checks['independent_feature_arithmetic'] and checks['sampler_byte_identical'] + gpu=json.loads((R/'long_seasonal_gpu_checks.json').read_text()) + assert gpu['gpu_initial_function_bitwise_equal'] and gpu['reserved_mib']<10000 + env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1') + command=['python3',str(R/'recovery/train.py'),'--code-dir',str(R/'long_seasonal'), + '--packed',str(R/'packed_sample'),'--source-weights-from',str(R/'packed_sample'), + '--out',str(R/'runs/long_seasonal'),'--initialize-from',str(R/'long_seasonal_initial.pt'), + '--steps','12000','--batch','64','--lr','.00002','--seed','197','--loss-mode','paired', + '--stop-file',str(R/'long_seasonal.stop')] + with (R/'long_seasonal_queue.log').open('w') as qlog,(R/'long_seasonal_watch.log').open('w') as wlog: + queued=subprocess.Popen(['python3',str(R/'queued_train.py'),'--label','E107 learned sixteen-cycle summary seed197', + '--log',str(R/'long_seasonal_train.log'),'--receipt',str(R/'long_seasonal_queue.json'), + '--wait-pid','13470','--require-checkpoint',str(R/'runs/stratified_volume/recovery.pt'), + '--',*command],stdout=qlog,stderr=subprocess.STDOUT,env=env) + watch=subprocess.Popen(['python3',str(R/'watch_evaluate.py'),'--run',str(R/'runs/long_seasonal'), + '--evaluator',str(R/'long_seasonal_inference/evaluate.py'),'--name','long_seasonal', + '--expected-packed',str(R/'packed_sample'),'--steps','1000,3000,6000,12000'],stdout=wlog,stderr=subprocess.STDOUT,env=env) + print({'queue_pid':queued.pid,'watch_pid':watch.pid},flush=True) + result=queued.wait() + if result:watch.terminate() + watch.wait();raise SystemExit(result) +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/long_seasonal/long_features.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/long_seasonal/long_features.py new file mode 100644 index 0000000000000000000000000000000000000000..efc6e3ba327c6016d844148fcfcc29ac63863f23 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/long_seasonal/long_features.py @@ -0,0 +1,37 @@ +"""Fixed within-context phase summaries; no estimated or adapted parameters.""" +import torch +from torch.nn import functional as F + + +def centered_seasonal_difference(z, valid, periods, horizon): + b, c = z.shape + time = torch.arange(horizon, device=z.device)[None, :] + sums = F.pad((z * valid).cumsum(-1), (1, 0)) + counts = F.pad(valid.float().cumsum(-1), (1, 0)) + deltas, extras = [], [] + for j in range(2): + period = periods[:, j:j+1].clamp(min=1) + anchor = c - period + time % period + centered, masks = [], [] + for cycle in range(16): + end = (c - cycle * period).clamp(min=0, max=c) + start = (c - (cycle + 1) * period).clamp(min=0, max=c) + count = counts.gather(1, end) - counts.gather(1, start) + mean = (sums.gather(1, end) - sums.gather(1, start)) / count.clamp(min=1) + index = anchor - cycle * period + safe = index.clamp(min=0, max=c-1) + present = (index >= 0) & valid.gather(1, safe) + centered.append(z.gather(1, safe) - mean) + masks.append(present) + values = torch.stack(centered) + seen = torch.stack(masks) + n4 = seen[:4].sum(0) + n16 = seen.sum(0) + mean4 = (values[:4] * seen[:4]).sum(0) / n4.clamp(min=1) + mean16 = (values * seen).sum(0) / n16.clamp(min=1) + active = (period >= 2) & (n4 >= 2) & (n16 >= 8) + delta = torch.where(active, mean16 - mean4, 0.) + support = torch.where(active, n16.float() / 16, 0.) + deltas.append(delta) + extras.extend([delta, support]) + return torch.stack(deltas, -1), torch.stack(extras, -1) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/long_seasonal/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/long_seasonal/model.py new file mode 100644 index 0000000000000000000000000000000000000000..298ee3b840cbc8b7da585ee5e47a3822d06717b0 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/long_seasonal/model.py @@ -0,0 +1,260 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + + +def centered_seasonal_difference(z, valid, periods, horizon): + b, c = z.shape + time = torch.arange(horizon, device=z.device)[None, :] + sums = F.pad((z * valid).cumsum(-1), (1, 0)) + counts = F.pad(valid.float().cumsum(-1), (1, 0)) + deltas, extras = [], [] + for j in range(2): + period = periods[:, j:j+1].clamp(min=1) + anchor = c - period + time % period + centered, masks = [], [] + for cycle in range(16): + end = (c - cycle * period).clamp(min=0, max=c) + start = (c - (cycle + 1) * period).clamp(min=0, max=c) + count = counts.gather(1, end) - counts.gather(1, start) + mean = (sums.gather(1, end) - sums.gather(1, start)) / count.clamp(min=1) + index = anchor - cycle * period + safe = index.clamp(min=0, max=c-1) + present = (index >= 0) & valid.gather(1, safe) + centered.append(z.gather(1, safe) - mean) + masks.append(present) + values = torch.stack(centered) + seen = torch.stack(masks) + n4 = seen[:4].sum(0) + n16 = seen.sum(0) + mean4 = (values[:4] * seen[:4]).sum(0) / n4.clamp(min=1) + mean16 = (values * seen).sum(0) / n16.clamp(min=1) + active = (period >= 2) & (n4 >= 2) & (n16 >= 8) + delta = torch.where(active, mean16 - mean4, 0.) + support = torch.where(active, n16.float() / 16, 0.) + deltas.append(delta) + extras.extend([delta, support]) + return torch.stack(deltas, -1), torch.stack(extras, -1) + + + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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,long_seasonal_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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,long_seasonal_features=long_seasonal_features) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + self.long_query=nn.Linear(patch*4,d,bias=False) if long_seasonal_features else None + self.long_head=nn.Linear(d,patch*2) if long_seasonal_features else None + if long_seasonal_features: + nn.init.zeros_(self.long_query.weight) + nn.init.zeros_(self.long_head.weight);nn.init.zeros_(self.long_head.bias) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + if self.long_query is not None:long_delta,long_extra=centered_seasonal_difference(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + hidden=self.norm(q) + out=self.head(hidden).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + if self.long_head is not None: + gates=self.long_head(hidden).view(b,h,2).float().tanh() + median=median+(gates*long_delta).sum(-1) + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/long_seasonal/transfer.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/long_seasonal/transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..c20a4df852f5b150e634ae2c06510d01c7ea18b3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/long_seasonal/transfer.py @@ -0,0 +1,73 @@ +"""Apply one matched feature-learning difference with explicit zero-extension semantics.""" +import argparse +import hashlib +import importlib.util +import json +import sys +import time +from pathlib import Path + +import numpy as np +import torch + +R = Path('/workspace/research') +parser = argparse.ArgumentParser() +for key in ['base','candidate','control','out']: + parser.add_argument('--'+key,required=True) +args = parser.parse_args() +torch.set_num_threads(2) +torch.manual_seed(571) +started = time.monotonic() +paths = [Path(args.base),Path(args.candidate),Path(args.control)] +base,candidate,control = [torch.load(p,map_location='cpu',weights_only=False) for p in paths] +extra = {'long_query.weight','long_head.weight','long_head.bias'} +assert set(base['model'])==set(control['model']) +assert set(candidate['model'])==set(base['model'])|extra +config = dict(candidate['config']) +assert config.pop('long_seasonal_features') is True +assert config==base['config']==control['config'] +sys.path.insert(0,str(R/'long_seasonal')) +from model import DirectForecaster +extended = DirectForecaster(**candidate['config']) +missing,unexpected = extended.load_state_dict(base['model'],strict=False) +assert set(missing)==extra and not unexpected +assert all(torch.count_nonzero(extended.state_dict()[k])==0 for k in extra) +spec = importlib.util.spec_from_file_location('transfer_original_model',R/'overflow_control/model.py') +code = importlib.util.module_from_spec(spec) +spec.loader.exec_module(code) +original = code.DirectForecaster(**base['config']) +original.load_state_dict(base['model']) +rng = np.random.default_rng(571) +periods = torch.tensor([[24,168],[7,365],[52,1],[1,1]]) +for c,h in [(32,6),(512,128)]: + ctx = torch.tensor(rng.normal(size=(4,c)).astype(np.float32)) + ctx[0,:c//3] = float('nan') + ctx[1] = 0 + ctx[2] = float('nan') + with torch.inference_mode(): + a = original(ctx,periods,h) + b = extended(ctx,periods,h) + assert all(torch.equal(v,w) for v,w in zip(a,b)) +weights = {k:v.clone() for k,v in extended.state_dict().items()} +for k in weights: + if k in extra: + weights[k].copy_(candidate['model'][k]) + else: + assert weights[k].shape==candidate['model'][k].shape==control['model'][k].shape + weights[k].add_(candidate['model'][k]-control['model'][k]) +assert all(torch.isfinite(v).all() for v in weights.values()) +out = Path(args.out) +assert not out.exists(),'Refuse to overwrite a declared fixed candidate' +conversion = dict(method='matched training delta after zero extension of new seasonal query/head parameters', + formula='extend_zero(base) + candidate - extend_zero(control)',coefficient=1.0, + new_parameters_from_candidate=sorted(extra), + parent_hashes={str(p):hashlib.sha256(p.read_bytes()).hexdigest() for p in paths}, + base_extension_forward_bitwise_equal=True,check_seed=571, + seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False) +checkpoint = dict(model=weights,config=candidate['config'],step=0,args={'packed':base['args']['packed']}, + parent_checkpoints=[str(p) for p in paths],conversion=conversion) +torch.save(checkpoint,out) +result = dict(conversion,checkpoint_sha256=hashlib.sha256(out.read_bytes()).hexdigest(), + parameters=sum(v.numel() for v in weights.values())) +out.with_suffix('.json').write_text(json.dumps(result,indent=2)) +print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/overflow_control/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/overflow_control/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/overflow_control/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/overflow_control/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/overflow_control/model.py new file mode 100644 index 0000000000000000000000000000000000000000..3532e5063bd8b5013f6b6e35703707ffef66e00b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/overflow_control/model.py @@ -0,0 +1,213 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/partial_delta/merge.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/partial_delta/merge.py new file mode 100644 index 0000000000000000000000000000000000000000..3dde47d52d25ed2b013942b3887f1bf686e42ed8 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/partial_delta/merge.py @@ -0,0 +1,16 @@ +"""Apply the difference of two matched, locally trained checkpoints to our selected model.""" +import argparse,torch,hashlib,json,time +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('--base',required=True);ap.add_argument('--candidate',required=True);ap.add_argument('--control',required=True);ap.add_argument('--out',required=True);a=ap.parse_args() +torch.set_num_threads(1);start=time.monotonic() +base=torch.load(a.base,map_location='cpu',weights_only=False);candidate=torch.load(a.candidate,map_location='cpu',weights_only=False);control=torch.load(a.control,map_location='cpu',weights_only=False) +assert set(candidate['model'])==set(control['model']) +weights={k:v.clone() for k,v in base['model'].items()} +for k in candidate['model']: + assert k in weights and weights[k].shape==candidate['model'][k].shape==control['model'][k].shape + weights[k].add_(candidate['model'][k]-control['model'][k]) +assert all(torch.isfinite(v).all() for v in weights.values()) +parents=[a.base,a.candidate,a.control] +conversion={'method':'matched training delta','formula':'base + candidate - control','coefficient':1.0,'parent_hashes':{p:hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in parents},'seconds':time.monotonic()-start} +ck={'model':weights,'config':base['config'],'step':0,'args':{'packed':base['args']['packed']},'parent_checkpoints':parents,'conversion':conversion} +torch.save(ck,a.out);print(json.dumps(conversion)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/partial_targets/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/partial_targets/data.py new file mode 100644 index 0000000000000000000000000000000000000000..a51e912d3c4b63a3ec0cd85133bf0e7aa3429569 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/partial_targets/data.py @@ -0,0 +1,73 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/partial_targets/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/partial_targets/model.py new file mode 100644 index 0000000000000000000000000000000000000000..4ffe50d9aadf21d73949e2052ceb7f3642bf65d3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/partial_targets/model.py @@ -0,0 +1,180 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(ctx,periods,target.shape[-1],forecast_lengths=lengths) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/partial_targets/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/partial_targets/train.py new file mode 100644 index 0000000000000000000000000000000000000000..2e77612e443d78dd80bcb6a0cc6d01169f61a3a4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/partial_targets/train.py @@ -0,0 +1,73 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/convert.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/convert.py new file mode 100644 index 0000000000000000000000000000000000000000..b2cbc8fc919be6a77eca9ab19c4faa06060a2e0d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/convert.py @@ -0,0 +1,18 @@ +"""Convert only our own trained checkpoint from 32- to 16-point patches. + +Context/query projections fold the two halves by summation, preserving the +embedding of constant features. The output projection keeps the first half. +Attention/MLP weights are inherited unchanged; position units remain 32 points. +""" +import argparse,torch,hashlib +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('--input',required=True);ap.add_argument('--output',required=True);a=ap.parse_args() +ck=torch.load(a.input,map_location='cpu',weights_only=False);state=ck['model'];d=ck['config']['d'];assert ck['config']['patch']==32 +old=state['embed.0.weight'].reshape(d,2,32);state['embed.0.weight']=(old[:,:,:16]+old[:,:,16:]).reshape(d,32) +old=state['query.0.weight'].reshape(d,32,9);state['query.0.weight']=(old[:,:16]+old[:,16:]).reshape(d,16*9) +state['head.weight']=state['head.weight'].reshape(32,18,d)[:16].reshape(16*18,d).clone() +state['head.bias']=state['head.bias'].reshape(32,18)[:16].reshape(16*18).clone() +ck['config']['patch']=16 +ck['conversion']={'from_checkpoint':str(Path(a.input).resolve()),'from_sha256':hashlib.sha256(Path(a.input).read_bytes()).hexdigest(),'method':'fold input/query halves by summation; retain first 16 output rows; preserve physical positional units'} +ck['args']={**ck['args'],'initialize_from':str(Path(a.input).resolve()),'converted':True} +torch.save(ck,a.output) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/evaluate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..05f086d4d84def4a48165f9e65d2948877675e56 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/evaluate.py @@ -0,0 +1,16 @@ +import sys,json,argparse,time,hashlib +from pathlib import Path +import torch +from predict import load_model,run +sys.path.insert(0,'/workspace/evaluation') +from score import score,json_safe + +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);ap.add_argument('--valid',default='/workspace/research/valid_screen');ap.add_argument('--baseline',default='/workspace/research/valid_screen/baseline.json');a=ap.parse_args() +torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cuda.matmul.allow_tf32=False +t0=time.time();out=Path(a.out);v=Path(a.valid) +run(load_model(a.weights),v/'input',out) +base=json.loads(Path(a.baseline).read_text())['configs'] +rep=score(v/'truth',out,base) +rep['checkpoint_sha256']=hashlib.sha256(Path(a.weights).read_bytes()).hexdigest();rep['eval_seconds']=time.time()-t0 +(out/'report.json').write_text(json.dumps(json_safe(rep),indent=1)) +print(json.dumps({k:rep[k] for k in ('skill_score','rel_mase_gmean','rel_wql_gmean','n_failed','groups','eval_seconds')},indent=1)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/model.py new file mode 100644 index 0000000000000000000000000000000000000000..06cce56e2ce671b6683f0246900abfcac06bb3c0 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/model.py @@ -0,0 +1,154 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..e20c6630475d6b4fa6906eb4ed9454b7b5aeec2c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/predict.py @@ -0,0 +1,43 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):q=model.predict(x,p,h).float().cpu().numpy() + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf95c9aec5936076b881c340edb960786f2d40d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/publish.py @@ -0,0 +1,31 @@ +"""Assemble a relocatable package, then atomically exchange complete directories.""" +import json,os,shutil,ctypes,hashlib,argparse +from pathlib import Path +import torch +HERE=Path(__file__).resolve().parent + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',default='/workspace/submission');ap.add_argument('--report',required=True);ap.add_argument('--experiments',default=str(HERE/'EXPERIMENTS.md'));a=ap.parse_args() + final=Path(a.out);staging=final.parent/f'.{final.name}-staging-{os.getpid()}' + shutil.rmtree(staging,ignore_errors=True);staging.mkdir(parents=True) + for file in ('model.py','predict.py','infer.sh','ts_io.py'): + shutil.copy(HERE/file,staging/file) + shutil.copy(a.weights,staging/'weights.pt');shutil.copy('/opt/runtime/requirements.txt',staging/'requirements.txt') + ck=torch.load(a.weights,map_location='cpu',weights_only=False);digest=hashlib.sha256((staging/'weights.pt').read_bytes()).hexdigest() + sources=json.loads(Path('/workspace/research/packed_sample/meta.json').read_text())['dirs'] + manifest={'name':'direct-seasonal-quantile-v1','contract':'timeseries-forecast/v1','parameters':sum(x.numel() for x in ck['model'].values()),'pretrained_assets':[],'sources_used':[f'gifteval_pretrain/{d}' for d in sources]+['synthetic:direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; data.py generator seed 17'],'weights_sha256':digest,'training_step':ck['step'],'config':ck['config'],'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.'} + (staging/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') + (staging/'config.json').write_text(json.dumps(ck['config'],indent=2)+'\n') + shutil.copy(a.experiments,staging/'EXPERIMENTS.md');shutil.copy(a.report,staging/'validation_report.json') + # Include generator/sampler provenance, which is not imported by inference. + (staging/'provenance').mkdir() + for file in ('pack.py','data.py','train.py'):shutil.copy(HERE/file,staging/'provenance'/file) + (staging/'README.md').write_text('# Direct seasonal quantile foundation forecaster\n\nRun `bash infer.sh INPUT_DIR OUTPUT_DIR`. This package contains all inference assets and uses only its supplied input directory. The 6.76M 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.\n\nThe 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.\n') + if final.exists(): + libc=ctypes.CDLL(None,use_errno=True) + if libc.renameat2(-100,os.fsencode(staging),-100,os.fsencode(final),2):raise OSError(ctypes.get_errno(),os.strerror(ctypes.get_errno())) + shutil.rmtree(staging) + else:os.replace(staging,final) + print(json.dumps(manifest,indent=1)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/record.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/record.py new file mode 100644 index 0000000000000000000000000000000000000000..1850a33f46fa3ee4d78cac4a5d6152404801a131 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/record.py @@ -0,0 +1,9 @@ +import argparse,json,math +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('report');ap.add_argument('--label',required=True);ap.add_argument('--outcome',default='Screened for model selection.');a=ap.parse_args() +r=json.loads(Path(a.report).read_text());p=Path(__file__).with_name('EXPERIMENTS.md') +lines=[f'\n## {a.label}',f'- Checkpoint SHA-256: `{r.get("checkpoint_sha256","see model_manifest.json")}`.',f'- Evaluation: {r["n_configs"]} configurations, {r["n_instances"]} instances, {r["n_failed"]} failed configurations; {r.get("eval_seconds","not separately timed")} seconds.',f'- Overall skill {r["skill_score"]:.6f}; relative MASE {r["rel_mase_gmean"]:.6f}; relative WQL {r["rel_wql_gmean"]:.6f}.'] +for group,entries in r['groups'].items(): + lines.append(f'- {group} skill: '+', '.join(f'{k}={1-math.sqrt(v["rel_mase_gmean"]*v["rel_wql_gmean"]):.4f}' for k,v in entries.items())+'.') +lines.append('- Outcome: '+a.outcome) +with p.open('a') as f:f.write('\n'.join(lines)+'\n') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/train.py new file mode 100644 index 0000000000000000000000000000000000000000..3cdc106980371c99d81c71d6746943c47206be83 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/train.py @@ -0,0 +1,71 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(3);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/validation_subset.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..4df83e69c4f9a3365955e5d17ffcfc0af71372b7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/patch16/validation_subset.py @@ -0,0 +1,18 @@ +"""Model-selection-only subset spanning all 97 configurations, seed 2026.""" +import sys,json,copy +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +import ts_io + +root=Path('/workspace/data/valid');out=Path('/workspace/research/valid_screen') +idx=json.loads((root/'input/index.json').read_text());new=copy.deepcopy(idx);rng=np.random.default_rng(2026) +for cfg in new['configs']: + cid=cfg['config_id'];case=ts_io.CaseFile(root/'input/cases'/f'{cid}.h5') + ids=np.sort(rng.choice(case.n,min(case.n,192),replace=False)) + ts_io.write_case_subset(case,ids,out/'input/cases'/f'{cid}.h5') + lab,se,meta=ts_io.read_truth_file(root/'truth/cases'/f'{cid}.h5') + ts_io.write_truth_file(out/'truth/cases'/f'{cid}.h5',lab[ids],se[ids],meta) + cfg['n_instances']=len(ids);case.close() +for kind in ('input','truth'):(out/kind/'index.json').write_text(json.dumps(new,indent=1)) +print('screen instances',sum(c['n_instances'] for c in new['configs'])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/postloss/check_numerical_fix.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/postloss/check_numerical_fix.py new file mode 100644 index 0000000000000000000000000000000000000000..0dd7f0b04a538020f59a4d4e8d6bc4884e0acd29 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/postloss/check_numerical_fix.py @@ -0,0 +1,26 @@ +"""Regression test for observed variance overflow in permitted training data.""" +import importlib.util +import json +from pathlib import Path +import time +import torch +from model import DirectForecaster,loss_fn + +R=Path('/workspace/research');torch.set_num_threads(1);started=time.monotonic() +spec=importlib.util.spec_from_file_location('original',Path(__file__).with_name('model_before_numerical_fix.py')) +original=importlib.util.module_from_spec(spec);spec.loader.exec_module(original) +torch.manual_seed(331);normal=torch.randn(8,512);normal[0,:200]=float('nan');normal[1]=float('nan');normal[2]=0 +old=original.DirectForecaster.standardize(normal);new=DirectForecaster.standardize(normal) +assert all(torch.equal(a,b) for a,b in zip(old,new)) +f=torch.load(R/'postloss_nonfinite_fixture.pt',map_location='cpu',weights_only=False) +indices=torch.tensor([37]);ctx=f['ctx'][indices];target=f['target'][indices];periods=f['periods'][indices] +z,valid,mu,scale=DirectForecaster.standardize(ctx) +assert torch.isfinite(z).all() and torch.isfinite(mu).all() and torch.isfinite(scale).all() +ck=torch.load(R/'horizon_delta12k.pt',map_location='cpu',weights_only=False) +m=DirectForecaster(**ck['config']).cuda();m.load_state_dict(ck['model']) +with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(m,ctx.cuda(),target.cuda(),periods.cuda(),paired=True) +loss.backward();torch.cuda.synchronize() +assert torch.isfinite(loss) and all(v.grad is not None and torch.isfinite(v.grad).all() for v in m.parameters()) +result={'ordinary_rows_bitwise_original':True,'observed_overflow_row_loss':float(loss.detach()), + 'all_gradients_finite':True,'optimizer_updates':0,'seconds':time.monotonic()-started} +(R/'postloss_numerical_fix_checks.json').write_text(json.dumps(result,indent=2));print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/postloss/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/postloss/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/postloss/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/postloss/diagnose_nonfinite.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/postloss/diagnose_nonfinite.py new file mode 100644 index 0000000000000000000000000000000000000000..770ff91d0718cbb6b947fc91fd61697ea50cbfd6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/postloss/diagnose_nonfinite.py @@ -0,0 +1,42 @@ +"""Find nonfinite fixed-transform outputs on the unchanged allowed-corpus stream.""" +import json +from pathlib import Path +import time +import numpy as np +import torch +from model import DirectForecaster +from data import Sampler +from torch_post import apply_fixed,context_statistics + +R=Path('/workspace/research');torch.set_num_threads(1);torch.manual_seed(197) +torch.backends.cuda.matmul.allow_tf32=True +ck=torch.load(R/'horizon_delta12k.pt',map_location='cpu',weights_only=False) +m=DirectForecaster(**ck['config']).cuda();m.load_state_dict(ck['model']);m.eval() +sampler=Sampler(R/'packed_sample',seed=197,source_weights_from=R/'packed_sample') +rng=np.random.default_rng(197);started=time.monotonic() +for step in range(1,251): + 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])) + arrays=sampler.sample(64,c,h);ctx,target,periods=[torch.from_numpy(v).cuda() for v in arrays] + with torch.no_grad(),torch.autocast('cuda',dtype=torch.bfloat16): + seen=torch.isfinite(target);pos=torch.arange(h,device=ctx.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + raw,mu,scale=m(torch.cat((ctx,-ctx),0),periods.repeat(2,1),h,forecast_lengths=lengths.repeat(2)) + q=(raw[:64]-raw[64:].flip(-1))*.5;mu=mu[:64];scale=scale[:64] + denormalized=q*scale[:,:,None]+mu[:,:,None] + post=apply_fixed(ctx,periods,denormalized) + bad=~torch.isfinite(post).all((1,2)) + if bad.any(): + stats=context_statistics(ctx,periods,h) + badids=torch.nonzero(bad)[:,0] + receipt={'step':step,'context':c,'horizon':h,'bad_rows':badids.tolist(), + 'raw_finite':bool(torch.isfinite(q).all()),'scale_finite':bool(torch.isfinite(scale).all()), + 'denormalized_finite':bool(torch.isfinite(denormalized).all()), + 'statistics_finite':[bool(torch.isfinite(v).all()) for v in stats], + 'bad_scale':scale[bad].tolist(),'bad_mu':mu[bad].tolist(), + 'bad_maximum_context':torch.nan_to_num(ctx[bad]).abs().max(-1).values.tolist(), + 'seconds':time.monotonic()-started,'optimizer_updates':0} + torch.save({'ctx':ctx.cpu(),'target':target.cpu(),'periods':periods.cpu(), + 'raw':denormalized.cpu(),'scale':scale.cpu(),'post':post.cpu(), + 'statistics':[v.cpu() for v in stats]},R/'postloss_nonfinite_fixture.pt') + (R/'postloss_nonfinite_diagnostic.json').write_text(json.dumps(receipt,indent=2));print(json.dumps(receipt));break +else:print(json.dumps({'no_nonfinite_fixed_parent_outputs_in_first_steps':250,'seconds':time.monotonic()-started})) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/postloss/gpu_check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/postloss/gpu_check.py new file mode 100644 index 0000000000000000000000000000000000000000..a457afa8d1dd55d2167434b70f4e1488e41e4049 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/postloss/gpu_check.py @@ -0,0 +1,24 @@ +"""Verify the new training loss at the largest scheduled bf16 shape.""" +import fcntl,json,sys,time +from pathlib import Path +import torch + +r=Path('/workspace/research');sys.path.insert(0,str(r/'postloss')) +from model import DirectForecaster,loss_fn +from data import Sampler +with open(r/'.evaluation.lock','a') as lock: + fcntl.flock(lock,fcntl.LOCK_EX) + torch.set_num_threads(1);torch.manual_seed(281);torch.backends.cuda.matmul.allow_tf32=True + started=time.monotonic() + ck=torch.load(r/'horizon_delta12k.pt',map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).cuda();model.load_state_dict(ck['model']) + x,y,p=[torch.from_numpy(a).cuda() for a in Sampler(r/'packed_sample',281).sample(64,4096,1024)] + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p,paired=True) + loss.backward();torch.cuda.synchronize() + assert torch.isfinite(loss) + assert all(v.grad is not None and torch.isfinite(v.grad).all() for v in model.parameters()) + result={'seed':281,'batch':64,'context':4096,'horizon':1024,'optimizer_updates':0, + 'loss':float(loss.detach()),'seconds':time.monotonic()-started, + 'peak_allocated_mib':torch.cuda.max_memory_allocated()/2**20, + 'peak_reserved_mib':torch.cuda.max_memory_reserved()/2**20} + (r/'postloss_gpu_check.json').write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/postloss/launch_completion.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/postloss/launch_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..8bdf1346b99ae846a2679a7494c9b88c1900bdce --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/postloss/launch_completion.py @@ -0,0 +1,30 @@ +"""Complete the original pruned schedule from its immutable exact training state.""" +def main(): + import json + import os + import subprocess + from pathlib import Path + R=Path('/workspace/research') + receipt=json.loads((R/'postloss_recovery003653.json').read_text()) + assert receipt['step']==3653 + assert json.loads((R/'postloss_completion_code_audit.json').read_text())['matches_original_E75_archived_training_code'] + assert (R/'postloss.stop').exists() + env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1') + command=['python3',str(R/'recovery/train.py'),'--code-dir',str(R/'postloss'), + '--packed',str(R/'packed_sample'),'--source-weights-from',str(R/'packed_sample'), + '--out',str(R/'runs/postloss_completion'),'--initialize-from',str(R/'horizon_delta12k.pt'), + '--resume',str(R/'postloss_recovery003653.pt'),'--steps','12000','--batch','64','--lr','.00002', + '--seed','197','--loss-mode','paired','--stop-file',str(R/'postloss_completion.stop')] + with (R/'postloss_completion_queue.log').open('w') as qlog,(R/'postloss_completion_watch.log').open('w') as wlog: + queued=subprocess.Popen(['python3',str(R/'queued_train.py'),'--label','E98 complete original E75 schedule', + '--log',str(R/'postloss_completion_train.log'),'--receipt',str(R/'postloss_completion_queue.json'), + '--wait-pid','9274','--require-checkpoint',str(R/'runs/split_patch/recovery.pt'), + '--',*command],stdout=qlog,stderr=subprocess.STDOUT,env=env) + watch=subprocess.Popen(['python3',str(R/'watch_evaluate.py'),'--run',str(R/'runs/postloss_completion'), + '--evaluator',str(R/'postloss_inference/evaluate.py'),'--name','postloss_completion', + '--steps','6000,12000'],stdout=wlog,stderr=subprocess.STDOUT,env=env) + print({'queue_pid':queued.pid,'watch_pid':watch.pid},flush=True) + result=queued.wait() + if result:watch.terminate() + watch.wait();raise SystemExit(result) +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/postloss/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/postloss/model.py new file mode 100644 index 0000000000000000000000000000000000000000..014b585df72cc69852a8eedf302320b52fe55aad --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/postloss/model.py @@ -0,0 +1,216 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + from torch_post import apply_fixed + q=apply_fixed(ctx,periods,q*scale[:,:,None]+mu[:,:,None]) + q=(q-mu[:,:,None])/scale[:,:,None] + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/postloss/model_before_numerical_fix.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/postloss/model_before_numerical_fix.py new file mode 100644 index 0000000000000000000000000000000000000000..1dab6e08582e4610693292e765d40a8b5392e97a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/postloss/model_before_numerical_fix.py @@ -0,0 +1,207 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + from torch_post import apply_fixed + q=apply_fixed(ctx,periods,q*scale[:,:,None]+mu[:,:,None]) + q=(q-mu[:,:,None])/scale[:,:,None] + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/postloss/restart.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/postloss/restart.py new file mode 100644 index 0000000000000000000000000000000000000000..fa09bf30ead55ac10ca2d8c9a55277ddd71986f7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/postloss/restart.py @@ -0,0 +1,25 @@ +"""Restart corrected E75 from the declared parent and record process compute.""" +import json +import os +from pathlib import Path +import subprocess +import time + +R=Path('/workspace/research');run=R/'runs/postloss' +receipt=json.loads((R/'postloss_queue_before_recovery2.json').read_text()) +command=receipt['command'] +assert not (run/'recovery.pt').exists(),'This script is only for the documented pre-checkpoint numerical restart.' +env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1') +with (R/'postloss_recovery3.log').open('w') as f: + p=subprocess.Popen(command,stdout=f,stderr=subprocess.STDOUT,env=env) +record={'command':command,'status':'running','pid':p.pid,'log':str(R/'postloss_recovery3.log'), + 'started_utc':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()), + 'note':'Restart own E62 initialization after verified float32 variance-overflow correction; original seed and recipe unchanged.'} +path=R/'postloss_recovery3_receipt.json';path.write_text(json.dumps(record,indent=2)) +watch=['python3',str(R/'watch_evaluate.py'),'--run',str(run),'--evaluator',str(R/'postloss_inference/evaluate.py'), + '--name','postloss','--steps','1000,3000,6000,12000'] +with (R/'postloss_watch_recovery3_fixed.log').open('w') as f: + subprocess.Popen(watch,stdout=f,stderr=subprocess.STDOUT,env=env) +started=time.monotonic();returncode=p.wait() +record.update(status='complete' if returncode==0 else 'failed',returncode=returncode,process_seconds=time.monotonic()-started) +path.write_text(json.dumps(record,indent=2));raise SystemExit(returncode) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/postloss/torch_post.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/postloss/torch_post.py new file mode 100644 index 0000000000000000000000000000000000000000..e19586bcc1677d56cedb6ce02c2f57797157f5f3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/postloss/torch_post.py @@ -0,0 +1,112 @@ +"""Differentiable forecast transforms with the package's fixed context rules. + +Context statistics are constants with respect to model parameters. Gradients +flow only through the forecast, including the continuity correction's anchor. +""" +import torch + + +@torch.no_grad() +def context_statistics(ctx, periods, horizon): + x=ctx.double(); finite=torch.isfinite(x); clean=torch.where(finite,x,0.) + b,c=x.shape; device=x.device + pos=torch.arange(c,device=device)[None,:] + count=finite.sum(-1).clamp(min=1) + mean=clean.sum(-1)/count + variance=(torch.where(finite,x-mean[:,None],0.).square()).sum(-1)/count + positive=((x>=0)|~finite).all(-1) + zeros=((x==0)&finite).sum(-1) + zero_active=positive&(zeros>=4)&(zeros/count>=.1) + cutoff=torch.where(zero_active,.4*variance.sqrt(),0.) + first=torch.where(finite,pos,c).min(-1).values + length=c-first + phase=torch.arange(max(1,c//3),device=device)[None,:] + future=torch.arange(horizon,device=device)[None,:] + z=torch.tensor([-1.2815515655,-.8416212336,-.5244005127,-.2533471031,0, + .2533471031,.5244005127,.8416212336,1.2815515655],device=device) + best_weight=torch.zeros(b,device=device,dtype=torch.float64) + prior=torch.zeros(b,horizon,9,device=device,dtype=torch.float64) + prior_valid=torch.zeros(b,horizon,device=device,dtype=torch.bool) + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + cycles=(length[:,None]//p).clamp(max=8) + history=finite&(pos>=c-cycles*p) + n=history.sum(-1).clamp(min=1) + center=(clean*history).sum(-1)/n + var=torch.where(history,x-center[:,None],0.).square().sum(-1)/n + previous=pos-p;safe=previous.clamp(min=0) + pairs=(previous>=c-cycles*p)&(previous>=0)&finite&finite.gather(1,safe) + pairs_count=pairs.sum(-1) + difference=clean-clean.gather(1,safe) + mse=(difference.square()*pairs).sum(-1)/pairs_count.clamp(min=1) + weight=(1-mse/(var+1e-12)/.25).clamp(0,.98) + eligible=(p[:,0]>=2)&(cycles[:,0]>=3)&(pairs_count>=p[:,0]) + weight=torch.where(eligible,weight,0.) + values=[];observed=[] + for cycle in range(4): + idx=c-p+phase-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(phase=0)&(cycle0 + template=(values*observed).sum(0)/nphase.clamp(min=1) + ntemplate=phase_valid.sum(-1).clamp(min=1) + template_mean=(template*phase_valid).sum(-1)/ntemplate + recent=finite&(pos>=c-p) + nr=recent.sum(-1).clamp(min=1) + recent_mean=(clean*recent).sum(-1)/nr + template=template+(recent_mean-template_mean)[:,None] + template_mean=(template*phase_valid).sum(-1)/ntemplate + recent_var=torch.where(recent,x-recent_mean[:,None],0.).square().sum(-1)/nr + template_var=((template-template_mean[:,None]).square()*phase_valid).sum(-1)/ntemplate + used_cycles=cycles[:,0].clamp(min=1,max=4) + noise=mse/2 + target_var=(recent_var-noise).clamp(min=0) + base_var=(template_var-noise/used_cycles).clamp(min=0) + ratio=(target_var/base_var.clamp(min=1e-12)).sqrt().clamp(.5,2.) + align=nr>=torch.maximum(torch.full_like(nr,2),.75*p[:,0]) + ratio=torch.where(align,ratio,1.) + template=template_mean[:,None]+(template-template_mean[:,None])*ratio[:,None] + sigma=(noise*(1+1/used_cycles)).sqrt() + index=(future%p).clamp(max=phase.shape[-1]-1) + selected=template.gather(1,index) + valid=phase_valid.gather(1,index) + q=selected[:,:,None]+sigma[:,None,None]*z[None,None,:] + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + choose=weight>best_weight + prior=torch.where(choose[:,None,None],q,prior) + prior_valid=torch.where(choose[:,None],valid,prior_valid) + best_weight=torch.maximum(best_weight,weight) + seasonal_weight=best_weight[:,None]*prior_valid + + recent=x[:,-512:];seen=torch.isfinite(recent) + n=seen.sum(-1).clamp(min=1);clean_recent=torch.where(seen,recent,0.) + center=clean_recent.sum(-1)/n + var=torch.where(seen,recent-center[:,None],0.).square().sum(-1)/n + differences=recent[:,1:]-recent[:,:-1] + diff_seen=torch.isfinite(differences);nd=diff_seen.sum(-1) + mse=torch.where(diff_seen,differences,0.).square().sum(-1)/nd.clamp(min=1) + tail=differences[:,-8:] + tail_seen=torch.isfinite(tail);nt=tail_seen.sum(-1) + sorted_tail=torch.where(tail_seen,tail,float('inf')).sort(-1).values + if tail.shape[-1]: + lo=((nt-1).clamp(min=0)//2)[:,None];hi=(nt//2).clamp(max=tail.shape[-1]-1)[:,None] + median=(sorted_tail.gather(1,lo)+sorted_tail.gather(1,hi))[:,0]/2 + else:median=torch.zeros(b,device=device,dtype=x.dtype) + continuity_weight=(1-mse/(var+1e-12)/.5).clamp(0,.95) + active=(nd>=8)&(nt>0)&seen[:,-1] + continuity_weight=torch.where(active,continuity_weight,0.) + anchor=torch.where(active,recent[:,-1]+median,0.) + return seasonal_weight,prior,continuity_weight,anchor,positive,cutoff + + +def apply_fixed(ctx,periods,quant): + """Quantiles are raw-scale tensors of shape (batch,horizon,9).""" + weight,prior,cweight,anchor,positive,cutoff=context_statistics(ctx,periods,quant.shape[1]) + q=torch.where(positive[:,None,None],quant.clamp(min=0),quant) + q=((1-weight[:,:,None])*q+weight[:,:,None]*prior).float() + bias=(cweight*(anchor-q[:,0,4])).float() + decay=torch.exp(-torch.arange(q.shape[1],device=q.device,dtype=torch.float64)/24) + q=(q.double()+bias[:,None,None]*decay[None,:,None]).float() + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return torch.where((q>=0)&(q8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recency_features/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recency_features/model.py new file mode 100644 index 0000000000000000000000000000000000000000..f8271c5b0bf9a5edb961e1c7839761fe50a2e40b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recency_features/model.py @@ -0,0 +1,171 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024,recency_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + if self.recency is not None: + pos=torch.arange(c,device=z.device)[None,:];extras=[] + for j in range(2): + period=periods[:,j:j+1] + recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recency_features/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recency_features/train.py new file mode 100644 index 0000000000000000000000000000000000000000..3bfb8b90f1a6656881b7598f864becaa737a76f4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recency_features/train.py @@ -0,0 +1,73 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(3);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/brief.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/brief.py new file mode 100644 index 0000000000000000000000000000000000000000..7f06e7c2e8fcd4ce31d08d936fa5018cf00dc855 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/brief.py @@ -0,0 +1,34 @@ +"""Write a short, current recovery handoff; never modify training state.""" +import datetime +import json +from pathlib import Path + +R = Path('/workspace/research') +s = json.loads((R/'CURRENT_RESEARCH_STATE.json').read_text()) +lines = ['# Current recovery brief', '', datetime.datetime.now(datetime.timezone.utc).isoformat(), '', + 'Continuous research; no endpoint/final hand-in. One H10080GB,22CPUs,224GiB requested RAM; no network or pretrained assets. Do not inspect credentials or spawn agents.', '', + '## Published', '', json.dumps(s['published']), '', '## Pending selection', '', + json.dumps(s.get('next_candidate',{})), '', json.dumps({k:v for k,v in s.get('selection_probes',{}).items() if k in ['E128','E130','E132','E133','E134','E135','E136','E137','E138','E139','E140','E141','E142']}), '', '## Active and queued training', ''] +for name, job in s.get('external_jobs',{}).items(): + if job['status'] not in ['running','waiting']: + continue + lines += [f'- {name}: {job["status"]}; receipt {job["receipt"]}; queue PID snapshot {job["queue_pid_at_snapshot"]}; children {job["child_pids_at_snapshot"]}.', + f' Last logged record: {json.dumps(job["last_phase_record"])}', + f' Complete recovery: {job["complete_recovery_checkpoint"]}; latest EMA: {job["latest_saved_ema"]}.'] +lines += ['', '## Recovery rules', '', + '- PIDs and launch-script dependencies are snapshots. After an operator restart, restore running jobs from each complete recovery.pt, preserving optimizer/EMA/RNG/prefetched batch and original schedules. Rewire waiting jobs to the newly launched dependency PIDs; do not blindly rerun old launch scripts.', + '- Waiting dependency chain: weekly_replication_control after long_seasonal; weekly_replication_candidate after that control; lowfreq_windows after that candidate; long_seasonal_replication after lowfreq_windows. phase_joint waits for random_capacity_512 final96000; seasonal_dispersion waits for phase_joint final12000; seasonal_history waits for seasonal_dispersion final12000. random_capacity_original_ar waits for random_capacity_1024 final96000; log_horizon waits for long_seasonal_replication final12000; seasonal_width waits for seasonal_history final12000; random_capacity_long_seasonal waits for both E94halfLR and E79wide final96000 and replaces only the E94allocation. visibility_curriculum waits for E110full and E79wide final96000 and replaces only the E110allocation; preserve --visibility-curriculum on any resume. direct_trend_head waits for E129seasonal_width final12000 and replaces that allocation. random_capacity_deep waits for E122originalAR and E79wide final96000, replacing only the E122allocation.', + '- E121 history-aware ensemble runtime is prepared at history_three_patch_ensemble; synthetic audit checks exact standalone composition and ordinary legacy equality. It also applies member finite cleanup before averaging, correcting a pre-existing extreme-value discrepancy. Use this separate publisher and complete public replay before any E121 publication; E130 now publishes four members using four_member_ensemble/publish.py, retaining both finite cleanup and per-member history support. Use that publisher for four-member packages.', + '- E126 compiled_teacher_trial completed its mandatory17000stop; do not resume it. It preserved original96000 LR schedule from immutable distill_ensemble_recovery016000.pt. Original E101 stays active. Compiler takeover rejected: max cutoff drift0.001964 exceeded0.0005 tolerance, with only3to5percent warm shared-device timing gain. No coefficient change selected. E125 component ablations completed; both paths help. E127 finite-member numerical fix is published with all97predictions bitwise unchanged; do not republish it. E128 dispersion transfers6000 and12000 both lost full validation; neither is published. E130 equal-quarter package is the current best. E132 checks scheduled E79wide96000 as the fourth member; E133 passed both source replication gates but its fixed averaged correction failed the ensemble gate (2of4positive, mean-0.0000154271); no full replay or averaging sweep. Receipts are indexed in CURRENT_RESEARCH_STATE.json.', + '- E138 learned gate uses immutable /workspace/research/gating_experts_E130, descriptorfa97880d..., even if submission improves. CPU/GPU/recovery/publicruntime/relocation audits passed; queued after E123final12000. Check queue receipt and rewire dependencies after restart. Training must preserve --gate-package and restore complete optimizer/EMA/RNG/prefetched batch. No expert tensors enter the gate optimizer. Gate publisher is ensemble_gate/publish.py. E139width primary6k is published at0.3843356309048914 after allfour diagnostics/fullsuite/bitwisecomposition;12k requires matched-source gate. E140separate loader-only candidate passed six-run syntheticidentity and45percent shared-device median loadreduction; full97bitwiseidentity/relocation pending, notpublished. Gate trainer/experts loader unchanged. E132final fourthmember andE142width6+final quartet both passeddiagnostics; assemble(kind fresh/joint) onlyafter E140runtime decision, then fullreplay andcomposition. E141matched146Mpatch16/patch8 continuations seed809/B32/LR2e-5/12k passed CPU/GPUaudits, queued29105control afterE13626926final12000 then29107candidate aftercontrolfinal12000. Same random_capacity model/data code, candidate folded ownE79wide96checkpoint. Preserve fullrecovery/compiledloss andsequentialdependency after restart. Use seasonal_width_transfer/promote.py only after better full replay and all checks.', + '- E101 distillation teacher is immutable /workspace/research/distill_teacher_E96, even after later publications. Do not substitute the current submission.', + '- Restore compiler_cache_backup to the same /tmp cache paths before restarting compiled trainers. Exact environment and commands are in CURRENT_RESEARCH_STATE.json.', + '- E105 output collision is documented in incidents/stratified_volume_output_collision. Correct E105 output is runs/stratified_volume. E95final and2k..12k weights survive, but E95optimizer recovery and original1k weights were lost. Do not resume completed E95.', + '- All previous negative/stopped branches stay stopped unless a new matched experiment explicitly revisits them. Never retrain the supplied baselines.', + '- Current training-source publisher archives all Python modules from explicitly declared directories, fixing earlier omissions of spectral.py and schedules.py. Complete-source members carry a -complete suffix when rebuilt. Runtime/weight hashes were unchanged.', + '- Full evaluation and GPU diagnostics use .evaluation.lock; the six main trainers share the one H100. The bounded E126 seventh-process probe completed17000 and should remain stopped. Dataset windows under data/valid and all earlier cutoffs are selection only, never training.', + '- Master journal direct_v1/EXPERIMENTS.md, chronological SESSION_20261023_PROGRESS.md, and RESEARCH_IDEAS.md contain decisions and rejected candidates. Recheck live processes and latest reports before acting.', + '', '## Time anchor', '', + 'Latest operator recovery allowance:151596research seconds at2026-10-23T02:45:51UTC. Pauses/preflight excluded. The goal remains active and has no requested token budget.', ''] +(R/'RECOVERY_BRIEF.md').write_text('\n'.join(lines)) +print('Wrote RECOVERY_BRIEF.md with '+str(sum(j['status'] in ['running','waiting'] for j in s.get('external_jobs',{}).values()))+' active/queued jobs.') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/capacity_curves.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/capacity_curves.py new file mode 100644 index 0000000000000000000000000000000000000000..c89a28a84243dc16ae52a1215c182a00f15dbc4e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/capacity_curves.py @@ -0,0 +1,50 @@ +"""Summarize completed validation checkpoints and measured shared-GPU training time.""" +import csv +import json +import time +from pathlib import Path + +R = Path('/workspace/research') +started = time.monotonic() +names = ['random_capacity_512', 'random_capacity_1024', 'random_capacity_1024_halflr', + 'random_capacity_full', 'distill_ensemble', 'random_capacity_512_anneal'] +rows = [] +for name in names: + log = R/(name+'_train.log') + records = {} + if log.exists(): + for line in log.read_text().splitlines(): + try: + item = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(item,dict) and 'step' in item and 'seconds' in item: + records[item['step']] = item + config_path = R/'runs'/name/'config.json' + config = json.loads(config_path.read_text()) if config_path.exists() else {} + for report in sorted((R/'evals').glob(name+'_ema*/report.json')): + result = json.loads(report.read_text()) + step = int(report.parent.name.rsplit('ema',1)[1]) + if result['n_failed']: + continue + record = records.get(step,{}) + rows.append(dict(run=name,step=step,parameters=config.get('parameters'), + seed=config.get('seed'),batch=config.get('batch'),learning_rate=config.get('lr'), + packed=config.get('packed'),skill=result['skill_score'], + rel_mase=result['rel_mase_gmean'],rel_wql=result['rel_wql_gmean'], + checkpoint_sha256=result['checkpoint_sha256'], + training_phase_loop_seconds=record.get('seconds'), + evaluation_seconds=result.get('eval_seconds'),report=str(report))) +rows.sort(key=lambda item:(names.index(item['run']),item['step'])) +output = dict(generated_utc=time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()), + note='Validation selection only. Time is logged process wall on the shared single H100, not isolated GPU time. The cooldown arm starts from the same saved24000state; its phase clock resets. No missing log time is inferred.', + rows=rows,analysis_seconds=time.monotonic()-started,no_training_or_new_inference=True) +(R/'capacity_learning_curves.json').write_text(json.dumps(output,indent=2)) +with (R/'capacity_learning_curves.csv').open('w',newline='') as handle: + writer = csv.DictWriter(handle,fieldnames=list(rows[0]) if rows else ['run']) + writer.writeheader() + writer.writerows(rows) +for name in names: + selected = [r for r in rows if r['run']==name] + if selected: + print(json.dumps(selected[-1])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/exposure_audit.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/exposure_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..fb67738bc9ed77f87173feda2430365e66c75966 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/exposure_audit.py @@ -0,0 +1,46 @@ +"""Describe sampled observation exposure and training invested in selected ancestry.""" +import json +import sys +import time +from pathlib import Path +import numpy as np + +R=Path('/workspace/research') +sys.path.insert(0,str(R/'random_capacity')) +from data import Sampler + +started=time.monotonic() +seed=521 +sampler=Sampler(R/'packed_sample',seed=seed,source_weights_from=R/'packed_sample') +rng=np.random.default_rng(seed) +rows=context_points=target_points=0 +for _ in range(320): + 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])) + x,y,p=sampler.sample(64,c,h) + rows+=len(x) + context_points+=int(np.isfinite(x).sum()) + target_points+=int(np.isfinite(y).sum()) +manifest=json.loads(Path('/workspace/submission/model_manifest.json').read_text()) +runs={} +for item in manifest['training_lineage']: + path=Path(item['checkpoint']) + batch=item.get('training_settings',{}).get('batch') + if path.parts[0]!='runs' or not batch: + continue + run=path.parts[1] + step=item.get('step',0) + if step>runs.get(run,{}).get('step',0): + runs[run]=dict(step=step,batch=batch,rows=step*batch,checkpoint=item['checkpoint']) +ancestral_rows=sum(v['rows'] for v in runs.values()) +mean_points=(context_points+target_points)/rows +result=dict(seed=seed,seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False, + sampled_rows=rows,mean_finite_context_points=context_points/rows, + mean_finite_target_points=target_points/rows,mean_finite_points=mean_points, + selected_descriptor=manifest['checkpoint_sha256'],ancestral_runs=runs, + selected_ancestral_rows_before_sign_pairing=ancestral_rows, + fresh96000_batch48_rows=96000*48, + fresh96000_batch48_gross_observation_presentations_estimate=96000*48*mean_points, + note='Gross sampled presentations include overlapping/resampled windows and synthetic values, not unique observations. Ancestral run maxima count compute invested in different branches, including subtracted controls; they are not an equivalent single-model training trajectory. Sign pairing duplicates compute but not distinct sampled rows. No future training recipe is inferred from this audit alone.') +(R/'training_exposure_audit.json').write_text(json.dumps(result,indent=2)) +print(json.dumps({k:v for k,v in result.items() if k!='ancestral_runs'})) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/launch_matched_cutoffs.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/launch_matched_cutoffs.py new file mode 100644 index 0000000000000000000000000000000000000000..6d33e64b8212b250fc38a2990604c80228b94c80 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/launch_matched_cutoffs.py @@ -0,0 +1,14 @@ +"""Keep evaluation controllers alive for the declared queued comparisons.""" +from pathlib import Path +import datetime,json,os,subprocess +R=Path('/workspace/research');jobs={};processes={};env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1') +for name,control,runtime,label in [('lowfreq_windows','overflow_control','postloss_inference','E113'),('seasonal_history','long_seasonal','seasonal_history_inference','E121'),('seasonal_width','seasonal_dispersion','seasonal_width_inference','E129'),('long_seasonal_replication','weekly_replication_control','long_seasonal_inference','E118'),('log_horizon','overflow_control','postloss_inference','E123')]: + path=R/(name+'_matched_cutoffs.log') + with path.open('a') as log: + command=['python3',str(R/'recovery/watch_matched_cutoffs.py'),'--run',name,'--control',control,'--evaluator',str(R/runtime/'evaluate.py'),'--label',label] + p=subprocess.Popen(command,stdout=log,stderr=subprocess.STDOUT,env=env) + processes[label]=p;jobs[label]=dict(pid=p.pid,parent_pid=os.getpid(),command=command,log=str(path),receipt=str(R/(name+'_matched_cutoffs_receipt.json'))) +q=R/'CURRENT_RESEARCH_STATE.json';state=json.loads(q.read_text());state['diagnostics']['matched_cutoff_controllers']=jobs;t=q.with_suffix('.tmp');t.write_text(json.dumps(state,indent=2));os.replace(t,q) +print(json.dumps(jobs),flush=True) +for label,p in processes.items(): + result=p.wait();print(json.dumps(dict(label=label,returncode=result)),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/matched_report.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/matched_report.py new file mode 100644 index 0000000000000000000000000000000000000000..f7755cfc0300a5a18f3e2db1d6d5aa89cda9f0fa --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/matched_report.py @@ -0,0 +1,16 @@ +"""Record matched validation reports, including all configuration-group metrics.""" +import argparse,datetime,json,math +from pathlib import Path +R=Path('/workspace/research');ap=argparse.ArgumentParser() +for key in ['candidate','control','label','out']:ap.add_argument('--'+key,required=True) +ap.add_argument('--cutoffs',default='0');ap.add_argument('--outcome',required=True);a=ap.parse_args() +folders=['evals','backcast_evals','backcast2_evals','backcast3_evals'];rows=[] +for index in map(int,a.cutoffs.split(',')): + folder=folders[index];x=json.loads((R/folder/a.candidate/'report.json').read_text());y=json.loads((R/folder/a.control/'report.json').read_text()) + assert x['n_failed']==y['n_failed']==0 and x['n_configs']==y['n_configs'] + delta={g:{k:math.sqrt(y['groups'][g][k]['rel_mase_gmean']*y['groups'][g][k]['rel_wql_gmean'])-math.sqrt(v['rel_mase_gmean']*v['rel_wql_gmean']) for k,v in entries.items()} for g,entries in x['groups'].items()} + rows.append(dict(cutoff=folder,candidate_skill=x['skill_score'],control_skill=y['skill_score'],delta=x['skill_score']-y['skill_score'],candidate_checkpoint=x['checkpoint_sha256'],control_checkpoint=y['checkpoint_sha256'],candidate_eval_seconds=x.get('eval_seconds'),candidate_groups=x['groups'],control_groups=y['groups'],group_skill_delta=delta)) +result=dict(label=a.label,utc=datetime.datetime.now(datetime.timezone.utc).isoformat(),candidate=a.candidate,control=a.control,rows=rows,mean_delta=sum(v['delta'] for v in rows)/len(rows),positive_cutoffs=sum(v['delta']>0 for v in rows),outcome=a.outcome) +p=Path(a.out);assert not p.exists(),'Refuse duplicate comparison record';p.write_text(json.dumps(result,indent=2)) +with (R/'direct_v1/EXPERIMENTS.md').open('a') as f:f.write('\n'+a.label+': '+json.dumps(result)+'\n') +print(json.dumps({k:v for k,v in result.items() if k!='rows'})) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/median_error_structure.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/median_error_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..83bb24d13841f0266d0947799c682f47e8641474 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/median_error_structure.py @@ -0,0 +1,30 @@ +"""Describe validation median errors without fitting or proposing corrected forecasts.""" +import argparse,json,sys,time +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +from ts_io import read_prediction_file,read_truth_file +ap=argparse.ArgumentParser() +for n in ['valid','pred','report','out']:ap.add_argument('--'+n,required=True) +a=ap.parse_args();start=time.monotonic();root=Path(a.valid);report=json.loads(Path(a.report).read_text());rows=[] +for cfg in report['configs']: + cid=cfg['config_id'];y,scale,_=read_truth_file(root/'truth/cases'/(cid+'.h5'));_,q=read_prediction_file(Path(a.pred)/'cases'/(cid+'.h5')) + good=np.isfinite(scale)&(scale>0);valid=np.isfinite(y)&good[...,None];safe=np.where(good,scale,1).astype(np.float64) + err=np.where(valid,(q[:,:,4,:].astype(np.float64)-y.astype(np.float64))/safe[...,None],0.) + n=valid.sum(-1);total=int(n.sum());mae=float(np.abs(err).sum()/total) + signed=float(err.sum()/total);absolute_window_mean=float(np.abs(err.sum(-1)).sum()/total) + assert absolute_window_mean<=mae+1e-10 + lead=[] + for positions in np.array_split(np.arange(y.shape[-1]),4): + mask=valid[...,positions];count=int(mask.sum());values=err[...,positions] + lead.append(dict(count=count,mase=float(np.abs(values).sum()/count),signed_scaled_error=float(values.sum()/count))) + rows.append(dict(config_id=cid,term=cfg['term'],domain=cfg['domain'],frequency=cfg['freq'],horizon=cfg['prediction_length'],mase=mae,scorer_mase=cfg['metrics']['mase'],signed_scaled_error=signed,absolute_window_mean_error=absolute_window_mean,window_mean_error_fraction_of_mae=absolute_window_mean/max(mae,1e-30),lead_quarters=lead)) + assert abs(mae-cfg['metrics']['mase'])<1e-6*max(1,mae) +groups={} +for key in ['term','domain','frequency']: + groups[key]={} + for value in sorted({row[key] for row in rows}): + selected=[row for row in rows if row[key]==value] + groups[key][value]=dict(configs=len(selected),mean_window_mean_error_fraction=float(np.mean([row['window_mean_error_fraction_of_mae'] for row in selected])),mean_signed_error_over_mae=float(np.mean([row['signed_scaled_error']/max(row['mase'],1e-30) for row in selected])),mean_lead_quarter_mase_ratio=[float(np.mean([row['lead_quarters'][i]['mase']/max(row['mase'],1e-30) for row in selected])) for i in range(4)]) +result=dict(checkpoint_sha256=report['checkpoint_sha256'],groups=groups,configs=rows,seconds=time.monotonic()-start,optimizer_updates=0,new_inference=False,note='Validation-only descriptive analysis. Absolute per-window mean error is a Jensen lower bound on MAE, not a recoverable correction or attributable causal component. Groups average configurations equally; lead ratios are descriptive, not the benchmark metric. No parameter fitting or forecast modification.') +Path(a.out).write_text(json.dumps(result,indent=2));print(json.dumps({k:v for k,v in result.items() if k!='configs'})) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/pack_composition.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/pack_composition.py new file mode 100644 index 0000000000000000000000000000000000000000..0a023de983f7c0860043b58def56406e3fd27eb9 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/pack_composition.py @@ -0,0 +1,32 @@ +"""Read-only comparison of source/length composition in the two allowed packs.""" +import json,time +from pathlib import Path +import numpy as np +R=Path('/workspace/research');started=time.monotonic();old=R/'packed_sample';new=R/'packed_stratified_full' +a=json.loads((old/'meta.json').read_text());b=json.loads((new/'meta.json').read_text());assert a['dirs']==b['dirs'];names=a['dirs'] +weights=[] +for n in names: + w=min((old/(n+'.bin')).stat().st_size//4,20000000)**.25 + if n.startswith(('era5_','cmip6_')):w*=.35 + if n.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) +weights=np.array(weights)/sum(weights);bins=np.array([16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131073]) +rows=[];aggregate={k:np.zeros(len(bins)-1) for k in ['old','full']} +for n,w in zip(names,weights): + row={'source':n,'conditional_real_source_probability':float(w)} + for k,root in [('old',old),('full',new)]: + lengths=np.diff(np.load(root/(n+'.offsets.npy'),mmap_mode='r')) + hist=np.histogram(lengths,bins=bins)[0]/len(lengths);aggregate[k]+=w*hist + row[k]={'series':len(lengths),'points':int(lengths.sum()),'mean_length':float(lengths.mean()),'median_length':float(np.median(lengths)), + 'fraction_below64':float(np.mean(lengths<64)),'fraction_below256':float(np.mean(lengths<256)), + 'fraction_at_least20480':float(np.mean(lengths>=20480)),'length_bin_probabilities':hist.tolist()} + row['weighted_length_distribution_l1']=float(w*np.abs(np.array(row['old']['length_bin_probabilities'])-row['full']['length_bin_probabilities']).sum()) + row['mixed_frequency_rows_in_full']=b['receipts'][n]['mixed_frequency_rows_in_candidates'];row['full_frequencies']=b['receipts'][n]['kept_frequencies'];rows.append(row) +result=dict(kind='per-source uniform-series sampling composition; no series values or validation labels read', + length_bins=bins.tolist(),conditional_real_length_bin_probabilities={k:v.tolist() for k,v in aggregate.items()}, + source_probabilities_unchanged=True,min_length_both=16,max_crop_length_both=131072, + mixed_frequency_sources=[r['source'] for r in rows if r['mixed_frequency_rows_in_full']],sources=rows, + seconds=time.monotonic()-started,optimizer_updates=0) +(R/'pack_composition_comparison.json').write_text(json.dumps(result,indent=2)) +print(json.dumps({k:v for k,v in result.items() if k!='sources'})) +for row in sorted(rows,key=lambda r:-r['weighted_length_distribution_l1'])[:12]:print(json.dumps({k:v for k,v in row.items() if k not in ['old','full']},separators=(',',':')), 'mean_length',row['old']['mean_length'],row['full']['mean_length']) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/quantile_coverage.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/quantile_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..d7f4958ae772a15c4a580eed59bb9257b065154d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/quantile_coverage.py @@ -0,0 +1,59 @@ +"""Validation-only quantile coverage, with separate strict/inclusive coverage at atoms.""" +import argparse +import json +import sys +import time +from pathlib import Path + +import numpy as np + +sys.path.insert(0,'/workspace/evaluation') +from ts_io import read_prediction_file, read_truth_file + +parser = argparse.ArgumentParser() +parser.add_argument('--valid',required=True) +parser.add_argument('--pred',required=True) +parser.add_argument('--report',required=True) +parser.add_argument('--out',required=True) +args = parser.parse_args() +started = time.monotonic() +root = Path(args.valid) +index = json.loads((root/'input/index.json').read_text()) +report = json.loads(Path(args.report).read_text()) +levels = np.arange(1,10)/10 +rows = [] +for cfg in index['configs']: + relative = Path('cases')/(cfg['config_id']+'.h5') + y,scale,_ = read_truth_file(root/'truth'/relative) + _,q = read_prediction_file(Path(args.pred)/relative) + valid = np.isfinite(y) + assert q.shape==(*y.shape[:2],9,y.shape[-1]) and np.isfinite(q).all() + count = int(valid.sum()) + assert count>0 + strict = ((y[:,:,None,:] anneal_from_step + assert 0 < anneal_final_lr <= anneal_from_lr + progress=max(0.,min(1.,(step-anneal_from_step)/(steps-anneal_from_step))) + return anneal_final_lr+.5*(anneal_from_lr-anneal_final_lr)*(1+math.cos(math.pi*progress)) + warm_step=step-reset_at if reset_at>=0 and step>reset_at else step + return peak*min(1,warm_step/400)*(.2+.4*(1+math.cos(math.pi*step/steps))) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/seasonal_history_support.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/seasonal_history_support.py new file mode 100644 index 0000000000000000000000000000000000000000..84314b30b22a4a761447fc5ee1cffb9301e725b9 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/seasonal_history_support.py @@ -0,0 +1,23 @@ +"""Context-metadata diagnostic of potential 8-cycle support, with no targets read.""" +import importlib.util,json,time +from pathlib import Path +import h5py,numpy as np +R=Path('/workspace/research');started=time.monotonic() +spec=importlib.util.spec_from_file_location('support_model',R/'long_seasonal/model.py');m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m) +root=Path('/workspace/data/valid/input');index=json.loads((root/'index.json').read_text());rows=[] +for cfg in index['configs']: + with h5py.File(root/'cases'/(cfg['config_id']+'.h5'),'r') as f:lengths=np.asarray(f['context_length']) + h=cfg['prediction_length'];periods=m.periods_for_freq(cfg['freq']);row={k:cfg[k] for k in ['config_id','freq','term','domain']};row['periods']=periods;row['n_instances']=len(lengths) + for cap in [4096,16384]: + support=[];cycles=[] + for p in periods: + count=np.clip(1+(np.minimum(lengths,cap)[:,None]-p+np.arange(h)[None,:]%p)//p,0,16) + support.append(float(np.mean((count>=8)&(p>=2))));cycles.append(float(np.mean(np.where(p>=2,count,0)))) + row[str(cap)]={'phase_support_fraction':support,'mean_available_cycles':cycles} + row['support_gain_sum']=sum(row['16384']['phase_support_fraction'])-sum(row['4096']['phase_support_fraction']);rows.append(row) +changed=[r for r in rows if r['support_gain_sum']>0] +result=dict(kind='optimistic potential support before missing-value masks; not measured forecast improvement',input_metadata_only=True,validation_targets_read=False,optimizer_updates=0,configs=rows, + changed_configurations=len(changed),changed_domains=sorted(set(r['domain'] for r in changed)),seconds=time.monotonic()-started) +(R/'seasonal_history_support.json').write_text(json.dumps(result,indent=2)) +print(json.dumps({k:v for k,v in result.items() if k!='configs'})) +for r in sorted(changed,key=lambda x:x['support_gain_sum'],reverse=True)[:20]:print(json.dumps(r)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/snapshot.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/snapshot.py new file mode 100644 index 0000000000000000000000000000000000000000..9e28a9c484f4afe4e605e8ffd7a53d25831b1d87 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/snapshot.py @@ -0,0 +1,99 @@ +"""Write a compact authoritative research recovery index without touching training state.""" +import datetime +import json +import os +from pathlib import Path + +R=Path('/workspace/research');p=R/'CURRENT_RESEARCH_STATE.json' +s=json.loads(p.read_text()) +s['snapshot_utc']=datetime.datetime.now(datetime.timezone.utc).isoformat() +receipt=json.loads((R/'recovery3_launch_receipt.json').read_text()) +s['runs']={} +for name,job in receipt['jobs'].items(): + run=R/'runs'/name + log=Path(job['log']) + records=[] + for line in log.read_text().splitlines(): + try: + record=json.loads(line) + if 'step' in record or 'completed_step' in record:records.append(record) + except json.JSONDecodeError:pass + s['runs'][name]={'config':json.loads((run/'config.json').read_text()) if (run/'config.json').exists() else None, + 'last_phase_record':records[-1] if records else None, + 'phase_log':str(log),'supervisor_receipt':str(R/'recovery3_launch_receipt.json'), + 'latest_saved_ema':str(max(run.glob('ema*.pt'))) if list(run.glob('ema*.pt')) else None, + 'complete_recovery_checkpoint':str(run/'recovery.pt') if (run/'recovery.pt').exists() else None, + 'pid_at_snapshot':job['pid'],'returncode':job.get('returncode'), + 'note':'Check actual live process and checkpoint state before resuming; this is only a snapshot.'} +s['queues']={name:{'status':q['status'],'dependency':q['dependency'],'command':q['command'], + 'required_checkpoints':q['required_checkpoints']} + for name,q in receipt['queues'].items()} +s.pop('prepared_not_launched',None) +s['deferred_unqueued']={'E72':'temporal_mixup, prepared and checked but not queued','ideas':'RESEARCH_IDEAS.md, no jobs attached'} +s['completed_since_previous_recovery']={ + 'E67_control12000':{'skill':.37724286394256845,'training_loop_seconds':2794.8358458959847}, + 'E67_paired12000':{'skill':.377427077277383,'training_loop_seconds':2794.867385860998}, + 'E63_expanded146M':'Stopped8501, complete recovery retained; allocation moved to E73; inconclusive data scaling', + 'E61_slowAR':'Complete12000; E76 used6000 correction, final transfer rejected', + 'E65_recent_normalization':'Complete12000; E81 equal ensemble rejected', + 'E58_small_control':'Complete32000', + 'E58_wide146M':'Complete32000; no gain over37Mcontrol; do not resume', + 'E71_patch8':'Complete12000; selected6000 used in E87/E96/E102 ensembles', + 'E69_volatility':'Complete12000; final below matched control; no transfer', + 'E89_patch8_control':'Complete12000; final0.380847096,loop2729.052105s; selected starting E71parent remains stronger', + 'E89_fullpatch4':'Complete12000,main0.381640078; E96 used6000, E103final cached alternative mixed; loop5066.016522s', + 'E93_split_patch':'Complete12000,main0.381711986; selected final is E102 published thirdmember; loop3153.565149s', + 'E92_robust_normalization':'Complete12000,final0.377099312 belowcontrol; rejected;E97started', + 'E90_metric_scale':'Complete12000; final0.377373344 ties/slightly trailsE80; no selection; loop2702.166704s', + 'E84_coarse':'Complete12000; daily gain but weekly regression; not selected', + 'E88_late_patch8_slowAR':'Complete12000; small9k gain lost atfinal; rejected', + 'E80_overflow':'Complete12000; finaltiesoriginal; selected3k compositeE91rejected', + 'E78_multiscaleAR':'Complete12000; no gain over single slowAR', + 'E86_protected_graft':'Complete8000; below own initialization; no publication', + 'E75_postloss':'Stopped3653 deliberately; immutable snapshot retained; E98 separately declared completion active in another output, original stopfile remains', + 'E73_independent_graft':'Stopped8683 after negative8000; replaced by E86; stopfile remains', + 'E95_stratified_corpus':'Complete12000,final0.377983250,earliermixed; E105collision destroyed only1000weights and optimizer recovery;2k..12k preserved; do not resume', + 'E97_weekly_synth':'Complete12000,final0.380439539; E112final weekly correction now published; loop2600.472750s', + 'E105_stratified_volume':'Complete12000,final0.377529200,earlier0.336713522/0.359535697/0.390349158 mixed; corrected continuationloop2013.982814s plus original incident phase', + 'E106_spectral_synth':'Complete12000,final0.377641399,earlier0.337647555/0.361626447/0.385497870, average matched gap negligible; loop2206.272278s; E114fixed6000transfers in selection', + 'E98_postloss_completion':'Complete12000,final0.376034254 below3000 andcontrol; rejected,loop1995.386513s', + 'E99_early_cooldown':'Complete36000,final0.363306598 trails original36k0.364859034; rejected,loop1603.635706s', + 'E77_pairedslowAR':'Complete12000;6000 strongest main/earlier comparison'} +s['external_receipts']=[str(R/'postloss_recovery3_receipt.json'),str(R/'random_capacity_512_queue.json'),str(R/'random_capacity_1024_queue.json'),str(R/'multiscale_ar_queue.json'),str(R/'overflow_control_queue.json'),str(R/'coarse_aggregate_queue.json'),str(R/'patch8_long_memory_queue.json'),str(R/'wide_graft_frozen_queue.json'),str(R/'patch4_candidate_queue.json'),str(R/'patch4_control_queue.json'),str(R/'metric_scale_queue.json'),str(R/'robust_normalization_queue.json'),str(R/'split_patch_queue.json'),str(R/'random_capacity_1024_halflr_queue.json'),str(R/'stratified_corpus_queue.json'),str(R/'weekly_synth_queue.json'),str(R/'postloss_completion_queue.json'),str(R/'random_capacity_512_anneal_queue.json'),str(R/'distill_ensemble_queue.json'),str(R/'stratified_volume_queue.json'),str(R/'spectral_synth_queue.json'),str(R/'long_seasonal_queue.json'),str(R/'random_capacity_full_queue.json'),str(R/'weekly_replication_control_queue.json'),str(R/'weekly_replication_candidate_queue.json'),str(R/'lowfreq_windows_queue.json'),str(R/'phase_joint_queue.json'),str(R/'long_seasonal_replication_queue.json'),str(R/'seasonal_dispersion_queue.json'),str(R/'seasonal_history_queue.json'),str(R/'random_capacity_original_ar_queue.json'),str(R/'log_horizon_queue.json'),str(R/'compiled_teacher_trial_queue.json'),str(R/'seasonal_width_queue.json'),str(R/'random_capacity_long_seasonal_queue.json'),str(R/'visibility_curriculum_queue.json'),str(R/'direct_trend_head_queue.json'),str(R/'random_capacity_deep_queue.json'),str(R/'ensemble_gate_queue.json'),str(R/'capacity_patch8_control_queue.json'),str(R/'capacity_patch8_candidate_queue.json')] +queue_pids={'random_capacity_512_queue.json':965,'random_capacity_1024_queue.json':967, + 'multiscale_ar_queue.json':1678,'overflow_control_queue.json':1676, + 'coarse_aggregate_queue.json':3086,'patch8_long_memory_queue.json':3739, + 'wide_graft_frozen_queue.json':3931,'patch4_candidate_queue.json':4078, + 'patch4_control_queue.json':4080} +s['external_jobs']={} +for receipt_name in s['external_receipts']: + receipt_path=Path(receipt_name) + if not receipt_path.exists():continue + item=json.loads(receipt_path.read_text());command=item.get('command',[]) + if '--out' not in command:continue + run=Path(command[command.index('--out')+1]);log=Path(item.get('log',str(receipt_path).replace('_queue.json','_train.log'))) + last=None + if log.exists(): + for line in log.read_text().splitlines(): + try: + record=json.loads(line) + if isinstance(record,dict) and ('step' in record or 'completed_step' in record):last=record + except json.JSONDecodeError:pass + queue_pid=item.get('launcher_pid',queue_pids.get(receipt_path.name)) + children_file=Path(f'/proc/{queue_pid}/task/{queue_pid}/children') if queue_pid else None + children=list(map(int,children_file.read_text().split())) if children_file and children_file.exists() else [] + checkpoints=list(run.glob('ema*.pt')) + s['external_jobs'][run.name]={'receipt':str(receipt_path),'status':item.get('status'), + 'queue_pid_at_snapshot':queue_pid,'child_pids_at_snapshot':children, + 'last_phase_record':last,'log':str(log), + 'latest_saved_ema':str(max(checkpoints)) if checkpoints else None, + 'complete_recovery_checkpoint':str(run/'recovery.pt') if (run/'recovery.pt').exists() else None, + 'command':command,'note':'PIDs are only a snapshot; check actual processes and serialized state before recovery.'} +s['compiler_environment']={'OPENBLAS_NUM_THREADS':'1','OMP_NUM_THREADS':'1','TORCHINDUCTOR_COMPILE_THREADS':'2','MAX_JOBS':'2','PYTHONPATH':str(R/'compiler_support'),'TRITON_CACHE_MANAGER':'sibling_cache:SiblingFileCacheManager','TRITON_CACHE_DIR':'/tmp/timeseries-triton-cache','TORCHINDUCTOR_CACHE_DIR':'/tmp/timeseries-inductor-cache'} +for job in s['external_jobs'].values(): + job['environment']=s['compiler_environment'] if '--compile-loss' in job['command'] else {'OPENBLAS_NUM_THREADS':'1','OMP_NUM_THREADS':'1'} +s['compiler_cache_backup']=str(R/'compiler_cache_backup') +for stale in ['pending','pending_actions','active_experiments','next_experiments','prepared_experiments']: + s.pop(stale,None) +tmp=p.with_suffix('.tmp');tmp.write_text(json.dumps(s,indent=2));os.replace(tmp,p) +print(s['snapshot_utc']) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/synthetic_window_audit.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/synthetic_window_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..5a6455bbd9926f9d342ee1a24ca825328a9e7e1f --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/synthetic_window_audit.py @@ -0,0 +1,63 @@ +"""Compare actual allowed/synthetic training-window dynamics without validation data.""" +import datetime +import json +from pathlib import Path +import sys +import time +import types +import numpy as np + +R=Path('/workspace/research') +sys.path.insert(0,str(R/'overflow_control')) +source=(R/'overflow_control/data.py').read_text() +needle='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)' +assert source.count(needle)==1 +instrumented=source.replace(needle,needle+';self.audit_synthetic=np.zeros(batch,bool)') +needle='if r.random()=16 and len(target)>=4: + k=min(16,n//4,len(target)) + # Descriptive finite-observation means, not a proposed inference feature. + scale=max(float(np.std(values)),float(np.mean(np.abs(values)))*1e-4,1e-4) + past=(float(np.mean(values[-k:]))-float(np.mean(values[-2*k:-k])))/scale + future=(float(np.mean(target[:k].astype(np.float64)))-float(np.mean(values[-k:])))/scale + item.update(past_change=float(np.clip(past,-20,20)),future_change=float(np.clip(future,-20,20))) + groups.setdefault(frequency+'_'+kind,[]).append(item);counts+=1 +summary={} +for name,rows in groups.items(): + c=np.array([x['context'] for x in rows]);h=np.array([x['target'] for x in rows]) + valid=[x for x in rows if x['past_change'] is not None] + past=np.array([x['past_change'] for x in valid]);future=np.array([x['future_change'] for x in valid]) + summary[name]=dict(rows=len(rows),median_finite_context=float(np.median(c)), + context_at_most128=float(np.mean(c<=128)),context_above512=float(np.mean(c>512)), + median_finite_target=float(np.median(h)),dynamic_rows=len(valid), + median_abs_recent_change=float(np.median(np.abs(past))), + median_abs_future_change=float(np.median(np.abs(future))), + recent_future_change_correlation=float(np.corrcoef(past,future)[0,1])) +result=dict(seed=seed,rows=counts,batches=160,groups=summary,seconds=time.monotonic()-started, + generated_utc=datetime.datetime.now(datetime.timezone.utc).isoformat(), + instrumentation_first640_rows_and_rng_bitwise=True,optimizer_updates=0, + validation_data_read=False,decision='Descriptive audit only. E113 remains unchanged; no new generator selected.') +(R/'synthetic_window_audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/train.py new file mode 100644 index 0000000000000000000000000000000000000000..6c435174dc1783fe2151c4a2df9093074a38a317 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/train.py @@ -0,0 +1,257 @@ +"""Resumable continuation of our existing permitted-corpus experiments.""" +import argparse,copy,fcntl,inspect,json,math,os,sys,time +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import numpy as np +import torch + +ap=argparse.ArgumentParser() +ap.add_argument('--code-dir',required=True);ap.add_argument('--packed',required=True) +ap.add_argument('--source-weights-from');ap.add_argument('--out',required=True) +ap.add_argument('--initialize-from',required=True);ap.add_argument('--initialize-ema') +ap.add_argument('--start-step',type=int,default=0);ap.add_argument('--resume') +ap.add_argument('--steps',type=int,required=True);ap.add_argument('--batch',type=int,required=True) +ap.add_argument('--lr',type=float,required=True);ap.add_argument('--seed',type=int,required=True) +ap.add_argument('--context',type=int);ap.add_argument('--sample-context',type=int,default=4096) +ap.add_argument('--save-every',type=int,default=1000);ap.add_argument('--stop-file') +ap.add_argument('--recovery-every',type=int,default=250) +ap.add_argument('--halt-after',type=int) +ap.add_argument('--loss-mode',choices=['individual','paired']) +ap.add_argument('--compile-loss',action='store_true') +ap.add_argument('--reset-at',type=int,default=-1);ap.add_argument('--reset-seed',type=int,default=179) +ap.add_argument('--anneal-from-step',type=int);ap.add_argument('--anneal-from-lr',type=float) +ap.add_argument('--anneal-final-lr',type=float) +ap.add_argument('--teacher-package');ap.add_argument('--teacher-coefficient',type=float) +ap.add_argument('--compile-teacher',action='store_true') +ap.add_argument('--visibility-curriculum',action='store_true') +ap.add_argument('--gate-package') +a=ap.parse_args() +# Hold a process-lifetime lock before loading a model or touching GPU state. +_run_out=Path(a.out);_run_out.mkdir(parents=True,exist_ok=True) +_run_lock=open(_run_out/'.training.lock','a') +try:fcntl.flock(_run_lock,fcntl.LOCK_EX|fcntl.LOCK_NB) +except BlockingIOError:raise SystemExit('Another trainer already owns this output directory: '+str(_run_out)) +if not a.resume: + _saved=list(_run_out.glob('ema*.pt'))+list(_run_out.glob('step*.pt')) + if (_run_out/'recovery.pt').exists():_saved.append(_run_out/'recovery.pt') + if _saved: + raise SystemExit('Refusing fresh training into an output with saved checkpoints; use a new directory or explicit --resume: '+str(_run_out)) +sys.path.insert(0,a.code_dir) +from model import DirectForecaster,loss_fn +from data import Sampler +from schedules import learning_rate +torch.set_num_threads(2);torch.manual_seed(a.seed);torch.backends.cuda.matmul.allow_tf32=True +out=Path(a.out);out.mkdir(parents=True,exist_ok=True);a.trainable_scope='all' +if Path(a.code_dir).name in ('long_memory_synth','paired_long_memory','multiscale_ar','random_capacity','patch8_long_memory','distill_ensemble','random_capacity_long_seasonal','visibility_curriculum','random_capacity_deep'):a.synthetic_ar_time_constants=[1,10000] +if Path(a.code_dir).name in ('full_paired','patch8','temporal_mixup','postloss','paired_long_memory','multiscale_ar','random_capacity','overflow_control','coarse_aggregate','patch8_long_memory','patch4','metric_scale','robust_normalization','split_patch','weekly_synth','distill_ensemble'):a.requested_horizon_seed=a.seed+300003 +if Path(a.code_dir).name=='multiscale_ar': + a.synthetic_ar_components=4;a.multiscale_ar_seed=a.seed+700003 +if Path(a.code_dir).name=='volatility_synth':a.stochastic_volatility_seed=a.seed+500003 +if Path(a.code_dir).name=='coarse_aggregate': + a.coarse_aggregation_seed=a.seed+900003;a.coarse_aggregation_probability=.2;a.coarse_aggregation_frequencies=['D','W'] +if Path(a.code_dir).name=='temporal_mixup':a.temporal_mixup_seed=a.seed+600003 +if Path(a.code_dir).name=='postloss': + a.fixed_postprocessing_loss=True;a.normalization_overflow_fallback=True +if Path(a.code_dir).name in ('overflow_control','metric_scale','random_capacity','weekly_synth','distill_ensemble'):a.normalization_overflow_fallback=True +if Path(a.code_dir).name=='weekly_synth': + a.weekly_synthetic_seed=a.seed+1000003;a.weekly_replacement_probability=1/11 +if Path(a.code_dir).name=='spectral_synth': + a.spectral_synthetic_seed=a.seed+1100003;a.spectral_replacement_probability=.5 + a.spectral_length_scale=[1,10000];a.spectral_families=['Matern0.5','Matern1.5','Matern2.5','RBF'] + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True +if Path(a.code_dir).name in ('long_seasonal','phase_joint','seasonal_dispersion','seasonal_history','seasonal_width','direct_trend_head','random_capacity_long_seasonal','visibility_curriculum','random_capacity_deep','ensemble_gate'): + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True +if Path(a.code_dir).name=='random_capacity_original_ar': + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True + a.synthetic_ar_coefficient_law='uniform(0.2,0.995), original generator; unchanged AR branch probability and asymptotic variance scaling' +if Path(a.code_dir).name=='log_horizon': + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True + a.requested_horizon_law='half full; half geometric quantile remap of the original uniform integer endpoint draw from min(16,max(1,H//4)) to H, then patch16 rounding; identical RNG consumption' +if Path(a.code_dir).name=='seasonal_history': + a.learned_seasonal_history_context=16384;a.recent_encoder_and_rule_context=4096 + a.history_extension_rule='extend originally full4096 real contexts before the same cutoff, preserving original recent contexts, targets, aggregation, sampler RNG and horizon RNG; synthetic extra prefix missing' +if Path(a.code_dir).name in ('lowfreq_windows','lowfreq_age'): + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True + a.lowfreq_window_seed=a.seed+1200003;a.lowfreq_window_probability=.5 + a.lowfreq_window_rule='period2=1,period1<=52;finite-target endpoint;log-uniform horizon4..min(H,max(8,2p),span-8) with available-length fallback;context cap min(C,max(64,32p));at least4finite history' +if Path(a.code_dir).name=='lowfreq_age': + a.synthetic_generation_origin='For successfully shortened selected low-frequency synthetic rows only, use the first nc+nh observations of the same generated path, split at nc; unchanged masks, lengths, periods, real/unselected rows and all RNG streams; no regeneration or extra draws' +if Path(a.code_dir).name=='metric_scale':a.loss_seasonality='lag1 for exact daily[7,365] and weekly[52,1] period pairs; unchanged otherwise' +if Path(a.code_dir).name=='robust_normalization':a.normalization_kind='finite median plus/minus6 mean absolute deviations winsorized mean/RMS, float64; original normalized history clipped30' +if Path(a.code_dir).name=='wide_graft_frozen':a.trainable_scope='new feature stream and cross-stream blocks; inherited parameter blocks frozen' +if a.visibility_curriculum: + assert Path(a.code_dir).name=='visibility_curriculum' and not a.teacher_package and not a.gate_package + from visibility import visible_batch + a.visibility_curriculum_rule='steps1..16000:lastC/4,firstmax(16,H/4);16001..32000:lastC/2,firstmax(16,H/2);32001..96000:unchanged; sample/prefetch full original windows and crop only current loss arrays' +ck=torch.load(a.resume or a.initialize_from,map_location='cpu',weights_only=False) +# Keep immutable branch ancestry across a later restart from this run's own recovery. +lineage_parents=list(ck.get('parent_checkpoints',[])) +if a.initialize_ema:lineage_parents.append(a.initialize_ema) +if a.resume and Path(a.resume).parent.resolve()!=out.resolve():lineage_parents.append(a.resume) +previous_args=ck.get('args',{}) +previous_resume=previous_args.get('resume') +if previous_resume and Path(previous_resume).parent.resolve()!=Path(previous_args.get('out',a.out)).resolve(): + lineage_parents.append(previous_resume) +lineage_parents=list(dict.fromkeys(lineage_parents)) +config=dict(ck['config']) +if a.context:config['max_context']=a.context +model=DirectForecaster(**config).cuda();model.load_state_dict(ck['model']) +teacher=None;teacher_predict=None;experts=None +if Path(a.code_dir).name=='distill_ensemble': + assert a.teacher_package and a.teacher_coefficient is not None +if a.teacher_package: + assert Path(a.code_dir).name=='distill_ensemble' + from teacher import OwnEnsembleTeacher + with torch.random.fork_rng(devices=[torch.cuda.current_device()]): + teacher=OwnEnsembleTeacher(a.teacher_package) + if ck.get('args',{}).get('teacher_descriptor_sha256'): + assert ck['args']['teacher_descriptor_sha256']==teacher.descriptor_sha256 + assert ck['args']['teacher_coefficient']==a.teacher_coefficient + a.teacher_descriptor_sha256=teacher.descriptor_sha256 + a.teacher_checkpoint_sha256=teacher.member_hashes + a.teacher_target_kind='equal average of own frozen E96 raw normalized sign-paired neural quantiles, before postprocessing' + teacher_predict=teacher + if a.compile_teacher: + torch._dynamo.config.recompile_limit=64 + teacher_predict=torch.compile(teacher.__call__,fullgraph=True,dynamic=False) +else: + assert not a.compile_teacher, '--compile-teacher requires a declared own-model teacher' + +if Path(a.code_dir).name=='ensemble_gate':assert a.gate_package and a.loss_mode=='paired' +if a.gate_package: + assert Path(a.code_dir).name=='ensemble_gate' and not a.teacher_package and not a.compile_loss + from experts import FrozenExperts + from model import FEATURE_NAMES + torch.backends.cuda.matmul.allow_tf32=False + with torch.random.fork_rng(devices=[torch.cuda.current_device()]): + experts=FrozenExperts(a.gate_package) + if ck.get('args',{}).get('fixed_expert_descriptor_sha256'): + assert ck['args']['fixed_expert_descriptor_sha256']==experts.descriptor_sha256 + assert ck['args']['fixed_expert_checkpoint_sha256']==experts.member_hashes + a.fixed_expert_descriptor_sha256=experts.descriptor_sha256 + a.fixed_expert_checkpoint_sha256=experts.member_hashes + a.expert_forecast_kind='four own frozen E130 raw-scale final forecasts, including exact packaged per-member transformations' + a.gate_weight_rule='0.125+0.5*softmax; same positive per-lead weight across all quantiles' + a.gate_features=FEATURE_NAMES + a.trainable_scope='6340 gate parameters only; four experts frozen and excluded from optimizer and EMA' + a.fixed_postprocessing_loss=True + a.gate_precision='FP32 gate, BF16 frozen experts, TF32 disabled' + assert sum(p.numel() for p in model.parameters())==6340 + +protector=None +if Path(a.code_dir).name=='wide_graft_frozen': + from frozen import FreezeInherited + protector=FreezeInherited(model) + a.protected_parameters=protector.inherited_numel +if a.compile_loss: + torch._dynamo.config.recompile_limit=64 + objective=torch.compile(loss_fn,fullgraph=True,dynamic=False) +else:objective=loss_fn +multipliers=ck.get('lr_multipliers',{}) +def optimizer(): + groups=[] + for mult in sorted(set(multipliers.values())|{1.}): + params=[p for n,p in model.named_parameters() if multipliers.get(n,1.)==mult] + if params:groups.append({'params':params,'lr':a.lr*mult,'lr_multiplier':mult,'weight_decay':.05/mult}) + return torch.optim.AdamW(groups,betas=(.9,.95),fused=True) +opt=optimizer() +if a.resume: + start_step=ck['step'];opt.load_state_dict(ck['optimizer']) + ema={k:v.cuda() for k,v in ck['ema_state'].items()} +else: + start_step=a.start_step + ema_ck=torch.load(a.initialize_ema,map_location='cpu',weights_only=False) if a.initialize_ema else ck + ema={k:v.cuda().clone() for k,v in ema_ck['model'].items()} +del ck +def make_sampler(seed): + kwargs={'seed':seed} + if 'source_weights_from' in inspect.signature(Sampler).parameters:kwargs['source_weights_from']=a.source_weights_from + return Sampler(a.packed,**kwargs),np.random.default_rng(seed) +stream_seed=a.reset_seed if a.reset_at>=0 and start_step>=a.reset_at else a.seed +sampler,rng=make_sampler(stream_seed) +def next_batch(): + c=int(rng.choice([512,1024,2048,a.sample_context],p=[.1,.15,.35,.4])) + h=int(rng.choice([32,128,512,1024],p=[.1,.2,.2,.5])) + x,y,p=sampler.sample(a.batch,c,h) + return x[:,-model.max_context:].copy(),y,p +pool=ThreadPoolExecutor(1) +if a.resume: + recovery=torch.load(a.resume,map_location='cpu',weights_only=False) + rng.bit_generator.state=recovery['batch_rng_state'];sampler.rng.bit_generator.state=recovery['sampler_rng_state'] + for name,state in recovery.get('sampler_rng_states',{}).items():getattr(sampler,name).bit_generator.state=state + torch.set_rng_state(recovery['torch_rng_state']);torch.cuda.set_rng_state_all(recovery['cuda_rng_state']) + pending=recovery['prefetched_batch'];del recovery + future=pool.submit(lambda:pending) +else:future=pool.submit(next_batch) +parameters=sum(p.numel() for p in model.parameters()) +(out/'config.json').write_text(json.dumps({**vars(a),'model':model.config,'parameters':parameters},indent=2)) +print(json.dumps({'parameters':parameters,'starting_step':start_step,'stream_seed':stream_seed,'restored_complete_training_state':bool(a.resume)}),flush=True) +started=time.monotonic();losses=[] +def atomic_save(obj,path): + torch.save(obj,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) +def save(step,include_selection_weights=True): + global future + pending_batch=future.result() + common={'config':model.config,'step':step,'args':vars(a),'lr_multipliers':multipliers, + 'parent_checkpoints':list(dict.fromkeys(lineage_parents+(teacher.checkpoints if teacher else [])+(experts.checkpoints if experts else [])))} + if include_selection_weights: + for prefix,state in [('step',model.state_dict()),('ema',ema)]: + atomic_save({**common,'model':state,'ema':prefix=='ema'},out/f'{prefix}{step:06d}.pt') + atomic_save({**common,'model':model.state_dict(),'optimizer':opt.state_dict(),'ema_state':ema, + 'prefetched_batch':pending_batch,'batch_rng_state':copy.deepcopy(rng.bit_generator.state), + 'sampler_rng_state':copy.deepcopy(sampler.rng.bit_generator.state), + 'sampler_rng_states':{name:copy.deepcopy(value.bit_generator.state) for name,value in vars(sampler).items() if isinstance(value,np.random.Generator)}, + 'torch_rng_state':torch.get_rng_state(),'cuda_rng_state':torch.cuda.get_rng_state_all()},out/'recovery.pt') + future=pool.submit(lambda:pending_batch) +for step in range(start_step+1,a.steps+1): + if a.reset_at>=0 and step==a.reset_at+1 and start_step=a.halt_after) + selection_checkpoint=step%a.save_every==0 or step==a.steps or stop + # Persist a complete state before a fresh/resumed job warms its remaining compiled shapes. + if selection_checkpoint or step%a.recovery_every==0 or step==start_step+1: + save(step,include_selection_weights=selection_checkpoint) + if stop:break +pool.shutdown() +print(json.dumps({'completed_step':step,'training_process_loop_seconds':time.monotonic()-started}),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/watch_matched_cutoffs.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/watch_matched_cutoffs.py new file mode 100644 index 0000000000000000000000000000000000000000..3bd2f95022f87dbe1c349575c0ec77662a2d4d6e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/recovery/watch_matched_cutoffs.py @@ -0,0 +1,34 @@ +"""Complete declared primary/durability comparisons; never select a model automatically.""" +import argparse,datetime,json,os,subprocess,time +from pathlib import Path +R=Path('/workspace/research');ap=argparse.ArgumentParser() +for key in ['run','control','evaluator','label']:ap.add_argument('--'+key,required=True) +ap.add_argument('--control-evaluator');ap.add_argument('--steps',default='6000,12000');a=ap.parse_args();start=time.monotonic() +receipt=R/(a.run+'_matched_cutoffs_receipt.json') +state=dict(pid=os.getpid(),status='running',run=a.run,control=a.control,steps=[],started_utc=datetime.datetime.now(datetime.timezone.utc).isoformat()) +def save(): + state['seconds']=time.monotonic()-start;tmp=receipt.with_suffix('.tmp');tmp.write_text(json.dumps(state,indent=2));os.replace(tmp,receipt) +def call(label,command): + state['status']=label;save();t=time.monotonic();result=subprocess.run(command);state['steps'].append(dict(label=label,returncode=result.returncode,seconds=time.monotonic()-t));save() + if result.returncode:state['status']='failed';save();raise SystemExit(result.returncode) +for step in map(int,a.steps.split(',')): + name=a.run+'_ema'+str(step);report=R/'evals'/name/'report.json';state['status']='waiting for main'+str(step);save() + while not report.exists(): + queue=R/(a.run+'_queue.json') + if queue.exists() and json.loads(queue.read_text()).get('status')=='failed':state['status']='training failed';save();raise SystemExit(1) + time.sleep(3) + time.sleep(1) + call('earlier cutoffs'+str(step),['python3',str(R/'evaluate_cutoffs.py'),'--name',name,'--weights',str(R/'runs'/a.run/f'ema{step:06d}.pt'),'--evaluator',a.evaluator,'--cutoffs','1,2,3']) + control_name=a.control+'_ema'+str(step) + if any(not (R/folder/control_name/'report.json').exists() for folder in ['evals','backcast_evals','backcast2_evals','backcast3_evals']): + assert a.control_evaluator,'Missing matched control reports; pass --control-evaluator for their declared evaluation' + call('control cutoffs'+str(step),['python3',str(R/'evaluate_cutoffs.py'),'--name',control_name,'--weights',str(R/'runs'/a.control/f'ema{step:06d}.pt'),'--evaluator',a.control_evaluator]) + out=R/(a.run+str(step//1000)+'k_four_cutoff_comparison.json') + if out.exists(): + cached=json.loads(out.read_text());assert cached['candidate']==name and cached['control']==a.control+'_ema'+str(step) and len(cached['rows'])==4 + for row,folder in zip(cached['rows'],['evals','backcast_evals','backcast2_evals','backcast3_evals']): + assert row['candidate_checkpoint']==json.loads((R/folder/name/'report.json').read_text())['checkpoint_sha256'] + assert row['control_checkpoint']==json.loads((R/folder/(a.control+'_ema'+str(step))/'report.json').read_text())['checkpoint_sha256'] + state['steps'].append(dict(label='reused verified matched comparison'+str(step),returncode=0,seconds=0));save();continue + call('matched comparison'+str(step),['python3',str(R/'recovery/matched_report.py'),'--candidate',name,'--control',a.control+'_ema'+str(step),'--label',a.label+' '+str(step)+' four-cutoff comparison','--cutoffs','0,1,2,3','--out',str(out),'--outcome',f'Declared comparison checkpoints {a.steps}. No transfer formula or automatic publication is selected by this controller.']) +state['status']='complete; research review required';save();print(json.dumps(state),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_dispersion/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_dispersion/check.py new file mode 100644 index 0000000000000000000000000000000000000000..c18b58905262b5ac8df12ab86f2f03e5ce285356 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_dispersion/check.py @@ -0,0 +1,101 @@ +"""E119 exact initialization and independent seasonal dispersion arithmetic.""" +import argparse +import hashlib +import importlib.util +import json +import sys +import time +from pathlib import Path +import numpy as np +import torch + +R=Path('/workspace/research') +sys.path.insert(0,str(R/'seasonal_dispersion')) +from model import DirectForecaster,centered_seasonal_difference,loss_fn +from data import Sampler +ap=argparse.ArgumentParser();ap.add_argument('--gpu',action='store_true');a=ap.parse_args() +torch.set_num_threads(2);torch.manual_seed(577);started=time.monotonic() +spec=importlib.util.spec_from_file_location('dispersion_control',R/'long_seasonal/model.py') +code=importlib.util.module_from_spec(spec);spec.loader.exec_module(code) +parent_path=R/'long_seasonal_initial.pt';parent=torch.load(parent_path,map_location='cpu',weights_only=False) +config=dict(parent['config'],seasonal_dispersion_features=True) +candidate=DirectForecaster(**config) +missing,unexpected=candidate.load_state_dict(parent['model'],strict=False) +assert missing==['dispersion_query.weight'] and not unexpected +assert torch.count_nonzero(candidate.dispersion_query.weight)==0 +assert all(torch.equal(v,candidate.state_dict()[k]) for k,v in parent['model'].items()) +assert all(p.requires_grad for p in candidate.parameters()) +control=code.DirectForecaster(**parent['config']);control.load_state_dict(parent['model']) +assert (R/'seasonal_dispersion/data.py').read_bytes()==(R/'long_seasonal/data.py').read_bytes() + +if a.gpu: + import fcntl + lock=open(R/'.evaluation.lock','a');fcntl.flock(lock,fcntl.LOCK_EX) + torch.backends.cuda.matmul.allow_tf32=False + candidate,control=candidate.cuda(),control.cuda() + rng=np.random.default_rng(587) + ctx=torch.tensor(rng.normal(size=(8,512)).astype(np.float32),device='cuda');ctx[0,:23]=float('nan');ctx[1]=0 + periods=torch.tensor([[24,168],[7,365],[12,1],[52,1],[4,1],[1,1],[96,672],[2,14]],device='cuda') + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16): + expected=control(ctx,periods,128);actual=candidate(ctx,periods,128) + assert all(torch.equal(v,w) for v,w in zip(expected,actual)) + del control,ctx,periods,expected,actual + torch.cuda.empty_cache();torch.cuda.reset_peak_memory_stats() + sampler=Sampler(R/'packed_sample',seed=587,source_weights_from=R/'packed_sample') + tensors=[torch.from_numpy(v).cuda() for v in sampler.sample(64,4096,1024)] + placeholders=[torch.zeros_like(p) for p in candidate.parameters() for _ in range(3)] + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(candidate,*tensors,paired=True) + loss.backward();assert torch.isfinite(loss) + assert all(p.grad is not None and torch.isfinite(p.grad).all() for p in candidate.parameters()) + keys=['dispersion_query.weight','long_query.weight','long_head.weight','head.weight'] + gradients={k:float(dict(candidate.named_parameters())[k].grad.norm()) for k in keys} + assert all(v>0 for v in gradients.values()) + result=dict(seed=587,gpu_initial_function_bitwise_equal=True,max_shape=[64,4096,1024], + loss=float(loss.detach()),selected_gradient_norms=gradients,all_parameters_trainable=True, + reserved_mib=torch.cuda.max_memory_reserved()/2**20,allocated_mib=torch.cuda.max_memory_allocated()/2**20, + includes_ema_and_adam_placeholders=True,seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False) + (R/'seasonal_dispersion_gpu_checks.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));raise SystemExit() + +rng=np.random.default_rng(577) +z=rng.normal(size=(6,128)).astype(np.float32);valid=rng.random(z.shape)>.12 +valid[4]=False;z[5]=0;z[~valid]=0 +periods=np.array([[4,7],[2,3],[12,1],[24,168],[4,8],[4,8]],dtype=np.int64) +delta,extra,dispersion=centered_seasonal_difference(torch.from_numpy(z),torch.from_numpy(valid),torch.from_numpy(periods),29) +old_delta,old_extra=code.centered_seasonal_difference(torch.from_numpy(z),torch.from_numpy(valid),torch.from_numpy(periods),29) +assert torch.equal(delta,old_delta) and torch.equal(extra,old_extra) +expected=np.zeros((6,29,4),dtype=np.float32) +for row in range(6): + for j,period in enumerate(periods[row]): + for t in range(29): + observations,recent=[],[] + for cycle in range(16): + end=max(0,128-cycle*period);start=max(0,128-(cycle+1)*period) + index=128-period+t%period-cycle*period + if index<0 or not valid[row,index]:continue + centered=float(z[row,index])-z[row,start:end][valid[row,start:end]].mean(dtype=np.float64) + observations.append(centered) + if cycle<4:recent.append(centered) + if period>=2 and len(observations)>=8 and len(recent)>=2: + expected[row,t,2*j]=np.log1p(np.std(recent,ddof=1)) + expected[row,t,2*j+1]=np.log1p(np.std(observations,ddof=1)) +assert np.max(np.abs(dispersion.numpy()-expected))<1e-6 +assert torch.isfinite(dispersion).all() and torch.count_nonzero(dispersion[4:])==0 +z0=torch.tensor(rng.normal(size=(1,64)).astype(np.float32));offsets=torch.tensor(rng.normal(size=(1,16,1)).astype(np.float32)) +z1=(z0.view(1,16,4)+offsets).view(1,64);p=torch.tensor([[4,4]]);ones=torch.ones_like(z0,dtype=torch.bool) +v0=centered_seasonal_difference(z0,ones,p,16)[2];v1=centered_seasonal_difference(z1,ones,p,16)[2] +assert torch.max(torch.abs(v0-v1))<1e-6 +for c,h in [(32,6),(128,29),(512,128)]: + ctx=torch.tensor(rng.normal(size=(6,c)).astype(np.float32));ctx[0,:c//3]=float('nan');ctx[1]=0;ctx[2]=float('nan') + with torch.inference_mode():expected=control(ctx,torch.from_numpy(periods),h);actual=candidate(ctx,torch.from_numpy(periods),h) + assert all(torch.equal(v,w) for v,w in zip(expected,actual)) +out=R/'seasonal_dispersion_initial.pt';assert not out.exists() +checkpoint=dict(model=candidate.state_dict(),config=config,step=0,args=dict(packed=str(R/'packed_sample'),seed=577), + parent_checkpoints=[str(parent_path)],conversion=dict(method='zero-initialized phase-specific cycle-centered standard-deviation query', + parent_sha256=hashlib.sha256(parent_path.read_bytes()).hexdigest(),initial_function_bitwise_equal=True)) +torch.save(checkpoint,out) +result=dict(seed=577,independent_feature_arithmetic=True,centered_cycle_offset_invariance=True, + old_features_bitwise_equal=True,initial_function_bitwise_equal=True,inherited_weights_bitwise_equal=True, + all_parameters_trainable=True,sampler_byte_identical=True,added_parameters=candidate.dispersion_query.weight.numel(), + total_parameters=sum(p.numel() for p in candidate.parameters()),checkpoint_sha256=hashlib.sha256(out.read_bytes()).hexdigest(), + seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False) +(R/'seasonal_dispersion_checks.json').write_text(json.dumps(result,indent=2));print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_dispersion/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_dispersion/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_dispersion/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_dispersion/durability.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_dispersion/durability.py new file mode 100644 index 0000000000000000000000000000000000000000..41afa5f1fbc5794764bfee688e8e0ae52d2b82e3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_dispersion/durability.py @@ -0,0 +1,20 @@ +"""E119 final durability and the predeclared conditional E128 transfer12000.""" +import json,os,subprocess,time +from pathlib import Path +R=Path('/workspace/research');start=time.monotonic();receipt=R/'seasonal_dispersion_durability_receipt.json' +state=dict(pid=os.getpid(),status='waiting for final12000 main report',steps=[]) +def save(): + state['seconds']=time.monotonic()-start;tmp=receipt.with_suffix('.tmp');tmp.write_text(json.dumps(state,indent=2));os.replace(tmp,receipt) +def call(label,command): + state['status']=label;save();t=time.monotonic();subprocess.run(command,check=True);state['steps'].append(dict(label=label,seconds=time.monotonic()-t));save() +save() +while not (R/'evals/seasonal_dispersion_ema12000/report.json').exists():time.sleep(3) +time.sleep(1) +call('earlier final cutoffs',['python3',str(R/'evaluate_cutoffs.py'),'--name','seasonal_dispersion_ema12000','--weights',str(R/'runs/seasonal_dispersion/ema012000.pt'),'--evaluator',str(R/'seasonal_dispersion_inference/evaluate.py'),'--cutoffs','1,2,3']) +call('matched final comparison',['python3',str(R/'recovery/matched_report.py'),'--candidate','seasonal_dispersion_ema12000','--control','long_seasonal_ema12000','--label','E119 dispersion12000 durability','--cutoffs','0,1,2,3','--out',str(R/'seasonal_dispersion12k_comparison.json'),'--outcome','Predeclared E12812000 transfer requires at least3of4 positive and positive mean; no coefficient selection.']) +result=json.loads((R/'seasonal_dispersion12k_comparison.json').read_text());state['matched_gate_passed']=result['positive_cutoffs']>=3 and result['mean_delta']>0;save() +if not state['matched_gate_passed']: + state['status']='complete; matched gate failed, no12000 transfer';save();raise SystemExit() +call('fixed matched merge12000',['python3',str(R/'seasonal_dispersion_transfer/merge.py'),'--base',str(R/'long_seasonal_transfer12k.pt'),'--candidate',str(R/'runs/seasonal_dispersion/ema012000.pt'),'--control',str(R/'runs/long_seasonal/ema012000.pt'),'--out',str(R/'seasonal_dispersion_transfer12k.pt')]) +call('fixed12000 standalone and ensemble diagnostics',['python3',str(R/'seasonal_dispersion_transfer/run12.py')]) +state['status']='complete; review ensemble gate';save();print(json.dumps(state),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_dispersion/launch.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_dispersion/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..4d8da258bf409fff7e3f5f62fa820bf333e9a2f7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_dispersion/launch.py @@ -0,0 +1,42 @@ +"""Queue E119 after the jointly trained phase-feature comparison finishes.""" +def main(): + import json + import os + import subprocess + from pathlib import Path + R = Path('/workspace/research') + checks = json.loads((R/'seasonal_dispersion_checks.json').read_text()) + gpu = json.loads((R/'seasonal_dispersion_gpu_checks.json').read_text()) + assert checks['initial_function_bitwise_equal'] and checks['sampler_byte_identical'] + assert checks['independent_feature_arithmetic'] and checks['all_parameters_trainable'] + assert gpu['gpu_initial_function_bitwise_equal'] and gpu['all_parameters_trainable'] + assert gpu['optimizer_updates'] == 0 and not gpu['validation_data_read'] + name = 'seasonal_dispersion' + run = R/'runs'/name + packed = R/'packed_sample' + env = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1') + command = ['python3', str(R/'recovery/train.py'), '--code-dir', str(R/name), + '--packed', str(packed), '--source-weights-from', str(packed), '--out', str(run), + '--initialize-from', str(R/'seasonal_dispersion_initial.pt'), '--steps', '12000', + '--batch', '64', '--lr', '.00002', '--seed', '197', '--loss-mode', 'paired', + '--stop-file', str(R/(name+'.stop'))] + assert command[command.index('--out')+1] == str(run) + with (R/(name+'_queue.log')).open('w') as qlog, (R/(name+'_watch.log')).open('w') as wlog: + queued = subprocess.Popen(['python3',str(R/'queued_train.py'), + '--label','E119 learned phase-specific dispersion seed197', + '--log',str(R/(name+'_train.log')),'--receipt',str(R/(name+'_queue.json')), + '--wait-pid','16340','--require-checkpoint',str(R/'runs/phase_joint/ema012000.pt'), + '--',*command], stdout=qlog,stderr=subprocess.STDOUT,env=env) + watch = subprocess.Popen(['python3',str(R/'watch_evaluate.py'),'--run',str(run), + '--evaluator',str(R/'seasonal_dispersion_inference/evaluate.py'),'--name',name, + '--expected-packed',str(packed),'--steps','1000,3000,6000,12000'], + stdout=wlog,stderr=subprocess.STDOUT,env=env) + print(json.dumps({'queue_pid':queued.pid,'watch_pid':watch.pid}),flush=True) + result = queued.wait() + if result: + watch.terminate() + watch.wait() + raise SystemExit(result) + +if __name__ == '__main__': + main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_dispersion/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_dispersion/model.py new file mode 100644 index 0000000000000000000000000000000000000000..79839282b194492635d02db0867c0db60200ee03 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_dispersion/model.py @@ -0,0 +1,268 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + + +def centered_seasonal_difference(z, valid, periods, horizon): + b, c = z.shape + time = torch.arange(horizon, device=z.device)[None, :] + sums = F.pad((z * valid).cumsum(-1), (1, 0)) + counts = F.pad(valid.float().cumsum(-1), (1, 0)) + deltas, extras, dispersion = [], [], [] + for j in range(2): + period = periods[:, j:j+1].clamp(min=1) + anchor = c - period + time % period + centered, masks = [], [] + for cycle in range(16): + end = (c - cycle * period).clamp(min=0, max=c) + start = (c - (cycle + 1) * period).clamp(min=0, max=c) + count = counts.gather(1, end) - counts.gather(1, start) + mean = (sums.gather(1, end) - sums.gather(1, start)) / count.clamp(min=1) + index = anchor - cycle * period + safe = index.clamp(min=0, max=c-1) + present = (index >= 0) & valid.gather(1, safe) + centered.append(z.gather(1, safe) - mean) + masks.append(present) + values = torch.stack(centered) + seen = torch.stack(masks) + n4 = seen[:4].sum(0) + n16 = seen.sum(0) + mean4 = (values[:4] * seen[:4]).sum(0) / n4.clamp(min=1) + mean16 = (values * seen).sum(0) / n16.clamp(min=1) + active = (period >= 2) & (n4 >= 2) & (n16 >= 8) + delta = torch.where(active, mean16 - mean4, 0.) + support = torch.where(active, n16.float() / 16, 0.) + deltas.append(delta) + extras.extend([delta, support]) + variance4 = (((values[:4] - mean4).square() * seen[:4]).sum(0) / (n4 - 1).clamp(min=1)) + variance16 = (((values - mean16).square() * seen).sum(0) / (n16 - 1).clamp(min=1)) + dispersion.extend([torch.where(active, variance4.sqrt().log1p(), 0.), + torch.where(active, variance16.sqrt().log1p(), 0.)]) + return torch.stack(deltas, -1), torch.stack(extras, -1), torch.stack(dispersion, -1) + + + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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,long_seasonal_features=True,seasonal_dispersion_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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,long_seasonal_features=long_seasonal_features,seasonal_dispersion_features=seasonal_dispersion_features) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + self.long_query=nn.Linear(patch*4,d,bias=False) if long_seasonal_features else None + self.long_head=nn.Linear(d,patch*2) if long_seasonal_features else None + if long_seasonal_features: + nn.init.zeros_(self.long_query.weight) + nn.init.zeros_(self.long_head.weight);nn.init.zeros_(self.long_head.bias) + assert long_seasonal_features or not seasonal_dispersion_features + self.dispersion_query=nn.Linear(patch*4,d,bias=False) if seasonal_dispersion_features else None + if self.dispersion_query is not None:nn.init.zeros_(self.dispersion_query.weight) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + if self.long_query is not None:long_delta,long_extra,dispersion_extra=centered_seasonal_difference(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + hidden=self.norm(q) + out=self.head(hidden).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + if self.long_head is not None: + gates=self.long_head(hidden).view(b,h,2).float().tanh() + median=median+(gates*long_delta).sum(-1) + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_width/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_width/check.py new file mode 100644 index 0000000000000000000000000000000000000000..a7fc656ca584892be9a9602177757199b5d2004f --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_width/check.py @@ -0,0 +1,84 @@ +"""E129 unchanged initialization and direct bounded-width arithmetic checks.""" +import argparse,hashlib,importlib.util,json,math,sys,time +from pathlib import Path +import numpy as np +import torch +R=Path('/workspace/research');sys.path.insert(0,str(R/'seasonal_width')) +from model import DirectForecaster,centered_seasonal_difference,seasonal_width_multiplier,loss_fn +from data import Sampler +ap=argparse.ArgumentParser();ap.add_argument('--gpu',action='store_true');a=ap.parse_args() +torch.set_num_threads(2);torch.manual_seed(661);started=time.monotonic() +spec=importlib.util.spec_from_file_location('seasonal_width_control',R/'seasonal_dispersion/model.py');code=importlib.util.module_from_spec(spec);spec.loader.exec_module(code) +parent_path=R/'seasonal_dispersion_initial.pt';parent=torch.load(parent_path,map_location='cpu',weights_only=False) +config=dict(parent['config'],seasonal_width_features=True) +candidate=DirectForecaster(**config);missing,unexpected=candidate.load_state_dict(parent['model'],strict=False) +assert set(missing)=={'width_head.weight','width_head.bias'} and not unexpected +assert all(torch.count_nonzero(candidate.state_dict()[k])==0 for k in missing) +assert all(torch.equal(v,candidate.state_dict()[k]) for k,v in parent['model'].items()) +assert all(p.requires_grad for p in candidate.parameters()) +assert (R/'seasonal_width/data.py').read_bytes()==(R/'seasonal_dispersion/data.py').read_bytes() +assert (R/'seasonal_width/model.py').read_bytes()==(R/'seasonal_width_inference/model.py').read_bytes() +control=code.DirectForecaster(**parent['config']);control.load_state_dict(parent['model']) +if a.gpu: + import fcntl + lock=open(R/'.evaluation.lock','a');tick=time.monotonic();fcntl.flock(lock,fcntl.LOCK_EX);wait=time.monotonic()-tick + torch.backends.cuda.matmul.allow_tf32=False + candidate,control=candidate.cuda(),control.cuda();rng=np.random.default_rng(673) + ctx=torch.tensor(rng.normal(size=(8,512)).astype(np.float32),device='cuda');ctx[0,:23]=float('nan');ctx[1]=0 + periods=torch.tensor([[24,168],[7,365],[12,1],[52,1],[4,1],[1,1],[96,672],[2,14]],device='cuda') + target=torch.tensor(rng.normal(size=(8,128)).astype(np.float32),device='cuda') + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16): + expected=control(ctx,periods,128);actual=candidate(ctx,periods,128) + loss0=code.loss_fn(control,ctx,target,periods,paired=True);loss1=loss_fn(candidate,ctx,target,periods,paired=True) + assert all(torch.equal(v,w) for v,w in zip(expected,actual)) and torch.equal(loss0,loss1) + del control,ctx,target,periods,expected,actual,loss0,loss1 + torch.cuda.empty_cache();torch.cuda.reset_peak_memory_stats();free_before=torch.cuda.mem_get_info()[0]/2**20 + sampler=Sampler(R/'packed_sample',seed=673,source_weights_from=R/'packed_sample') + tensors=[torch.from_numpy(v).cuda() for v in sampler.sample(64,4096,1024)] + placeholders=[torch.zeros_like(p) for p in candidate.parameters() for _ in range(3)] + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(candidate,*tensors,paired=True) + loss.backward();assert torch.isfinite(loss) + assert all(p.grad is not None and torch.isfinite(p.grad).all() for p in candidate.parameters()) + gradients={k:float(dict(candidate.named_parameters())[k].grad.norm()) for k in ['width_head.weight','width_head.bias','dispersion_query.weight','long_head.weight','head.weight']} + assert all(v>0 for v in gradients.values()) + result=dict(seed=673,gpu_initial_function_bitwise_equal=True,gpu_initial_loss_bitwise_equal=True,max_shape=[64,4096,1024],loss=float(loss.detach()),selected_gradient_norms=gradients,all_parameters_trainable=True,reserved_mib=torch.cuda.max_memory_reserved()/2**20,allocated_mib=torch.cuda.max_memory_allocated()/2**20,free_before_mib=free_before,includes_ema_and_adam_placeholders=True,lock_wait_seconds=wait,seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False) + (R/'seasonal_width_gpu_checks.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));raise SystemExit() +rng=np.random.default_rng(661);z=rng.normal(size=(6,128)).astype(np.float32);valid=rng.random(z.shape)>.12;valid[4]=False;z[5]=0;z[~valid]=0 +periods=np.array([[4,7],[2,3],[12,1],[24,168],[4,8],[4,8]],dtype=np.int64) +tensors=[torch.from_numpy(x) for x in [z,valid,periods]] +actual=centered_seasonal_difference(*tensors,29);old=code.centered_seasonal_difference(*tensors,29) +assert all(torch.equal(v,w) for v,w in zip(actual[:3],old)) +expected=np.zeros((6,29,2),dtype=np.float32) +for row in range(6): + for j,period in enumerate(periods[row]): + for t in range(29): + observations=[];recent=0 + for cycle in range(16): + end=max(0,128-cycle*period);start=max(0,128-(cycle+1)*period);index=128-period+t%period-cycle*period + if index<0 or not valid[row,index]:continue + observations.append(float(z[row,index])-z[row,start:end][valid[row,start:end]].mean(dtype=np.float64)) + if cycle<4:recent+=1 + if period>=2 and len(observations)>=8 and recent>=2:expected[row,t,j]=np.log1p(np.std(observations,ddof=1))-np.log(2.) +assert np.max(np.abs(actual[3].numpy()-expected))<1e-6 +assert torch.count_nonzero(actual[3][4])==0 and torch.all(actual[3][5]==-math.log(2.)) +raw=rng.normal(size=expected.shape).astype(np.float32)*30 +factor=seasonal_width_multiplier(torch.from_numpy(raw),actual[3]).numpy() +reference=np.exp(np.clip((np.tanh(raw)*expected).sum(-1),-np.log(4.),np.log(4.))) +assert np.max(np.abs(factor-reference))<1e-6 and np.all((factor>=.25)&(factor<=4)) +for c,h in [(32,6),(128,29),(512,128)]: + ctx=torch.tensor(rng.normal(size=(6,c)).astype(np.float32));ctx[0,:c//3]=float('nan');ctx[1]=0;ctx[2]=float('nan') + with torch.inference_mode():q0,mu0,s0=control(ctx,torch.from_numpy(periods),h);q1,mu1,s1=candidate(ctx,torch.from_numpy(periods),h) + assert torch.equal(q0,q1) and torch.equal(mu0,mu1) and torch.equal(s0,s1) + with torch.no_grad():candidate.width_head.bias.view(16,2)[:]=torch.tensor([2.,-.7]) + with torch.inference_mode():q2,_,_=candidate(ctx,torch.from_numpy(periods),h) + zz,v,_,_=candidate.standardize(ctx);wd=centered_seasonal_difference(zz,v,torch.from_numpy(periods),h)[3] + multiplier=seasonal_width_multiplier(torch.tensor([2.,-.7]).expand(6,h,2),wd) + wanted=q0[:,:,4,None]+(q0-q0[:,:,4,None])*multiplier[:,:,None] + assert torch.max(torch.abs(q2-wanted))<2e-6 and torch.equal(q0[:,:,4],q2[:,:,4]) + assert torch.isfinite(q2).all() and torch.all(q2[:,:,1:]>=q2[:,:,:-1]) + with torch.no_grad():candidate.width_head.bias.zero_() +out=R/'seasonal_width_initial.pt';assert not out.exists() +checkpoint=dict(model=candidate.state_dict(),config=config,step=0,args=dict(packed=str(R/'packed_sample'),seed=661),parent_checkpoints=[str(parent_path)],conversion=dict(method='zero-initialized direct seasonal width head',parent_sha256=hashlib.sha256(parent_path.read_bytes()).hexdigest(),initial_function_bitwise_equal=True)) +torch.save(checkpoint,out) +result=dict(seed=661,initial_function_bitwise_equal=True,inherited_features_and_weights_bitwise_equal=True,independent_width_arithmetic=True,bounded_multiplier=[.25,4.],unchanged_median_for_fixed_hidden=True,finite_ordered=True,sampler_byte_identical=True,all_parameters_trainable=True,added_parameters=sum(v.numel() for v in candidate.width_head.parameters()),total_parameters=sum(p.numel() for p in candidate.parameters()),checkpoint_sha256=hashlib.sha256(out.read_bytes()).hexdigest(),seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False) +(R/'seasonal_width_checks.json').write_text(json.dumps(result,indent=2));print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_width/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_width/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_width/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_width/launch.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_width/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..4ab2570be7d55f94acc25ee268dd91c2e1f0f6cb --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_width/launch.py @@ -0,0 +1,42 @@ +"""Queue E129 after the older-history seasonal comparison finishes.""" +def main(): + import json + import os + import subprocess + from pathlib import Path + R = Path('/workspace/research') + checks = json.loads((R/'seasonal_width_checks.json').read_text()) + gpu = json.loads((R/'seasonal_width_gpu_checks.json').read_text()) + assert checks['initial_function_bitwise_equal'] and checks['sampler_byte_identical'] + assert checks['independent_width_arithmetic'] and checks['all_parameters_trainable'] + assert gpu['gpu_initial_function_bitwise_equal'] and gpu['all_parameters_trainable'] + assert gpu['optimizer_updates'] == 0 and not gpu['validation_data_read'] + name = 'seasonal_width' + run = R/'runs'/name + packed = R/'packed_sample' + env = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1') + command = ['python3', str(R/'recovery/train.py'), '--code-dir', str(R/name), + '--packed', str(packed), '--source-weights-from', str(packed), '--out', str(run), + '--initialize-from', str(R/'seasonal_width_initial.pt'), '--steps', '12000', + '--batch', '64', '--lr', '.00002', '--seed', '197', '--loss-mode', 'paired', + '--stop-file', str(R/(name+'.stop'))] + assert command[command.index('--out')+1] == str(run) + with (R/(name+'_queue.log')).open('w') as qlog, (R/(name+'_watch.log')).open('w') as wlog: + queued = subprocess.Popen(['python3',str(R/'queued_train.py'), + '--label','E129 direct learned seasonal uncertainty head seed197', + '--log',str(R/(name+'_train.log')),'--receipt',str(R/(name+'_queue.json')), + '--wait-pid','20306','--require-checkpoint',str(R/'runs/seasonal_history/ema012000.pt'), + '--',*command], stdout=qlog,stderr=subprocess.STDOUT,env=env) + watch = subprocess.Popen(['python3',str(R/'watch_evaluate.py'),'--run',str(run), + '--evaluator',str(R/'seasonal_width_inference/evaluate.py'),'--name',name, + '--expected-packed',str(packed),'--steps','1000,3000,6000,12000'], + stdout=wlog,stderr=subprocess.STDOUT,env=env) + print(json.dumps({'queue_pid':queued.pid,'watch_pid':watch.pid}),flush=True) + result = queued.wait() + if result: + watch.terminate() + watch.wait() + raise SystemExit(result) + +if __name__ == '__main__': + main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_width/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_width/model.py new file mode 100644 index 0000000000000000000000000000000000000000..0fb76d7fe91edd7ea32a5e4cf8ea092b570edcfe --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_width/model.py @@ -0,0 +1,279 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + + +def centered_seasonal_difference(z, valid, periods, horizon): + b, c = z.shape + time = torch.arange(horizon, device=z.device)[None, :] + sums = F.pad((z * valid).cumsum(-1), (1, 0)) + counts = F.pad(valid.float().cumsum(-1), (1, 0)) + deltas, extras, dispersion, width_deltas = [], [], [], [] + for j in range(2): + period = periods[:, j:j+1].clamp(min=1) + anchor = c - period + time % period + centered, masks = [], [] + for cycle in range(16): + end = (c - cycle * period).clamp(min=0, max=c) + start = (c - (cycle + 1) * period).clamp(min=0, max=c) + count = counts.gather(1, end) - counts.gather(1, start) + mean = (sums.gather(1, end) - sums.gather(1, start)) / count.clamp(min=1) + index = anchor - cycle * period + safe = index.clamp(min=0, max=c-1) + present = (index >= 0) & valid.gather(1, safe) + centered.append(z.gather(1, safe) - mean) + masks.append(present) + values = torch.stack(centered) + seen = torch.stack(masks) + n4 = seen[:4].sum(0) + n16 = seen.sum(0) + mean4 = (values[:4] * seen[:4]).sum(0) / n4.clamp(min=1) + mean16 = (values * seen).sum(0) / n16.clamp(min=1) + active = (period >= 2) & (n4 >= 2) & (n16 >= 8) + delta = torch.where(active, mean16 - mean4, 0.) + support = torch.where(active, n16.float() / 16, 0.) + deltas.append(delta) + extras.extend([delta, support]) + variance4 = (((values[:4] - mean4).square() * seen[:4]).sum(0) / (n4 - 1).clamp(min=1)) + variance16 = (((values - mean16).square() * seen).sum(0) / (n16 - 1).clamp(min=1)) + width_deltas.append(torch.where(active, variance16.sqrt().log1p() - math.log(2.), 0.)) + dispersion.extend([torch.where(active, variance4.sqrt().log1p(), 0.), + torch.where(active, variance16.sqrt().log1p(), 0.)]) + return torch.stack(deltas, -1), torch.stack(extras, -1), torch.stack(dispersion, -1), torch.stack(width_deltas, -1) + + + +def seasonal_width_multiplier(raw, delta): + return ((raw.float().tanh() * delta).sum(-1).clamp(-math.log(4.), math.log(4.))).exp() + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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,long_seasonal_features=True,seasonal_dispersion_features=True,seasonal_width_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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,long_seasonal_features=long_seasonal_features,seasonal_dispersion_features=seasonal_dispersion_features,seasonal_width_features=seasonal_width_features) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + self.long_query=nn.Linear(patch*4,d,bias=False) if long_seasonal_features else None + self.long_head=nn.Linear(d,patch*2) if long_seasonal_features else None + if long_seasonal_features: + nn.init.zeros_(self.long_query.weight) + nn.init.zeros_(self.long_head.weight);nn.init.zeros_(self.long_head.bias) + assert long_seasonal_features or not seasonal_dispersion_features + self.dispersion_query=nn.Linear(patch*4,d,bias=False) if seasonal_dispersion_features else None + if self.dispersion_query is not None:nn.init.zeros_(self.dispersion_query.weight) + assert seasonal_dispersion_features or not seasonal_width_features + self.width_head=nn.Linear(d,patch*2) if seasonal_width_features else None + if self.width_head is not None: + nn.init.zeros_(self.width_head.weight);nn.init.zeros_(self.width_head.bias) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + if self.long_query is not None:long_delta,long_extra,dispersion_extra,width_delta=centered_seasonal_difference(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + hidden=self.norm(q) + out=self.head(hidden).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + if self.long_head is not None: + gates=self.long_head(hidden).view(b,h,2).float().tanh() + median=median+(gates*long_delta).sum(-1) + widths=F.softplus(out[:,:,10:]).clamp(max=20) + if self.width_head is not None: + multiplier=seasonal_width_multiplier(self.width_head(hidden).view(b,h,2),width_delta) + widths=widths*multiplier[:,:,None] + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_width_transfer/assemble.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_width_transfer/assemble.py new file mode 100644 index 0000000000000000000000000000000000000000..91bcb5ee6127595d7a2a32cfca638ebd8f2b533d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_width_transfer/assemble.py @@ -0,0 +1,12 @@ +"""Assemble only a width-treatment candidate that passed its declared diagnostics.""" +import argparse,json,subprocess +from pathlib import Path +R=Path('/workspace/research');ap=argparse.ArgumentParser();ap.add_argument('--duration',type=int,choices=[6,12],required=True);a=ap.parse_args();d=a.duration +selection=json.loads((R/'seasonal_width_transfer_receipt.json').read_text());result=next(v for v in selection['results'] if v['duration']==d);assert result['selection_gate_passed'] and result['positive_cutoffs']>=3 and result['mean_delta']>0 +command=['python3',str(R/'publish_full_paired.py'),'--weights',str(R/f'seasonal_width_transfer{d}k.pt'),'--report',str(R/'evals'/f'seasonal_width_transfer{d}k/report.json'),'--runtime-dir',str(R/'seasonal_width_inference'),'--out',str(R/f'candidate-width-transfer{d}k')] +for name in ['postloss','long_memory_synth','overflow_control','weekly_synth','spectral_synth','spectral_transfer','long_seasonal','seasonal_dispersion','seasonal_width','seasonal_width_transfer']:command+=['--extra-training-code',name] +subprocess.run(command,check=True) +command=['python3',str(R/'four_member_ensemble/publish.py')] +for name in [f'candidate-width-transfer{d}k','candidate-patch8-6k-complete','candidate-split-patch-12k-complete','candidate-fresh146m-48k']:command+=['--member',str(R/name)] +command+=['--out',str(R/f'candidate-width{d}-ensemble')];subprocess.run(command,check=True) +subprocess.run(['python3',str(R/'seasonal_width_transfer/validate.py'),'--duration',str(d)],check=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_width_transfer/check_runtime.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_width_transfer/check_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..0b4b2787b2b3367603c9c0df2a5c7fc73a91988b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_width_transfer/check_runtime.py @@ -0,0 +1,23 @@ +"""New width member and quartet replay against unchanged E130 synthetic inputs/members.""" +import argparse,fcntl,hashlib,json,shutil,subprocess,sys,time +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation');from ts_io import read_prediction_file +R=Path('/workspace/research');ap=argparse.ArgumentParser();ap.add_argument('--duration',type=int,choices=[6,12],required=True);a=ap.parse_args();started=time.monotonic() +root=R/f'width{a.duration}_fixture';reference=R/'fresh_capacity4_fixture';package=R/f'candidate-width{a.duration}-ensemble';member=R/f'candidate-width-transfer{a.duration}k' +root.mkdir(exist_ok=True);shutil.copytree(reference/'input',root/'input',dirs_exist_ok=True) +for p in (root/'input').rglob('*'): + if p.is_file():assert hashlib.sha256(p.read_bytes()).digest()==hashlib.sha256((reference/'input'/p.relative_to(root/'input')).read_bytes()).digest() +descriptor=json.loads((package/'config.json').read_text());control=json.loads((R/'candidate-fresh-capacity4-ensemble/config.json').read_text());assert descriptor['members'][1:]==control['members'][1:] +lock=open(R/'.evaluation.lock','a');fcntl.flock(lock,fcntl.LOCK_EX) +for label,source,asset in [('standalone0',member,'weights.pt'),('ensemble',package,'config.json')]: + with (root/(label+'.log')).open('w') as log:subprocess.run(['python3',str(source/'predict.py'),str(root/'input'),str(root/label),'--weights',str(source/asset),'--batch','4'],stdout=log,stderr=subprocess.STDOUT,check=True) +rows=[] +for cfg in json.loads((root/'input/index.json').read_text())['configs']: + cid=cfg['config_id'];_,expected=read_prediction_file(root/'standalone0/cases'/(cid+'.h5'));expected=expected.copy() + for i in range(1,4):expected+=read_prediction_file(reference/f'standalone{i}/cases'/(cid+'.h5'))[1] + expected/=4;mean,actual=read_prediction_file(root/'ensemble/cases'/(cid+'.h5')) + assert np.array_equal(expected,actual) and np.array_equal(mean,actual[:,:,4]) and np.isfinite(actual).all() and np.all(np.diff(actual,axis=2)>=0) + rows.append(dict(config_id=cid,instances=cfg['n_instances'],bitwise_composition=True,finite_ordered=True)) +result=dict(duration=a.duration,descriptor_sha256=hashlib.sha256((package/'config.json').read_bytes()).hexdigest(),members=[v['weights_sha256'] for v in descriptor['members']],checks=rows,unchanged_member_references_reused=str(reference),input_files_bitwise_identical=True,seconds=time.monotonic()-started) +(R/f'width{a.duration}_runtime_checks.json').write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_width_transfer/merge.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_width_transfer/merge.py new file mode 100644 index 0000000000000000000000000000000000000000..04b124b615cfba7243c3d938b8d7540bf3d2c01c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_width_transfer/merge.py @@ -0,0 +1,32 @@ +"""E139 transfer only the width-treatment difference, with two distinct zero extensions.""" +import argparse,hashlib,importlib.util,json,sys,time +from pathlib import Path +import numpy as np +import torch +R=Path('/workspace/research');ap=argparse.ArgumentParser() +for key in ['base','candidate','control','out']:ap.add_argument('--'+key,required=True) +a=ap.parse_args();torch.set_num_threads(2);torch.manual_seed(769);started=time.monotonic() +paths=[Path(a.base),Path(a.candidate),Path(a.control)];base,candidate,control=[torch.load(p,map_location='cpu',weights_only=False) for p in paths] +base_extra={'dispersion_query.weight','width_head.weight','width_head.bias'};control_extra={'width_head.weight','width_head.bias'} +assert set(candidate['model'])==set(base['model'])|base_extra==set(control['model'])|control_extra +c=dict(candidate['config']);assert c.pop('seasonal_width_features') is True;assert c==control['config'];assert c.pop('seasonal_dispersion_features') is True;assert c==base['config'] +sys.path.insert(0,str(R/'seasonal_width'));from model import DirectForecaster +extended=DirectForecaster(**candidate['config']);missing,unexpected=extended.load_state_dict(base['model'],strict=False) +assert set(missing)==base_extra and not unexpected and all(torch.count_nonzero(extended.state_dict()[k])==0 for k in base_extra) +spec=importlib.util.spec_from_file_location('width_transfer_base',R/'long_seasonal/model.py');module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module) +original=module.DirectForecaster(**base['config']);original.load_state_dict(base['model']);rng=np.random.default_rng(769);periods=torch.tensor([[24,168],[7,365],[52,1],[1,1]]) +for c,h in [(32,6),(512,128)]: + ctx=torch.tensor(rng.normal(size=(4,c)).astype(np.float32));ctx[0,:c//3]=float('nan');ctx[1]=0;ctx[2]=float('nan') + with torch.inference_mode():left=original(ctx,periods,h);right=extended(ctx,periods,h) + assert all(torch.equal(v,w) for v,w in zip(left,right)) +weights={k:v.clone() for k,v in extended.state_dict().items()} +for k in weights: + if k in control_extra:weights[k].copy_(candidate['model'][k]) + else:weights[k].add_(candidate['model'][k]-control['model'][k]) +assert all(torch.isfinite(v).all() for v in weights.values());extended.load_state_dict(weights) +with torch.inference_mode():quant,mu,scale=extended(ctx,periods,128) +assert torch.isfinite(quant).all() and torch.all(quant[:,:,1:]>=quant[:,:,:-1]) +out=Path(a.out);assert not out.exists() +conversion=dict(method='matched direct-width-head training delta, separately zero-extending base and control',formula='zero_extend(E117first)+E129-zero_extend(E119)',coefficient=1.,base_zero_parameters=sorted(base_extra),control_zero_parameters=sorted(control_extra),dispersion_query='candidate-minus-control only; no E128 correction',parent_hashes={str(p):hashlib.sha256(p.read_bytes()).hexdigest() for p in paths},base_extension_forward_bitwise_equal=True,finite_ordered_fixture=True,check_seed=769,seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False) +ck=dict(model=weights,config=candidate['config'],step=0,args=dict(packed=base['args']['packed']),parent_checkpoints=[str(p) for p in paths],conversion=conversion);torch.save(ck,out) +result=dict(conversion,checkpoint_sha256=hashlib.sha256(out.read_bytes()).hexdigest(),parameters=sum(v.numel() for v in weights.values()));out.with_suffix('.json').write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_width_transfer/promote.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_width_transfer/promote.py new file mode 100644 index 0000000000000000000000000000000000000000..5bfd16861ed4594c178012b066b2614104e505b5 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_width_transfer/promote.py @@ -0,0 +1,40 @@ +"""Publish an E139 candidate only after complete replay, exact composition and current-best checks.""" +import argparse,datetime,hashlib,json,os,subprocess +from pathlib import Path +R=Path('/workspace/research');ap=argparse.ArgumentParser();ap.add_argument('--duration',type=int,choices=[6,12],required=True);a=ap.parse_args();d=a.duration;name=f'width{d}_ensemble';package=R/f'candidate-width{d}-ensemble';report=R/f'valid-report-width{d}-ensemble.json' +read=lambda p:json.loads(p.read_text()) +result=read(report);suite=read(R/(name+'_validation_receipt.json'));selection=next(v for v in read(R/'seasonal_width_transfer_receipt.json')['results'] if v['duration']==d) +assert suite['status']=='complete' and all(x['returncode']==0 for x in suite['steps']) +assert selection['selection_gate_passed'] and selection['positive_cutoffs']>=3 and selection['mean_delta']>0 +relocation=read(R/(name+'_package_checks.json'));assert len(relocation)==1 and all(x['bitwise_equal_after_relocation'] and x['finite_and_monotone'] for x in relocation) +composition=read(R/(name+'_composition_checks.json'));assert len(composition['comparisons'])==3 and all(x['bitwise_equal_to_fixed_member_average'] for x in composition['comparisons']) +synthetic=read(R/f'width{d}_runtime_checks.json');assert len(synthetic['checks'])==2 and all(x['bitwise_composition'] and x['finite_ordered'] for x in synthetic['checks']) +validated=read(package/'model_manifest.json');assert validated['checkpoint_sha256']==synthetic['descriptor_sha256']==result['checkpoint_sha256'] +assert len(validated['members'])==4 and validated['ensemble_weights']==[.25]*4 and validated['pretrained_assets']==[] +old=read(Path('/workspace/submission/validation_report.json'));old_manifest=read(Path('/workspace/submission/model_manifest.json'));state=read(R/'CURRENT_RESEARCH_STATE.json');prior=state['published'] +assert old_manifest['checkpoint_sha256']==prior['checkpoint_sha256'] +assert result['n_failed']==0 and result['n_configs']==97 and result['n_instances']==151170 and result['skill_score']>old['skill_score'] +cutoffs=['valid_screen','valid_backcast','valid_backcast2','valid_backcast3'];probes=[read(R/(name+'_'+c+'.json')) for c in cutoffs] +current_skills=[prior['main_skill']]+prior['earlier_skills'];differences=[x['skill_score']-y for x,y in zip(probes,current_skills)] +assert len(differences)==4 and sum(x>0 for x in differences)>=3 and sum(differences)>0 +members=[R/f'candidate-width-transfer{d}k',R/'candidate-patch8-6k-complete',R/'candidate-split-patch-12k-complete',R/'candidate-fresh146m-48k'] +for i,source in enumerate(members): + m=read(source/'model_manifest.json');assert m['weights_sha256']==validated['members'][i]['weights_sha256'] and m['runtime_code_sha256']['model.py']==validated['runtime_code_sha256'][f'model{i}.py'] + assert (source/'provenance/recovery/schedules.py').exists() +for path in (R/'four_member_ensemble/runtime').iterdir(): + if path.name in validated['runtime_code_sha256']:assert hashlib.sha256(path.read_bytes()).hexdigest()==validated['runtime_code_sha256'][path.name] +comparison=read(R/(name+'_comparison.json')) +outcome=f"Matched width-treatment correction at {d*1000} steps improves full skill from {old['skill_score']:.12f} to {result['skill_score']:.12f}. All97configs151170instances pass. Inference {result['inference_seconds']:.3f}s on shared H100. Relocation and actual-member real/extreme synthetic composition are bitwise exact. Validation selection only, not held-out reward." +subprocess.run(['python3',str(R/'direct_v1/record.py'),str(report),'--label',f'E139 direct-width treatment{d*1000} equal-quarter full replay selected','--outcome',outcome],check=True) +with (R/'direct_v1/EXPERIMENTS.md').open('a') as f:f.write('\nE139 complete suite '+json.dumps(suite)+'. Synthetic checks '+json.dumps(synthetic)+'. Descriptive comparison '+json.dumps({k:v for k,v in comparison.items() if k!='configs'})+'. Current-publication diagnostic deltas '+json.dumps(differences)+'. Every member forecasts every instance. E101teacher and E138experts remain their immutable declared snapshots.\n') +command=['python3',str(R/'four_member_ensemble/publish.py')] +for source in members:command+=['--member',str(source)] +command+=['--report',str(report),'--out','/workspace/submission'];subprocess.run(command,check=True) +published=read(Path('/workspace/submission/model_manifest.json'));assert published['checkpoint_sha256']==validated['checkpoint_sha256'] and published['runtime_code_sha256']==validated['runtime_code_sha256'] +now=datetime.datetime.now(datetime.timezone.utc).isoformat();state=read(R/'CURRENT_RESEARCH_STATE.json');state.setdefault('previous_published',[]).append(state['published']) +state['published']=dict(experiment=f'E139 width-treatment{d*1000} firstmember/E71/E93/E79wide48000 equal quarters',package='/workspace/submission',checkpoint_sha256=result['checkpoint_sha256'],parameters=published['parameters'],main_skill=probes[0]['skill_score'],earlier_skills=[x['skill_score'] for x in probes[1:]],full_validation_skill=result['skill_score'],full_report=str(report),status='published after full replay and all checks',publisher=command[1],publisher_arguments=command[2:],published_utc=now,journal_refreshed_utc=now,validation_receipt=str(R/(name+'_validation_receipt.json')),package_checks=str(R/(name+'_package_checks.json')),composition_checks=str(R/(name+'_composition_checks.json')),synthetic_checks=str(R/f'width{d}_runtime_checks.json'),notes='Validation only. All members trained here; fixed equal quarters. E101teacher E96 and E138expert E130 snapshots stay immutable.') +state['selection_probes']['E139'].setdefault('duration_results',{})[str(d*1000)]=dict(status='published',full_skill=result['skill_score'],descriptor=result['checkpoint_sha256'],published_utc=now) +state['next_candidate']=dict(experiment='E132 final fourthmember, E139 width durability, E138 learned gate; active matched architecture/data studies',status='continue research') +p=R/'CURRENT_RESEARCH_STATE.json';tmp=p.with_suffix('.tmp');tmp.write_text(json.dumps(state,indent=2));os.replace(tmp,p) +with (R/'SESSION_20261023_PROGRESS.md').open('a') as f:f.write('\n'+now+': E139 width'+str(d*1000)+' atomically published. '+outcome+' Descriptor'+result['checkpoint_sha256']+'.\n') +print(json.dumps(dict(utc=now,skill=result['skill_score'],descriptor=result['checkpoint_sha256'],parameters=published['parameters'])),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_width_transfer/run.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_width_transfer/run.py new file mode 100644 index 0000000000000000000000000000000000000000..9f35156c37f33a35c2e6005cbfae1e6de2676101 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_width_transfer/run.py @@ -0,0 +1,36 @@ +"""E139 fixed width-treatment transfers at primary6k and conditional12k durability.""" +import datetime,hashlib,json,os,subprocess,time +from pathlib import Path +R=Path('/workspace/research');start=time.monotonic();receipt=R/'seasonal_width_transfer_receipt.json' +state=dict(pid=os.getpid(),status='running',steps=[],results=[],started_utc=datetime.datetime.now(datetime.timezone.utc).isoformat()) +def save(): + state['seconds']=time.monotonic()-start;tmp=receipt.with_suffix('.tmp');tmp.write_text(json.dumps(state,indent=2));os.replace(tmp,receipt) +def call(label,command): + state['status']=label;save();t=time.monotonic();result=subprocess.run(command);state['steps'].append(dict(label=label,returncode=result.returncode,seconds=time.monotonic()-t));save() + if result.returncode:state['status']='failed';save();raise SystemExit(result.returncode) +for duration in [6,12]: + step=duration*1000;comparison=R/f'seasonal_width{duration}k_four_cutoff_comparison.json';state['status']='waiting matched width gate'+str(duration);save() + while not comparison.exists():time.sleep(3) + time.sleep(1);d=json.loads(comparison.read_text());assert d['candidate']==f'seasonal_width_ema{step}' and d['control']==f'seasonal_dispersion_ema{step}' + if d['positive_cutoffs']<3 or d['mean_delta']<=0: + state['status']='complete; matched source gate failed'+str(duration);save() + with (R/'direct_v1/EXPERIMENTS.md').open('a') as f:f.write('\nE139source gate failed for'+str(duration)+'k; no additional transfer constructed. '+json.dumps(state)+'\n') + raise SystemExit() + name=f'seasonal_width_transfer{duration}k';weights=R/(name+'.pt') + if not weights.exists():call('literal matched merge'+str(duration),['python3',str(R/'seasonal_width_transfer/merge.py'),'--base',str(R/'long_seasonal_transfer12k.pt'),'--candidate',str(R/'runs/seasonal_width'/f'ema{step:06d}.pt'),'--control',str(R/'runs/seasonal_dispersion'/f'ema{step:06d}.pt'),'--out',str(weights)]) + merge=json.loads(weights.with_suffix('.json').read_text());assert hashlib.sha256(weights.read_bytes()).hexdigest()==merge['checkpoint_sha256'] + for parent,digest in merge['parent_hashes'].items():assert hashlib.sha256(Path(parent).read_bytes()).hexdigest()==digest + call('first member four cutoffs'+str(duration),['python3',str(R/'evaluate_cutoffs.py'),'--name',name,'--weights',str(weights),'--evaluator',str(R/'seasonal_width_inference/evaluate.py')]) + rows=[] + for cutoff,folder in [('valid_screen','evals'),('valid_backcast','backcast_evals'),('valid_backcast2','backcast2_evals'),('valid_backcast3','backcast3_evals')]: + call('record first '+str(duration)+' '+cutoff,['python3',str(R/'direct_v1/record.py'),str(R/folder/name/'report.json'),'--label',f'E139 width-treatment transfer{step} '+cutoff,'--outcome','Fixed zero-extended E117first + E129 - zero-extended E119, coefficient1. No E128dispersion correction; no optimizer update. Equal-quarter ensemble selected separately.']) + out=R/(f'width{duration}_ensemble_'+cutoff+'.json');command=['python3',str(R/'equal_ensemble_probe.py'),'--valid',str(R/cutoff),'--out',str(out)] + for member in [name,'patch8_ema6000','split_patch_ema12000','random_capacity_1024_ema48000']:command+=['--pred',str(R/folder/member)] + call('fixed equal quarters '+str(duration)+' '+cutoff,command) + a=json.loads(out.read_text());b=json.loads((R/('fresh_capacity4_ensemble_'+cutoff+'.json')).read_text()) + rows.append(dict(cutoff=cutoff,skill=a['skill_score'],control_skill=b['skill_score'],delta=a['skill_score']-b['skill_score'],groups=a['groups'],member_checkpoint_hashes=a['member_checkpoint_hashes'],cpu_seconds=a['cpu_seconds'])) + result=dict(duration=duration,rows=rows,positive_cutoffs=sum(v['delta']>0 for v in rows),mean_delta=sum(v['delta'] for v in rows)/4) + result['selection_gate_passed']=result['positive_cutoffs']>=3 and result['mean_delta']>0 + state['results'].append(result);save() + with (R/'direct_v1/EXPERIMENTS.md').open('a') as f:f.write('\nE139 fixed width-treatment equal-quarter ensemble diagnostics: '+json.dumps(result)+'. Full replay/runtime checks and comparison to current publication required before any promotion.\n') +state['status']='complete; research review required';save();print(json.dumps(state),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_width_transfer/validate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_width_transfer/validate.py new file mode 100644 index 0000000000000000000000000000000000000000..1cc073a620db92b2d7b1c3c564834d5ecf95f8ef --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/seasonal_width_transfer/validate.py @@ -0,0 +1,13 @@ +"""Full public replay and independent composition for E139; no automatic promotion.""" +import argparse,json,subprocess,time +from pathlib import Path +R=Path('/workspace/research');ap=argparse.ArgumentParser();ap.add_argument('--duration',type=int,choices=[6,12],required=True);a=ap.parse_args();d=a.duration;started=time.monotonic() +package=R/f'candidate-width{d}-ensemble';report=R/f'valid-report-width{d}-ensemble.json';pred=R/f'valid-pred-width{d}-ensemble';firstpred=R/f'composition-pred-width-transfer{d}k';receipt=R/f'width{d}_ensemble_validation_receipt.json' +steps=[('synthetic_composition',['python3',str(R/'seasonal_width_transfer/check_runtime.py'),'--duration',str(d)]),('relocation',['python3',str(R/'verify_package_examples.py'),'--package',str(package),'--receipt',str(R/f'width{d}_ensemble_package_checks.json')]),('full_public_replay',['python3',str(R/'run_package_validation.py'),'--package',str(package),'--out',str(pred),'--report',str(report)]),('independent_first_member',['python3',str(R/'run_composition_member.py'),'--package',str(R/f'candidate-width-transfer{d}k'),'--out',str(firstpred),'--receipt',str(R/f'width{d}_composition_replay.json')]),('composition',['python3',str(R/'check_ensemble_composition.py'),'--pred',str(pred),'--member',str(firstpred),'--member',str(R/'valid-pred-patch8-6k'),'--member',str(R/'composition-pred-split-patch-12k'),'--member',str(R/'composition-pred-fresh146m48'),'--out',str(R/f'width{d}_ensemble_composition_checks.json')]),('descriptive_comparison',['python3',str(R/'compare_reports.py'),'--candidate',str(report),'--parent',str(R/'valid-report-fresh-capacity4-ensemble.json'),'--out',str(R/f'width{d}_ensemble_comparison.json')])] +state=dict(package=str(package),status='running',steps=[]) +for label,command in steps: + state['current_step']=label;receipt.write_text(json.dumps(state,indent=2));tick=time.monotonic();result=subprocess.run(command);state['steps'].append(dict(name=label,returncode=result.returncode,seconds=time.monotonic()-tick)) + if result.returncode: + state.update(status='failed',seconds=time.monotonic()-started);receipt.write_text(json.dumps(state,indent=2));raise SystemExit(result.returncode) +r=json.loads(report.read_text());assert r['n_failed']==0 and r['n_configs']==97 and r['n_instances']==151170 +state.update(status='complete',seconds=time.monotonic()-started,skill=r['skill_score']);receipt.write_text(json.dumps(state,indent=2));print(json.dumps(state),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/spectral_synth/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/spectral_synth/check.py new file mode 100644 index 0000000000000000000000000000000000000000..18b155db82902843efdf6df4164d5ed87f249a47 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/spectral_synth/check.py @@ -0,0 +1,79 @@ +"""Check spectral covariance and unchanged control streams without validation data.""" +import copy +import hashlib +import importlib.util +import json +import sys +import time +from pathlib import Path + +import numpy as np + +R = Path('/workspace/research') +sys.path.insert(0, str(R / 'spectral_synth')) +from data import Sampler +from spectral import gaussian_residual, spectral_density + +spec = importlib.util.spec_from_file_location('spectral_control_data', R / 'overflow_control/data.py') +control_code = importlib.util.module_from_spec(spec) +spec.loader.exec_module(control_code) +started = time.monotonic() +seed = 499 +candidate = Sampler(R / 'packed_sample', seed=seed, source_weights_from=R / 'packed_sample') +control = control_code.Sampler(R / 'packed_sample', seed=seed, source_weights_from=R / 'packed_sample') +rng = np.random.default_rng(seed) +rows = synthetic_rows = replaced_rows = 0 +for _ in range(120): + c = int(rng.choice([512, 1024, 2048, 4096])) + h = int(rng.choice([32, 128, 512, 1024])) + expected = control.sample(64, c, h) + actual = candidate.sample(64, c, h) + replacements = np.array(candidate.last_spectral_rows, dtype=int) + unchanged = np.ones(64, dtype=bool) + unchanged[replacements] = False + for x, y in zip(expected, actual): + assert np.array_equal(x[unchanged], y[unchanged], equal_nan=True) + assert set(replacements) <= set(candidate.last_synthetic_rows) + assert np.array_equal(expected[2], actual[2]) + for x, y in zip(expected[:2], actual[:2]): + assert np.array_equal(np.isfinite(x), np.isfinite(y)) + assert candidate.rng.bit_generator.state == control.rng.bit_generator.state + assert candidate.horizon_rng.bit_generator.state == control.horizon_rng.bit_generator.state + rows += 64 + synthetic_rows += len(candidate.last_synthetic_rows) + replaced_rows += len(replacements) +sampler_seconds = time.monotonic() - started +states = {n: copy.deepcopy(v.bit_generator.state) for n, v in vars(candidate).items() + if isinstance(v, np.random.Generator)} +next_batch = candidate.sample(64, 4096, 1024) +for name, state in states.items(): + getattr(candidate, name).bit_generator.state = state +replayed = candidate.sample(64, 4096, 1024) +assert all(np.array_equal(x, y, equal_nan=True) for x, y in zip(next_batch, replayed)) + +covariances = [] +for family in range(4): + values = np.stack([gaussian_residual(512, rng, length_scale=8, family=family) + for _ in range(1024)]) + expected = np.fft.irfft(spectral_density(2048, 8, family), n=2048) + observed = [float(np.mean(values * values))] + observed += [float(np.mean(values[:, lag:] * values[:, :-lag])) for lag in [1, 8, 32]] + wanted = expected[[0, 1, 8, 32]] + assert np.max(np.abs(np.array(observed) - wanted)) < .045 + covariances.append(dict(family=family, observed=observed, theoretical=wanted.tolist())) +for family in range(4): + for n in [8, 40, 5120]: + for scale in [1., 1e4]: + assert np.isfinite(gaussian_residual(n, rng, scale, family)).all() +model_hash = hashlib.sha256((R / 'spectral_synth/model.py').read_bytes()).hexdigest() +assert model_hash == hashlib.sha256((R / 'overflow_control/model.py').read_bytes()).hexdigest() +result = dict(seed=seed, rows=rows, original_synthetic_rows=synthetic_rows, + replaced_spectral_rows=replaced_rows, probability=.5, + original_and_horizon_rng_bitwise_preserved=True, + unmodified_rows_bitwise_preserved=True, periods_and_finite_masks_unchanged=True, + all_numpy_rng_recovery_exact=True, model_sha256=model_hash, + model_bitwise_unchanged=True, covariance_checks=covariances, + sampler_comparison_seconds=sampler_seconds, seconds=time.monotonic()-started, + optimizer_updates=0, validation_data_read=False) +(R / 'spectral_synth_checks.json').write_text(json.dumps(result, indent=2)) +print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/spectral_synth/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/spectral_synth/data.py new file mode 100644 index 0000000000000000000000000000000000000000..bf91f33740715be702c2772f3cca89b656cea4dc --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/spectral_synth/data.py @@ -0,0 +1,102 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq +from spectral import gaussian_residual + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + if self.spectral_rng.random()8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + self.spectral_rng=np.random.default_rng(seed+1100003) + self.spectral_probability=.5 + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/spectral_synth/launch.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/spectral_synth/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..0134693b620294a3fb18eed15e107d649a0cc487 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/spectral_synth/launch.py @@ -0,0 +1,29 @@ +"""Queue spectral synthetic residuals after postloss completion finishes.""" +def main(): + import json + import os + import subprocess + from pathlib import Path + R=Path('/workspace/research') + checks=json.loads((R/'spectral_synth_checks.json').read_text()) + assert checks['original_and_horizon_rng_bitwise_preserved'] and checks['unmodified_rows_bitwise_preserved'] + assert checks['all_numpy_rng_recovery_exact'] and checks['model_bitwise_unchanged'] + env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1') + command=['python3',str(R/'recovery/train.py'),'--code-dir',str(R/'spectral_synth'), + '--packed',str(R/'packed_sample'),'--source-weights-from',str(R/'packed_sample'), + '--out',str(R/'runs/spectral_synth'),'--initialize-from',str(R/'horizon_delta12k.pt'), + '--steps','12000','--batch','64','--lr','.00002','--seed','197','--loss-mode','paired', + '--stop-file',str(R/'spectral_synth.stop')] + with (R/'spectral_synth_queue.log').open('w') as qlog,(R/'spectral_synth_watch.log').open('w') as wlog: + queued=subprocess.Popen(['python3',str(R/'queued_train.py'),'--label','E106 spectral synthetic residuals seed197', + '--log',str(R/'spectral_synth_train.log'),'--receipt',str(R/'spectral_synth_queue.json'), + '--wait-pid','10664','--require-checkpoint',str(R/'runs/postloss_completion/recovery.pt'), + '--',*command],stdout=qlog,stderr=subprocess.STDOUT,env=env) + watch=subprocess.Popen(['python3',str(R/'watch_evaluate.py'),'--run',str(R/'runs/spectral_synth'), + '--evaluator',str(R/'postloss_inference/evaluate.py'),'--name','spectral_synth', + '--expected-packed',str(R/'packed_sample'),'--steps','1000,3000,6000,12000'],stdout=wlog,stderr=subprocess.STDOUT,env=env) + print({'queue_pid':queued.pid,'watch_pid':watch.pid},flush=True) + result=queued.wait() + if result:watch.terminate() + watch.wait();raise SystemExit(result) +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/spectral_synth/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/spectral_synth/model.py new file mode 100644 index 0000000000000000000000000000000000000000..3532e5063bd8b5013f6b6e35703707ffef66e00b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/spectral_synth/model.py @@ -0,0 +1,213 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/spectral_synth/spectral.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/spectral_synth/spectral.py new file mode 100644 index 0000000000000000000000000000000000000000..f7358c3ec944849ea619ef2e73697775b48d408c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/spectral_synth/spectral.py @@ -0,0 +1,27 @@ +"""Locally generated finite stationary Gaussian fields with varied smoothness.""" +import numpy as np + + +def spectral_density(size, length_scale, family): + omega = 2 * np.pi * np.fft.rfftfreq(size) + if family == 3: + density = np.exp(-.5 * (length_scale * omega) ** 2) + else: + nu = [.5, 1.5, 2.5][family] + density = (1 + (length_scale * omega) ** 2 / (2 * nu)) ** (-nu - .5) + # Real FFT has one DC and one Nyquist coefficient, two of each interior bin. + variance = (density[0] + density[-1] + 2 * density[1:-1].sum()) / size + return density / variance + + +def gaussian_residual(n, rng, length_scale=None, family=None): + """The covariance is the discrete inverse Fourier transform of the declared PSD.""" + if length_scale is None: + length_scale = 10 ** rng.uniform(0, 4) + if family is None: + family = int(rng.integers(4)) + size = 1 << (max(16, 4 * n) - 1).bit_length() + density = spectral_density(size, length_scale, family) + white = rng.normal(size=size) + field = np.fft.irfft(np.fft.rfft(white) * np.sqrt(density), n=size) + return field[:n].astype(np.float32) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/spectral_transfer/run.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/spectral_transfer/run.py new file mode 100644 index 0000000000000000000000000000000000000000..b12c03e56acc3688932c441fd31aa259136f1bc1 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/spectral_transfer/run.py @@ -0,0 +1,55 @@ +"""E114: two predeclared coefficient-one spectral-prior transfers; selection only.""" +import hashlib +import json +import os +import subprocess +import time +from pathlib import Path + +R = Path('/workspace/research') +env = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1') +started = time.monotonic() +receipt = {'experiment': 'E114', 'status': 'running', 'steps': []} +receipt_path = R / 'spectral_transfer_receipt.json' + +def run(label, command): + receipt['current_step'] = label + receipt_path.write_text(json.dumps(receipt, indent=2)) + print(json.dumps({'starting': label}), flush=True) + t0 = time.monotonic() + result = subprocess.run(command, env=env, check=False) + receipt['steps'].append({'name': label, 'seconds': time.monotonic()-t0, + 'returncode': result.returncode}) + if result.returncode: + receipt.update(status='failed', seconds=time.monotonic()-started) + receipt_path.write_text(json.dumps(receipt, indent=2)) + raise SystemExit(result.returncode) + +add = R/'spectral_add_delta6k.pt' +replace = R/'spectral_replace_delta6k.pt' +assert not add.exists() and not replace.exists(), 'Refuse to overwrite fixed candidates' +run('add_spectral_delta', ['python3', str(R/'partial_delta/merge.py'), + '--base', str(R/'weekly_slow_ar_delta6k.pt'), + '--candidate', str(R/'runs/spectral_synth/ema006000.pt'), + '--control', str(R/'runs/overflow_control/ema006000.pt'), '--out', str(add)]) +run('remove_old_slow_ar_delta', ['python3', str(R/'partial_delta/merge.py'), + '--base', str(add), '--candidate', str(R/'runs/partial_targets/ema006000.pt'), + '--control', str(R/'runs/long_memory_synth_recovery/ema006000.pt'), '--out', str(replace)]) +receipt['candidate_hashes'] = {p.stem: hashlib.sha256(p.read_bytes()).hexdigest() for p in [add, replace]} +for weights in [add, replace]: + run(weights.stem+'_four_cutoffs', ['python3', str(R/'evaluate_cutoffs.py'), + '--name', weights.stem, '--weights', str(weights), + '--evaluator', str(R/'postloss_inference/evaluate.py')]) + for cutoff, folder in [('valid_screen','evals'), ('valid_backcast','backcast_evals'), + ('valid_backcast2','backcast2_evals'), ('valid_backcast3','backcast3_evals')]: + run(weights.stem+'_'+cutoff+'_record', ['python3', str(R/'direct_v1/record.py'), + str(R/folder/weights.stem/'report.json'), '--label', 'E114 '+weights.stem+' '+cutoff, + '--outcome', 'Fixed coefficient-one spectral transfer; additive and old-slow-AR replacement are the two predeclared ablations. No optimization. Ensemble selection recorded separately.']) + command = ['python3', str(R/'equal_ensemble_probe.py'), '--valid', str(R/cutoff), + '--out', str(R/(weights.stem+'_ensemble_'+cutoff+'.json'))] + for name in [weights.stem, 'patch8_ema6000', 'split_patch_ema12000']: + command += ['--pred', str(R/folder/name)] + run(weights.stem+'_'+cutoff+'_ensemble', command) +receipt.update(status='complete', seconds=time.monotonic()-started) +receipt_path.write_text(json.dumps(receipt, indent=2)) +print(json.dumps(receipt), flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/weekly_synth/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/weekly_synth/check.py new file mode 100644 index 0000000000000000000000000000000000000000..1797c7ca37791de3ac143f64843434ad7beda0ba --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/weekly_synth/check.py @@ -0,0 +1,45 @@ +"""Verify the weekly-only data change without using validation or optimizer steps.""" +import copy +import hashlib +import importlib.util +import json +import sys +import time +from pathlib import Path +import numpy as np + +R=Path('/workspace/research') +sys.path.insert(0,str(R/'weekly_synth')) +from data import Sampler +spec=importlib.util.spec_from_file_location('weekly_control_data',R/'overflow_control/data.py') +control_code=importlib.util.module_from_spec(spec);spec.loader.exec_module(control_code) +started=time.monotonic();seed=467 +candidate=Sampler(R/'packed_sample',seed=seed,source_weights_from=R/'packed_sample') +control=control_code.Sampler(R/'packed_sample',seed=seed,source_weights_from=R/'packed_sample') +rng=np.random.default_rng(seed);rows=synthetic_rows=weekly_rows=0 +for _ in range(120): + c=int(rng.choice([512,1024,2048,4096]));h=int(rng.choice([32,128,512,1024])) + expected=control.sample(64,c,h);actual=candidate.sample(64,c,h) + replacements=np.array(candidate.last_weekly_rows,dtype=int) + unchanged=np.ones(64,dtype=bool);unchanged[replacements]=False + for x,y in zip(expected,actual): + assert np.array_equal(x[unchanged],y[unchanged],equal_nan=True) + assert set(candidate.last_weekly_rows)<=set(candidate.last_synthetic_rows) + assert np.all(actual[2][replacements]==np.array([52,1])) + for x,y in zip(expected[:2],actual[:2]): + assert np.array_equal(np.isfinite(x),np.isfinite(y)) + assert candidate.rng.bit_generator.state==control.rng.bit_generator.state + assert candidate.horizon_rng.bit_generator.state==control.horizon_rng.bit_generator.state + rows+=64;synthetic_rows+=len(candidate.last_synthetic_rows);weekly_rows+=len(replacements) +states={n:copy.deepcopy(v.bit_generator.state) for n,v in vars(candidate).items() if isinstance(v,np.random.Generator)} +next_batch=candidate.sample(64,4096,1024) +for name,state in states.items():getattr(candidate,name).bit_generator.state=state +replayed=candidate.sample(64,4096,1024) +assert all(np.array_equal(x,y,equal_nan=True) for x,y in zip(next_batch,replayed)) +model_hash=hashlib.sha256((R/'weekly_synth/model.py').read_bytes()).hexdigest() +assert model_hash==hashlib.sha256((R/'overflow_control/model.py').read_bytes()).hexdigest() +result=dict(seed=seed,rows=rows,original_synthetic_rows=synthetic_rows,replaced_weekly_rows=weekly_rows, + probability=1/11,original_and_horizon_rng_bitwise_preserved=True,unmodified_rows_bitwise_preserved=True, + finite_masks_unchanged=True,all_numpy_rng_recovery_exact=True,model_sha256=model_hash, + model_bitwise_unchanged=True,seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False) +(R/'weekly_synth_checks.json').write_text(json.dumps(result,indent=2));print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/weekly_synth/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/weekly_synth/data.py new file mode 100644 index 0000000000000000000000000000000000000000..81f0f018cb212a6e2125543e0d4efa2f31b9d8fb --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/weekly_synth/data.py @@ -0,0 +1,113 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + self.weekly_rng=np.random.default_rng(seed+1000003) + self.weekly_probability=1/11 + def synthetic(self,n,p): + # Always consume the control generator first, preserving its complete RNG stream. + original=super().synthetic(n,p) + if self.weekly_rng.random()>=self.weekly_probability: + return original + original_rng=self.rng + try: + self.rng=self.weekly_rng + result=super().synthetic(n,[52,1]) + finally: + self.rng=original_rng + p[:]=[52,1] + self.last_weekly_rows.append(self._synthetic_row) + return result + + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/weekly_synth/launch.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/weekly_synth/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..ef36b1e3de2ad1cc424019100da141536161d07a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/weekly_synth/launch.py @@ -0,0 +1,29 @@ +"""Queue weekly synthetic coverage after robust-normalization training finishes.""" +def main(): + import json + import os + import subprocess + from pathlib import Path + R=Path('/workspace/research') + checks=json.loads((R/'weekly_synth_checks.json').read_text()) + assert checks['original_and_horizon_rng_bitwise_preserved'] and checks['unmodified_rows_bitwise_preserved'] + assert checks['all_numpy_rng_recovery_exact'] and checks['model_bitwise_unchanged'] + env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1') + command=['python3',str(R/'recovery/train.py'),'--code-dir',str(R/'weekly_synth'), + '--packed',str(R/'packed_sample'),'--source-weights-from',str(R/'packed_sample'), + '--out',str(R/'runs/weekly_synth'),'--initialize-from',str(R/'horizon_delta12k.pt'), + '--steps','12000','--batch','64','--lr','.00002','--seed','197','--loss-mode','paired', + '--stop-file',str(R/'weekly_synth.stop')] + with (R/'weekly_synth_queue.log').open('w') as qlog,(R/'weekly_synth_watch.log').open('w') as wlog: + queued=subprocess.Popen(['python3',str(R/'queued_train.py'),'--label','E97 weekly synthetic coverage seed197', + '--log',str(R/'weekly_synth_train.log'),'--receipt',str(R/'weekly_synth_queue.json'), + '--wait-pid','9354','--require-checkpoint',str(R/'runs/robust_normalization/recovery.pt'), + '--',*command],stdout=qlog,stderr=subprocess.STDOUT,env=env) + watch=subprocess.Popen(['python3',str(R/'watch_evaluate.py'),'--run',str(R/'runs/weekly_synth'), + '--evaluator',str(R/'postloss_inference/evaluate.py'),'--name','weekly_synth', + '--steps','1000,3000,6000,12000'],stdout=wlog,stderr=subprocess.STDOUT,env=env) + print({'queue_pid':queued.pid,'watch_pid':watch.pid},flush=True) + result=queued.wait() + if result:watch.terminate() + watch.wait();raise SystemExit(result) +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/weekly_synth/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/weekly_synth/model.py new file mode 100644 index 0000000000000000000000000000000000000000..3532e5063bd8b5013f6b6e35703707ffef66e00b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member0/training/weekly_synth/model.py @@ -0,0 +1,213 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/model_manifest.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/model_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..ed7d82d53ee418c27f3691dc143ede37891db0ef --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/model_manifest.json @@ -0,0 +1,660 @@ +{ + "name": "direct-seasonal-foundation", + "contract": "timeseries-forecast/v1", + "parameters": 36665488, + "pretrained_assets": [], + "sources_used": [ + "gifteval_pretrain/BEIJING_SUBWAY_30MIN", + "gifteval_pretrain/HZMETRO", + "gifteval_pretrain/LOS_LOOP", + "gifteval_pretrain/PEMS03", + "gifteval_pretrain/PEMS04", + "gifteval_pretrain/PEMS07", + "gifteval_pretrain/PEMS08", + "gifteval_pretrain/PEMS_BAY", + "gifteval_pretrain/Q-TRAFFIC", + "gifteval_pretrain/SHMETRO", + "gifteval_pretrain/alibaba_cluster_trace_2018", + "gifteval_pretrain/australian_electricity_demand", + "gifteval_pretrain/azure_vm_traces_2017", + "gifteval_pretrain/bdg-2_bear", + "gifteval_pretrain/bdg-2_fox", + "gifteval_pretrain/bdg-2_panther", + "gifteval_pretrain/bdg-2_rat", + "gifteval_pretrain/bitcoin_with_missing", + "gifteval_pretrain/borealis", + "gifteval_pretrain/borg_cluster_data_2011", + "gifteval_pretrain/buildings_900k", + "gifteval_pretrain/bull", + "gifteval_pretrain/cdc_fluview_ilinet", + "gifteval_pretrain/cdc_fluview_who_nrevss", + "gifteval_pretrain/china_air_quality", + "gifteval_pretrain/cif_2016_12", + "gifteval_pretrain/cif_2016_6", + "gifteval_pretrain/cmip6_2000", + "gifteval_pretrain/cmip6_2005", + "gifteval_pretrain/cmip6_2010", + "gifteval_pretrain/cockatoo", + "gifteval_pretrain/covid19_energy", + "gifteval_pretrain/covid_mobility", + "gifteval_pretrain/elecdemand", + "gifteval_pretrain/elf", + "gifteval_pretrain/era5_2010", + "gifteval_pretrain/era5_2011", + "gifteval_pretrain/era5_2012", + "gifteval_pretrain/era5_2013", + "gifteval_pretrain/era5_2014", + "gifteval_pretrain/era5_2015", + "gifteval_pretrain/era5_2016", + "gifteval_pretrain/era5_2017", + "gifteval_pretrain/era5_2018", + "gifteval_pretrain/extended_web_traffic_with_missing", + "gifteval_pretrain/favorita_sales", + "gifteval_pretrain/favorita_transactions", + "gifteval_pretrain/gfc12_load", + "gifteval_pretrain/gfc14_load", + "gifteval_pretrain/gfc17_load", + "gifteval_pretrain/godaddy", + "gifteval_pretrain/hog", + "gifteval_pretrain/ideal", + "gifteval_pretrain/kaggle_web_traffic_weekly", + "gifteval_pretrain/kdd2022", + "gifteval_pretrain/largest_2017", + "gifteval_pretrain/largest_2018", + "gifteval_pretrain/largest_2019", + "gifteval_pretrain/largest_2020", + "gifteval_pretrain/largest_2021", + "gifteval_pretrain/lcl", + "gifteval_pretrain/london_smart_meters_with_missing", + "gifteval_pretrain/m1_monthly", + "gifteval_pretrain/m1_quarterly", + "gifteval_pretrain/m1_yearly", + "gifteval_pretrain/m5", + "gifteval_pretrain/monash_m3_monthly", + "gifteval_pretrain/monash_m3_other", + "gifteval_pretrain/monash_m3_quarterly", + "gifteval_pretrain/nn5_daily_with_missing", + "gifteval_pretrain/nn5_weekly", + "gifteval_pretrain/oikolab_weather", + "gifteval_pretrain/pdb", + "gifteval_pretrain/project_tycho", + "gifteval_pretrain/residential_load_power", + "gifteval_pretrain/residential_pv_power", + "gifteval_pretrain/rideshare_with_missing", + "gifteval_pretrain/sceaux", + "gifteval_pretrain/smart", + "gifteval_pretrain/solar_power", + "gifteval_pretrain/spain", + "gifteval_pretrain/subseasonal", + "gifteval_pretrain/subseasonal_precip", + "gifteval_pretrain/sunspot_with_missing", + "gifteval_pretrain/taxi_30min", + "gifteval_pretrain/tourism_quarterly", + "gifteval_pretrain/tourism_yearly", + "gifteval_pretrain/traffic_hourly", + "gifteval_pretrain/traffic_weekly", + "gifteval_pretrain/uber_tlc_daily", + "gifteval_pretrain/uber_tlc_hourly", + "gifteval_pretrain/vehicle_trips_with_missing", + "gifteval_pretrain/wiki-rolling_nips", + "gifteval_pretrain/wind_farms_with_missing", + "gifteval_pretrain/wind_power", + "synthetic:both original and sign-reflected orientations of each sampled allowed or locally generated window; paired quantile loss, seed 197", + "synthetic:both original and sign-reflected orientations of each sampled window, seed 197", + "synthetic:independent sign reflection of sampled allowed-corpus and locally generated windows; seeds 43,47,59,79,89,197", + "synthetic:own direct_v1 Fourier seasons, damped trends, AR noise, changepoints and intermittent demand; seeds 23,43,47,59,79,89,197", + "synthetic:own random requested-horizon prefixes, half of rows retain the full horizon and half use a patch-rounded prefix between one-quarter and the full horizon; independent seed 300200" + ], + "weights_sha256": "308389b7217c080af9eb185559d4ee3cafa0f3e0f8c4dd8f5526b68198c89988", + "config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "training_lineage": [ + { + "checkpoint": "runs/patch8/ema006000.pt", + "sha256": "308389b7217c080af9eb185559d4ee3cafa0f3e0f8c4dd8f5526b68198c89988", + "step": 6000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "patch8_initial.pt" + ] + }, + { + "checkpoint": "patch8_initial.pt", + "sha256": "e7da4d47a9cc984a9423296679d7c9127ef2d679be950b9e8d3758e6fca074cc", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "from_checkpoint": "/run-state/workspace/research/horizon_delta12k.pt", + "from_sha256": "22c08571978be31ba57368eb983089a40a44d56d4ae5e17da41afd2a761a258c", + "method": "fold input/query/recency halves by summation; retain first8 output rows; preserve physical position units", + "exact_function_preservation": false + }, + "parents": [ + "horizon_delta12k.pt", + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "horizon_delta12k.pt", + "sha256": "22c08571978be31ba57368eb983089a40a44d56d4ae5e17da41afd2a761a258c", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/runs/confidence_query/ema006000.pt": "0bad97e8994aac49ea173443db0a4fa8d72d33f9eb9e2660f06de75f7f1403eb", + "/workspace/research/runs/horizon_jitter/ema012000.pt": "830179d763916a1065fc615d2c5e22f4a3b5b19390dde707ab0f057e13cadff6", + "/workspace/research/runs/large_corpus_control/ema012000.pt": "7f9ba5e01ac59c51a3b63d3067b442e23e15d0abc51ddbcccdd04d6083ae4add" + }, + "seconds": 1.2663014469435439 + }, + "parents": [ + "runs/confidence_query/ema006000.pt", + "runs/horizon_jitter/ema012000.pt", + "runs/large_corpus_control/ema012000.pt" + ] + }, + { + "checkpoint": "runs/confidence_query/ema006000.pt", + "sha256": "0bad97e8994aac49ea173443db0a4fa8d72d33f9eb9e2660f06de75f7f1403eb", + "step": 6000, + "seed": 89, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 0.0002, + "steps": 6000 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true + }, + "parents": [ + "runs/recency_features/ema024000.pt" + ] + }, + { + "checkpoint": "runs/horizon_jitter/ema012000.pt", + "sha256": "830179d763916a1065fc615d2c5e22f4a3b5b19390dde707ab0f057e13cadff6", + "step": 12000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "partial_target_lengths": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/large_corpus_control/ema012000.pt", + "sha256": "7f9ba5e01ac59c51a3b63d3067b442e23e15d0abc51ddbcccdd04d6083ae4add", + "step": 12000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/recency_features/ema024000.pt", + "sha256": "1530fbb577a87ca4eb39da83d6fee9b8ee5bc924202e021e3a7b56493112f564", + "step": 24000, + "seed": 59, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/patch16_trial/ema006000.pt" + ] + }, + { + "checkpoint": "runs/recency_features/ema012000.pt", + "sha256": "8ccb6870a025e1097331a3a288b1183741a413f3460fbf3352d0c589c6a4394c", + "step": 12000, + "seed": 59, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/patch16_trial/ema006000.pt" + ] + }, + { + "checkpoint": "runs/patch16_trial/ema006000.pt", + "sha256": "0ff54447074e0271d2e331c7d3e6e9e0fdd73353e4d8cef0175ff627385f71c3", + "step": 6000, + "seed": 47, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024 + }, + "parents": [ + "patch16_init.pt" + ] + }, + { + "checkpoint": "patch16_init.pt", + "sha256": "d69531bfde5bf801e7f36c515bf15fd0cae0bd84f7d1479d35f4a7b67f26b508", + "step": 6000, + "seed": 43, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024 + }, + "conversion": { + "from_checkpoint": "/run-state/workspace/research/runs/large_sign/ema006000.pt", + "from_sha256": "96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547", + "method": "fold input/query halves by summation; retain first 16 output rows; preserve physical positional units" + }, + "parents": [ + "runs/large_sign/ema006000.pt" + ] + }, + { + "checkpoint": "runs/large_sign/ema006000.pt", + "sha256": "96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547", + "step": 6000, + "seed": 43, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 32, + "max_context": 4096, + "max_horizon": 1024 + }, + "parents": [ + "runs/direct_large/step024000.pt" + ] + }, + { + "checkpoint": "runs/direct_large/step024000.pt", + "sha256": "b7e4f38aebcd2cf38ce484edaad8d19851317fb3b8df485e2faa0d0423cbcb48", + "step": 24000, + "seed": 23, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 128, + "lr": 0.0002, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 32, + "max_context": 4096, + "max_horizon": 1024 + }, + "initialization": "random initialization in this workspace" + } + ], + "symmetric_averaging": true, + "seasonal_gate": { + "variance_ratio_threshold": 0.25, + "maximum_weight": 0.98, + "cycles_averaged": 4, + "template_mode": "aligned", + "amplitude_ratio_clip": [ + 0.5, + 2.0 + ], + "latest_cycle_minimum_coverage": 0.75, + "variance_noise_correction": "mean squared seasonal differences / 2" + }, + "continuity": { + "decay_steps": 24, + "variance_ratio_threshold": 0.5, + "maximum_weight": 0.95, + "lookback": 512, + "slope_median_differences": 8 + }, + "notes": "All training lineage originates from random initialization here, using only the declared corpus and locally generated series. Validation was used only for selection and diagnostics. Context transformations are fixed formulas; there is no inference-time fitting or parameter adaptation.", + "runtime_code_sha256": { + "model.py": "c27748fa4b1186b513f76eca26052753b8dcd1794994e5989addaf371ca70f2e", + "infer.sh": "5fe66b4fe9a4787285d830cfd96975701e97286a75ba7c3687bd8891475edf68", + "continuity.py": "dbb08d2229ad80ad00f638b0b9f2f6ca13c663e0fd6730058e5fee8ff54545d5", + "ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "zero_mass.py": "f079d509009bcda409b80eb64467c869b838cfbab11b2bd4c660c2875b6642fe", + "seasonal.py": "b946e63048196ab5ea8b249137d48c80d8510943caccd0f180e4fb86d9b24b37", + "predict.py": "9bde896945a2cd8f892e7eeb6328ed2dfda09293532f3a4a64d929c9943614ef" + }, + "final_training_stage": { + "trainable_scope": "all parameters", + "sign_loss": "paired", + "learning_rate_multipliers": {} + }, + "trend_summary": { + "fixed_averaging_width": 128, + "matches_all_pretraining_context_widths": true, + "independent_of_batch_padding": true + }, + "zero_mass_projection": { + "threshold_in_context_standard_deviations": 0.4, + "nonnegative_context_required": true, + "minimum_exact_zeros": 4, + "minimum_zero_fraction": 0.1, + "context_cap": 4096 + }, + "recency_features": { + "query_projection_parameters": 16384, + "latest_vs_four_cycle_level": true, + "amplitude_ratio_clip": [ + 0.5, + 2.0 + ], + "minimum_observed_cycles": 3 + }, + "confidence_features": { + "query_projection_parameters": 3072, + "backbone_frozen_during_projection_training": true, + "training_objective": "weighted quantile and median loss after averaging both sign orientations", + "statistics": [ + "mean absolute difference", + "root mean square difference" + ], + "lags": "one and the two frequency-derived periods", + "lookback": "512 for lag one; eight cycles for seasonal lags", + "minimum_valid_pairs": 8, + "insufficient_pair_defaults": [ + 1, + 1.4142135623730951 + ], + "statistic_clip": 10, + "transform": "log1p", + "stage_scope": "Frozen-backbone details refer to projection introduction; subsequent updates are recorded in training_lineage.training_settings." + }, + "partial_target_training": { + "available_horizon": "last finite training-label position rounded up to the patch boundary", + "decoder_future_key_mask": true, + "per_row_horizon_metadata": true, + "inference_uses_requested_horizon_only": true + }, + "training_provenance_code_sha256": { + "confidence_query/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "confidence_query/model.py": "b4f11ba2018e2b50879cdc33acf0138301548971508b58035a7c96a29aaa6f2d", + "confidence_query/train.py": "fc8a7555a5a6b0a6f91e80ac8cc9cbbfddaa2b26468c57f49dfb17671b22ce93", + "direct_large/data.py": "6e6db217936f8dd79380d2ceff3eaa8598a44f1b60b17acae7bfde2363116847", + "direct_large/evaluate.py": "eaea99e8cd44c9f7c70a45fa9abf51354ae5449dbad273fcb55e48ad02652223", + "direct_large/model.py": "146d93a3f95b13bda8b1b437bc36621b91356cf946e94f62999f89e7fb348071", + "direct_large/pack.py": "3bcc4ce9eb3361ad741ceebd7efce7a2fb86fb49543f52c72aabd0e3e8cd17ce", + "direct_large/predict.py": "930a9f18f9f5da47c03859698c9d2f5567d1e1c73fd61edac1ed20b3a6f9bb50", + "direct_large/publish.py": "3c167f33e8571731c26f1cb70168eda54ef9cb4c76423dfd374240b75ca5f106", + "direct_large/record.py": "b3b00b0ed14bc3af00c7b1ad97195238ecb8f06e96bc41f0c07913bc3f6ed949", + "direct_large/train.py": "b9ad6b2adddeaf12961b529d6535dd33f6d044a31979b5c9e49dceafbadd3ac0", + "direct_large/ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "direct_large/validation_subset.py": "8d3eb9d3f3aa124368761ef402ff066935c0be31a62b25b8551a45dcb922e28d", + "full_paired/check.py": "90ac1c78846439d51ab8acd62a19bd536c7c394bd02e94f6d5ff17c0af8bd116", + "full_paired/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "full_paired/model.py": "c27748fa4b1186b513f76eca26052753b8dcd1794994e5989addaf371ca70f2e", + "horizon_jitter/data.py": "5044cf648323420095ed6058d29f837c07ff5559b606df8b00cc8d1e95c8b58e", + "horizon_jitter/model.py": "186bb282236f23cc665a012194d26e58f51004c680393352ec053f5308f1240f", + "horizon_jitter/train.py": "4e9cbca1293f18f7eea2c72dba127815c0934a13c86e8f6cc881a749676d41a6", + "large_corpus/data.py": "27c078cb0ed085717a364f556b5ff976fd803d5af37612cf3a03a0a3ca12a678", + "large_corpus/model.py": "e3a1bc01e89a0d6d750ede2cc969272ad01e1ca580b174af7dee00db029f1cf7", + "large_corpus/train.py": "3baca16c3945e6ef241ccbc9c13644539e3c265f71095cbbaa61a3d338e4fafe", + "large_sign/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "large_sign/evaluate.py": "eaea99e8cd44c9f7c70a45fa9abf51354ae5449dbad273fcb55e48ad02652223", + "large_sign/model.py": "3fff6445a1982a1b3c92f06a9b5f1bb627dda6a291b0b2364bcfb1a6457830d7", + "large_sign/pack.py": "3bcc4ce9eb3361ad741ceebd7efce7a2fb86fb49543f52c72aabd0e3e8cd17ce", + "large_sign/predict.py": "930a9f18f9f5da47c03859698c9d2f5567d1e1c73fd61edac1ed20b3a6f9bb50", + "large_sign/publish.py": "3c167f33e8571731c26f1cb70168eda54ef9cb4c76423dfd374240b75ca5f106", + "large_sign/record.py": "b3b00b0ed14bc3af00c7b1ad97195238ecb8f06e96bc41f0c07913bc3f6ed949", + "large_sign/train.py": "a597f40ab87cce04e96dc654d12e56cdf40ffd87f00034d8bc4d56dff4eb7c68", + "large_sign/ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "large_sign/validation_subset.py": "8d3eb9d3f3aa124368761ef402ff066935c0be31a62b25b8551a45dcb922e28d", + "partial_delta/merge.py": "63984a0f46f7d48817037f5bf5a1c9319e45a9b1924cde62c667ac49ce47532e", + "partial_targets/data.py": "27c078cb0ed085717a364f556b5ff976fd803d5af37612cf3a03a0a3ca12a678", + "partial_targets/model.py": "186bb282236f23cc665a012194d26e58f51004c680393352ec053f5308f1240f", + "partial_targets/train.py": "3baca16c3945e6ef241ccbc9c13644539e3c265f71095cbbaa61a3d338e4fafe", + "patch16/convert.py": "11e1d30100ab25311020ac1f4ab8227ec66156836df5de613300867977091c45", + "patch16/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "patch16/evaluate.py": "eaea99e8cd44c9f7c70a45fa9abf51354ae5449dbad273fcb55e48ad02652223", + "patch16/model.py": "8031c597b354eb2cf464140bee40c3ec8dff86c775b5c55c5ce910302b443582", + "patch16/pack.py": "3bcc4ce9eb3361ad741ceebd7efce7a2fb86fb49543f52c72aabd0e3e8cd17ce", + "patch16/predict.py": "930a9f18f9f5da47c03859698c9d2f5567d1e1c73fd61edac1ed20b3a6f9bb50", + "patch16/publish.py": "3c167f33e8571731c26f1cb70168eda54ef9cb4c76423dfd374240b75ca5f106", + "patch16/record.py": "b3b00b0ed14bc3af00c7b1ad97195238ecb8f06e96bc41f0c07913bc3f6ed949", + "patch16/train.py": "3156710f76111a31447cbe638ee27fe2811d060917aa083aab0b5134d98accf8", + "patch16/ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "patch16/validation_subset.py": "8d3eb9d3f3aa124368761ef402ff066935c0be31a62b25b8551a45dcb922e28d", + "patch8/convert.py": "9edaa0c8349310b7419d649fb4f21dd3ddb9067ebe984d5df3701a234be73780", + "patch8/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "patch8/memory_check.py": "78e8e5cca960bf1225ec0104980363c82f4c3c13c2d77ed154cea37a5b6f3fd1", + "patch8/model.py": "c27748fa4b1186b513f76eca26052753b8dcd1794994e5989addaf371ca70f2e", + "recency_features/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "recency_features/model.py": "e3a1bc01e89a0d6d750ede2cc969272ad01e1ca580b174af7dee00db029f1cf7", + "recency_features/train.py": "a654b9a27b6c27141e1d4e517ab28fcae3f2c23d061742fa2f6c01e3d23c8a00", + "recovery/capacity_curves.py": "2bdc6635705b70a868e115cd13eb529563acacf6f47c71f250a50dce8e943be4", + "recovery/exposure_audit.py": "54c194a626b8876ece84686b39b22360155c9fada7248a393ca9b7d6ee38002b", + "recovery/relaunch_20261022b.py": "f90ddd77928a793c8e151ba74cfa9cc84c8aefad0c0d943a833c74bc07b79313", + "recovery/relaunch_20261023.py": "a4c40c5674b0d05cfe9bb1fffe907f02dec16c53cbddb8b86efbba1b96649097", + "recovery/schedules.py": "7748fd6b2bbbe64037472faf7e6583d03cf339138d2f3c07b1bac9e65bf2d4f5", + "recovery/snapshot.py": "0f241a7e139e47ffff7efea40572205fd84c12efe6fb3c2dccd87c50d678a6c3", + "recovery/train.py": "63bee736565af670877b4cd7c75015fab06a18c66bbe132b0bb3faff5ebd80c7" + } +} diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/confidence_query/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/confidence_query/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/confidence_query/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/confidence_query/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/confidence_query/model.py new file mode 100644 index 0000000000000000000000000000000000000000..b881039b3752b3396e06415a8d01d24956fa29a7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/confidence_query/model.py @@ -0,0 +1,190 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + if self.recency is not None: + pos=torch.arange(c,device=z.device)[None,:];extras=[] + for j in range(2): + period=periods[:,j:j+1] + recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + n=ctx.shape[0] + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1]) + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/confidence_query/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/confidence_query/train.py new file mode 100644 index 0000000000000000000000000000000000000000..fd9d2a3a0502cee1a67c41c832266c7f87cc5a80 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/confidence_query/train.py @@ -0,0 +1,54 @@ +"""Train only confidence-query features on a frozen model, using paired-sign forecast loss.""" +import argparse,json,math,time,os +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) +ap.add_argument('--initialize-from',required=True);ap.add_argument('--steps',type=int,default=6000) +ap.add_argument('--batch',type=int,default=128);ap.add_argument('--lr',type=float,default=2e-4) +ap.add_argument('--seed',type=int,default=89);ap.add_argument('--save-every',type=int,default=1000);a=ap.parse_args() +torch.set_num_threads(1);torch.manual_seed(a.seed);torch.backends.cuda.matmul.allow_tf32=True +out=Path(a.out);out.mkdir(parents=True,exist_ok=True) +ck=torch.load(a.initialize_from,map_location='cpu',weights_only=False) +config={**ck['config'],'confidence_features':True};model=DirectForecaster(**config).cuda() +missing,unexpected=model.load_state_dict(ck['model'],strict=False) +assert not unexpected and all(k.startswith('confidence.') for k in missing) +for name,param in model.named_parameters():param.requires_grad_(name.startswith('confidence.')) +params=[p for p in model.parameters() if p.requires_grad] +opt=torch.optim.AdamW(params,lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) +ema={k:v.detach().clone() for k,v in model.state_dict().items()};sampler=Sampler(a.packed,seed=a.seed) +(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)) +rng=np.random.default_rng(a.seed) +def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) +def save(step): + for prefix,weights in [('step',model.state_dict()),('ema',ema)]: + state={'model':weights,'config':model.config,'step':step,'args':vars(a),'ema':prefix=='ema'} + path=out/f'{prefix}{step:06d}.pt';torch.save(state,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) +save(0);pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] +for step in range(1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch);x,y,p=[torch.from_numpy(x).cuda() for x in arrays] + lr=a.lr*min(1,step/200)*(.2+.8*.5*(1+math.cos(math.pi*step/a.steps))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(params,1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items(): + if k.startswith('confidence.'):ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + if step%a.save_every==0 or step==a.steps:save(step) +pool.shutdown() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/direct_large/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/direct_large/data.py new file mode 100644 index 0000000000000000000000000000000000000000..2378e33d7352ba5ad97d566148782e63e64b367c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/direct_large/data.py @@ -0,0 +1,71 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + return ctx,tgt,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/direct_large/evaluate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/direct_large/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..05f086d4d84def4a48165f9e65d2948877675e56 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/direct_large/evaluate.py @@ -0,0 +1,16 @@ +import sys,json,argparse,time,hashlib +from pathlib import Path +import torch +from predict import load_model,run +sys.path.insert(0,'/workspace/evaluation') +from score import score,json_safe + +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);ap.add_argument('--valid',default='/workspace/research/valid_screen');ap.add_argument('--baseline',default='/workspace/research/valid_screen/baseline.json');a=ap.parse_args() +torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cuda.matmul.allow_tf32=False +t0=time.time();out=Path(a.out);v=Path(a.valid) +run(load_model(a.weights),v/'input',out) +base=json.loads(Path(a.baseline).read_text())['configs'] +rep=score(v/'truth',out,base) +rep['checkpoint_sha256']=hashlib.sha256(Path(a.weights).read_bytes()).hexdigest();rep['eval_seconds']=time.time()-t0 +(out/'report.json').write_text(json.dumps(json_safe(rep),indent=1)) +print(json.dumps({k:rep[k] for k in ('skill_score','rel_mase_gmean','rel_wql_gmean','n_failed','groups','eval_seconds')},indent=1)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/direct_large/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/direct_large/model.py new file mode 100644 index 0000000000000000000000000000000000000000..7a224cc12a159446a1e427b2052b53d1d1f7e83e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/direct_large/model.py @@ -0,0 +1,142 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional(torch.arange(-nt,0,device=z.device),self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + q=self.query(base.reshape(b,h//p,p*9))+positional(torch.arange(h//p,device=z.device),self.d)[None]+emb + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + pin=torch.maximum(levels*err,(levels-1)*err).mean(-1) + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + return per.mean() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/direct_large/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/direct_large/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/direct_large/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/direct_large/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/direct_large/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..e20c6630475d6b4fa6906eb4ed9454b7b5aeec2c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/direct_large/predict.py @@ -0,0 +1,43 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):q=model.predict(x,p,h).float().cpu().numpy() + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/direct_large/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/direct_large/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf95c9aec5936076b881c340edb960786f2d40d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/direct_large/publish.py @@ -0,0 +1,31 @@ +"""Assemble a relocatable package, then atomically exchange complete directories.""" +import json,os,shutil,ctypes,hashlib,argparse +from pathlib import Path +import torch +HERE=Path(__file__).resolve().parent + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',default='/workspace/submission');ap.add_argument('--report',required=True);ap.add_argument('--experiments',default=str(HERE/'EXPERIMENTS.md'));a=ap.parse_args() + final=Path(a.out);staging=final.parent/f'.{final.name}-staging-{os.getpid()}' + shutil.rmtree(staging,ignore_errors=True);staging.mkdir(parents=True) + for file in ('model.py','predict.py','infer.sh','ts_io.py'): + shutil.copy(HERE/file,staging/file) + shutil.copy(a.weights,staging/'weights.pt');shutil.copy('/opt/runtime/requirements.txt',staging/'requirements.txt') + ck=torch.load(a.weights,map_location='cpu',weights_only=False);digest=hashlib.sha256((staging/'weights.pt').read_bytes()).hexdigest() + sources=json.loads(Path('/workspace/research/packed_sample/meta.json').read_text())['dirs'] + manifest={'name':'direct-seasonal-quantile-v1','contract':'timeseries-forecast/v1','parameters':sum(x.numel() for x in ck['model'].values()),'pretrained_assets':[],'sources_used':[f'gifteval_pretrain/{d}' for d in sources]+['synthetic:direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; data.py generator seed 17'],'weights_sha256':digest,'training_step':ck['step'],'config':ck['config'],'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.'} + (staging/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') + (staging/'config.json').write_text(json.dumps(ck['config'],indent=2)+'\n') + shutil.copy(a.experiments,staging/'EXPERIMENTS.md');shutil.copy(a.report,staging/'validation_report.json') + # Include generator/sampler provenance, which is not imported by inference. + (staging/'provenance').mkdir() + for file in ('pack.py','data.py','train.py'):shutil.copy(HERE/file,staging/'provenance'/file) + (staging/'README.md').write_text('# Direct seasonal quantile foundation forecaster\n\nRun `bash infer.sh INPUT_DIR OUTPUT_DIR`. This package contains all inference assets and uses only its supplied input directory. The 6.76M 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.\n\nThe 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.\n') + if final.exists(): + libc=ctypes.CDLL(None,use_errno=True) + if libc.renameat2(-100,os.fsencode(staging),-100,os.fsencode(final),2):raise OSError(ctypes.get_errno(),os.strerror(ctypes.get_errno())) + shutil.rmtree(staging) + else:os.replace(staging,final) + print(json.dumps(manifest,indent=1)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/direct_large/record.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/direct_large/record.py new file mode 100644 index 0000000000000000000000000000000000000000..1850a33f46fa3ee4d78cac4a5d6152404801a131 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/direct_large/record.py @@ -0,0 +1,9 @@ +import argparse,json,math +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('report');ap.add_argument('--label',required=True);ap.add_argument('--outcome',default='Screened for model selection.');a=ap.parse_args() +r=json.loads(Path(a.report).read_text());p=Path(__file__).with_name('EXPERIMENTS.md') +lines=[f'\n## {a.label}',f'- Checkpoint SHA-256: `{r.get("checkpoint_sha256","see model_manifest.json")}`.',f'- Evaluation: {r["n_configs"]} configurations, {r["n_instances"]} instances, {r["n_failed"]} failed configurations; {r.get("eval_seconds","not separately timed")} seconds.',f'- Overall skill {r["skill_score"]:.6f}; relative MASE {r["rel_mase_gmean"]:.6f}; relative WQL {r["rel_wql_gmean"]:.6f}.'] +for group,entries in r['groups'].items(): + lines.append(f'- {group} skill: '+', '.join(f'{k}={1-math.sqrt(v["rel_mase_gmean"]*v["rel_wql_gmean"]):.4f}' for k,v in entries.items())+'.') +lines.append('- Outcome: '+a.outcome) +with p.open('a') as f:f.write('\n'.join(lines)+'\n') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/direct_large/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/direct_large/train.py new file mode 100644 index 0000000000000000000000000000000000000000..a2ccc736bfef804259199a2dd315347d9854b680 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/direct_large/train.py @@ -0,0 +1,67 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(6);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/direct_large/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/direct_large/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/direct_large/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/direct_large/validation_subset.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/direct_large/validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..4df83e69c4f9a3365955e5d17ffcfc0af71372b7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/direct_large/validation_subset.py @@ -0,0 +1,18 @@ +"""Model-selection-only subset spanning all 97 configurations, seed 2026.""" +import sys,json,copy +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +import ts_io + +root=Path('/workspace/data/valid');out=Path('/workspace/research/valid_screen') +idx=json.loads((root/'input/index.json').read_text());new=copy.deepcopy(idx);rng=np.random.default_rng(2026) +for cfg in new['configs']: + cid=cfg['config_id'];case=ts_io.CaseFile(root/'input/cases'/f'{cid}.h5') + ids=np.sort(rng.choice(case.n,min(case.n,192),replace=False)) + ts_io.write_case_subset(case,ids,out/'input/cases'/f'{cid}.h5') + lab,se,meta=ts_io.read_truth_file(root/'truth/cases'/f'{cid}.h5') + ts_io.write_truth_file(out/'truth/cases'/f'{cid}.h5',lab[ids],se[ids],meta) + cfg['n_instances']=len(ids);case.close() +for kind in ('input','truth'):(out/kind/'index.json').write_text(json.dumps(new,indent=1)) +print('screen instances',sum(c['n_instances'] for c in new['configs'])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/full_paired/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/full_paired/check.py new file mode 100644 index 0000000000000000000000000000000000000000..fda928e16338305fd9912f7bc08cacff58bd8aa4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/full_paired/check.py @@ -0,0 +1,34 @@ +import importlib.util,json,time +from pathlib import Path +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +r=Path('/workspace/research');torch.set_num_threads(1);torch.manual_seed(197);start=time.monotonic() +ck=torch.load(r/'horizon_delta12k.pt',map_location='cpu',weights_only=False) +spec=importlib.util.spec_from_file_location('parent_model',r/'confidence_inference/model.py') +old=importlib.util.module_from_spec(spec);spec.loader.exec_module(old) +parent=old.DirectForecaster(**ck['config']);parent.load_state_dict(ck['model']) +m=DirectForecaster(**ck['config']);m.load_state_dict(ck['model']) +x=torch.randn(4,512);x[0,:50]=float('nan');p=torch.tensor([[24,168]]*4);y=torch.randn(4,128);y[0,32:]=float('nan') +with torch.inference_mode(): + assert all(torch.equal(a,b) for a,b in zip(m(x,p,48),parent(x,p,48))) + short=m(x,p,32)[0];long=m(x,p,128,forecast_lengths=torch.full((4,),32))[0][:,:32] + assert torch.allclose(short,long,atol=3e-6,rtol=1e-6),(short-long).abs().max() + paired=float(loss_fn(m,x,y,p,paired=True));reverse=float(loss_fn(m,-x,-y,p,paired=True)) + assert abs(paired-reverse)<1e-7,(paired,reverse) +a=Sampler(r/'packed_sample',197);b=Sampler(r/'packed_sample',197) +for c,h in [(512,32),(4096,1024)]: + assert all(np.array_equal(v,w,equal_nan=True) for v,w in zip(a.sample(16,c,h),b.sample(16,c,h))) +assert a.rng.bit_generator.state==b.rng.bit_generator.state and a.horizon_rng.bit_generator.state==b.horizon_rng.bit_generator.state +cpu=time.monotonic()-start;del parent,ck,a,b +m=m.cuda();ema={k:v.detach().clone() for k,v in m.state_dict().items()} +moments=[torch.zeros_like(v) for v in m.parameters() for _ in range(2)] +torch.backends.cuda.matmul.allow_tf32=True;torch.cuda.reset_peak_memory_stats();start=time.monotonic() +x=torch.randn(64,4096,device='cuda');y=torch.randn(64,1024,device='cuda');p=torch.tensor([[24,168]]*64,device='cuda') +with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(m,x,y,p,paired=True) +loss.backward();torch.cuda.synchronize() +assert torch.isfinite(loss) and all(v.grad is not None and torch.isfinite(v.grad).all() for v in m.parameters()) +z={'cpu_seconds':cpu,'initial_forecast_bitwise_parent':True,'unused_future_tokens_do_not_change_requested_prefix':True,'paired_loss_sign_symmetric':True,'matched_sampler_main_and_horizon_rng':True,'gpu_fixture_seconds':time.monotonic()-start,'allocated_mib':torch.cuda.max_memory_allocated()/2**20,'reserved_mib':torch.cuda.max_memory_reserved()/2**20,'optimizer_updates':0} +(r/'full_paired_checks.json').write_text(json.dumps(z,indent=2));print(json.dumps(z),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/full_paired/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/full_paired/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/full_paired/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/full_paired/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/full_paired/model.py new file mode 100644 index 0000000000000000000000000000000000000000..dedcdff4698028a8ba655865f8425d0dc3ef0dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/full_paired/model.py @@ -0,0 +1,204 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/horizon_jitter/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/horizon_jitter/data.py new file mode 100644 index 0000000000000000000000000000000000000000..3d632af7e96a71f30b7964a2b3fd73bc1c3f3f3e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/horizon_jitter/data.py @@ -0,0 +1,86 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/horizon_jitter/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/horizon_jitter/model.py new file mode 100644 index 0000000000000000000000000000000000000000..4ffe50d9aadf21d73949e2052ceb7f3642bf65d3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/horizon_jitter/model.py @@ -0,0 +1,180 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(ctx,periods,target.shape[-1],forecast_lengths=lengths) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/horizon_jitter/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/horizon_jitter/train.py new file mode 100644 index 0000000000000000000000000000000000000000..768d33da4421b24bd760d7d9680d0c2cd9bd84e4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/horizon_jitter/train.py @@ -0,0 +1,74 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler,truncate_targets + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + horizon_rng=np.random.default_rng(a.seed+startstep+300003) + def nextbatch(): + 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])) + return truncate_targets(sampler.sample(a.batch,c,h),horizon_rng,a.patch) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_corpus/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_corpus/data.py new file mode 100644 index 0000000000000000000000000000000000000000..a51e912d3c4b63a3ec0cd85133bf0e7aa3429569 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_corpus/data.py @@ -0,0 +1,73 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_corpus/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_corpus/model.py new file mode 100644 index 0000000000000000000000000000000000000000..f8271c5b0bf9a5edb961e1c7839761fe50a2e40b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_corpus/model.py @@ -0,0 +1,171 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024,recency_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + if self.recency is not None: + pos=torch.arange(c,device=z.device)[None,:];extras=[] + for j in range(2): + period=periods[:,j:j+1] + recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_corpus/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_corpus/train.py new file mode 100644 index 0000000000000000000000000000000000000000..2e77612e443d78dd80bcb6a0cc6d01169f61a3a4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_corpus/train.py @@ -0,0 +1,73 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_sign/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_sign/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_sign/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_sign/evaluate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_sign/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..05f086d4d84def4a48165f9e65d2948877675e56 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_sign/evaluate.py @@ -0,0 +1,16 @@ +import sys,json,argparse,time,hashlib +from pathlib import Path +import torch +from predict import load_model,run +sys.path.insert(0,'/workspace/evaluation') +from score import score,json_safe + +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);ap.add_argument('--valid',default='/workspace/research/valid_screen');ap.add_argument('--baseline',default='/workspace/research/valid_screen/baseline.json');a=ap.parse_args() +torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cuda.matmul.allow_tf32=False +t0=time.time();out=Path(a.out);v=Path(a.valid) +run(load_model(a.weights),v/'input',out) +base=json.loads(Path(a.baseline).read_text())['configs'] +rep=score(v/'truth',out,base) +rep['checkpoint_sha256']=hashlib.sha256(Path(a.weights).read_bytes()).hexdigest();rep['eval_seconds']=time.time()-t0 +(out/'report.json').write_text(json.dumps(json_safe(rep),indent=1)) +print(json.dumps({k:rep[k] for k in ('skill_score','rel_mase_gmean','rel_wql_gmean','n_failed','groups','eval_seconds')},indent=1)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_sign/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_sign/model.py new file mode 100644 index 0000000000000000000000000000000000000000..60aeb14b5f4fa298521ddce8a3276d076c1bb631 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_sign/model.py @@ -0,0 +1,154 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional(torch.arange(-nt,0,device=z.device),self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + q=self.query(base.reshape(b,h//p,p*9))+positional(torch.arange(h//p,device=z.device),self.d)[None]+emb + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_sign/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_sign/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_sign/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_sign/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_sign/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..e20c6630475d6b4fa6906eb4ed9454b7b5aeec2c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_sign/predict.py @@ -0,0 +1,43 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):q=model.predict(x,p,h).float().cpu().numpy() + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_sign/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_sign/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf95c9aec5936076b881c340edb960786f2d40d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_sign/publish.py @@ -0,0 +1,31 @@ +"""Assemble a relocatable package, then atomically exchange complete directories.""" +import json,os,shutil,ctypes,hashlib,argparse +from pathlib import Path +import torch +HERE=Path(__file__).resolve().parent + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',default='/workspace/submission');ap.add_argument('--report',required=True);ap.add_argument('--experiments',default=str(HERE/'EXPERIMENTS.md'));a=ap.parse_args() + final=Path(a.out);staging=final.parent/f'.{final.name}-staging-{os.getpid()}' + shutil.rmtree(staging,ignore_errors=True);staging.mkdir(parents=True) + for file in ('model.py','predict.py','infer.sh','ts_io.py'): + shutil.copy(HERE/file,staging/file) + shutil.copy(a.weights,staging/'weights.pt');shutil.copy('/opt/runtime/requirements.txt',staging/'requirements.txt') + ck=torch.load(a.weights,map_location='cpu',weights_only=False);digest=hashlib.sha256((staging/'weights.pt').read_bytes()).hexdigest() + sources=json.loads(Path('/workspace/research/packed_sample/meta.json').read_text())['dirs'] + manifest={'name':'direct-seasonal-quantile-v1','contract':'timeseries-forecast/v1','parameters':sum(x.numel() for x in ck['model'].values()),'pretrained_assets':[],'sources_used':[f'gifteval_pretrain/{d}' for d in sources]+['synthetic:direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; data.py generator seed 17'],'weights_sha256':digest,'training_step':ck['step'],'config':ck['config'],'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.'} + (staging/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') + (staging/'config.json').write_text(json.dumps(ck['config'],indent=2)+'\n') + shutil.copy(a.experiments,staging/'EXPERIMENTS.md');shutil.copy(a.report,staging/'validation_report.json') + # Include generator/sampler provenance, which is not imported by inference. + (staging/'provenance').mkdir() + for file in ('pack.py','data.py','train.py'):shutil.copy(HERE/file,staging/'provenance'/file) + (staging/'README.md').write_text('# Direct seasonal quantile foundation forecaster\n\nRun `bash infer.sh INPUT_DIR OUTPUT_DIR`. This package contains all inference assets and uses only its supplied input directory. The 6.76M 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.\n\nThe 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.\n') + if final.exists(): + libc=ctypes.CDLL(None,use_errno=True) + if libc.renameat2(-100,os.fsencode(staging),-100,os.fsencode(final),2):raise OSError(ctypes.get_errno(),os.strerror(ctypes.get_errno())) + shutil.rmtree(staging) + else:os.replace(staging,final) + print(json.dumps(manifest,indent=1)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_sign/record.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_sign/record.py new file mode 100644 index 0000000000000000000000000000000000000000..1850a33f46fa3ee4d78cac4a5d6152404801a131 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_sign/record.py @@ -0,0 +1,9 @@ +import argparse,json,math +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('report');ap.add_argument('--label',required=True);ap.add_argument('--outcome',default='Screened for model selection.');a=ap.parse_args() +r=json.loads(Path(a.report).read_text());p=Path(__file__).with_name('EXPERIMENTS.md') +lines=[f'\n## {a.label}',f'- Checkpoint SHA-256: `{r.get("checkpoint_sha256","see model_manifest.json")}`.',f'- Evaluation: {r["n_configs"]} configurations, {r["n_instances"]} instances, {r["n_failed"]} failed configurations; {r.get("eval_seconds","not separately timed")} seconds.',f'- Overall skill {r["skill_score"]:.6f}; relative MASE {r["rel_mase_gmean"]:.6f}; relative WQL {r["rel_wql_gmean"]:.6f}.'] +for group,entries in r['groups'].items(): + lines.append(f'- {group} skill: '+', '.join(f'{k}={1-math.sqrt(v["rel_mase_gmean"]*v["rel_wql_gmean"]):.4f}' for k,v in entries.items())+'.') +lines.append('- Outcome: '+a.outcome) +with p.open('a') as f:f.write('\n'.join(lines)+'\n') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_sign/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_sign/train.py new file mode 100644 index 0000000000000000000000000000000000000000..d089166fb1612ddf4955fcd2f096cb0b33624dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_sign/train.py @@ -0,0 +1,70 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(3);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_sign/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_sign/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_sign/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_sign/validation_subset.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_sign/validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..4df83e69c4f9a3365955e5d17ffcfc0af71372b7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/large_sign/validation_subset.py @@ -0,0 +1,18 @@ +"""Model-selection-only subset spanning all 97 configurations, seed 2026.""" +import sys,json,copy +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +import ts_io + +root=Path('/workspace/data/valid');out=Path('/workspace/research/valid_screen') +idx=json.loads((root/'input/index.json').read_text());new=copy.deepcopy(idx);rng=np.random.default_rng(2026) +for cfg in new['configs']: + cid=cfg['config_id'];case=ts_io.CaseFile(root/'input/cases'/f'{cid}.h5') + ids=np.sort(rng.choice(case.n,min(case.n,192),replace=False)) + ts_io.write_case_subset(case,ids,out/'input/cases'/f'{cid}.h5') + lab,se,meta=ts_io.read_truth_file(root/'truth/cases'/f'{cid}.h5') + ts_io.write_truth_file(out/'truth/cases'/f'{cid}.h5',lab[ids],se[ids],meta) + cfg['n_instances']=len(ids);case.close() +for kind in ('input','truth'):(out/kind/'index.json').write_text(json.dumps(new,indent=1)) +print('screen instances',sum(c['n_instances'] for c in new['configs'])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/partial_delta/merge.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/partial_delta/merge.py new file mode 100644 index 0000000000000000000000000000000000000000..3dde47d52d25ed2b013942b3887f1bf686e42ed8 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/partial_delta/merge.py @@ -0,0 +1,16 @@ +"""Apply the difference of two matched, locally trained checkpoints to our selected model.""" +import argparse,torch,hashlib,json,time +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('--base',required=True);ap.add_argument('--candidate',required=True);ap.add_argument('--control',required=True);ap.add_argument('--out',required=True);a=ap.parse_args() +torch.set_num_threads(1);start=time.monotonic() +base=torch.load(a.base,map_location='cpu',weights_only=False);candidate=torch.load(a.candidate,map_location='cpu',weights_only=False);control=torch.load(a.control,map_location='cpu',weights_only=False) +assert set(candidate['model'])==set(control['model']) +weights={k:v.clone() for k,v in base['model'].items()} +for k in candidate['model']: + assert k in weights and weights[k].shape==candidate['model'][k].shape==control['model'][k].shape + weights[k].add_(candidate['model'][k]-control['model'][k]) +assert all(torch.isfinite(v).all() for v in weights.values()) +parents=[a.base,a.candidate,a.control] +conversion={'method':'matched training delta','formula':'base + candidate - control','coefficient':1.0,'parent_hashes':{p:hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in parents},'seconds':time.monotonic()-start} +ck={'model':weights,'config':base['config'],'step':0,'args':{'packed':base['args']['packed']},'parent_checkpoints':parents,'conversion':conversion} +torch.save(ck,a.out);print(json.dumps(conversion)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/partial_targets/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/partial_targets/data.py new file mode 100644 index 0000000000000000000000000000000000000000..a51e912d3c4b63a3ec0cd85133bf0e7aa3429569 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/partial_targets/data.py @@ -0,0 +1,73 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/partial_targets/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/partial_targets/model.py new file mode 100644 index 0000000000000000000000000000000000000000..4ffe50d9aadf21d73949e2052ceb7f3642bf65d3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/partial_targets/model.py @@ -0,0 +1,180 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(ctx,periods,target.shape[-1],forecast_lengths=lengths) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/partial_targets/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/partial_targets/train.py new file mode 100644 index 0000000000000000000000000000000000000000..2e77612e443d78dd80bcb6a0cc6d01169f61a3a4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/partial_targets/train.py @@ -0,0 +1,73 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/convert.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/convert.py new file mode 100644 index 0000000000000000000000000000000000000000..b2cbc8fc919be6a77eca9ab19c4faa06060a2e0d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/convert.py @@ -0,0 +1,18 @@ +"""Convert only our own trained checkpoint from 32- to 16-point patches. + +Context/query projections fold the two halves by summation, preserving the +embedding of constant features. The output projection keeps the first half. +Attention/MLP weights are inherited unchanged; position units remain 32 points. +""" +import argparse,torch,hashlib +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('--input',required=True);ap.add_argument('--output',required=True);a=ap.parse_args() +ck=torch.load(a.input,map_location='cpu',weights_only=False);state=ck['model'];d=ck['config']['d'];assert ck['config']['patch']==32 +old=state['embed.0.weight'].reshape(d,2,32);state['embed.0.weight']=(old[:,:,:16]+old[:,:,16:]).reshape(d,32) +old=state['query.0.weight'].reshape(d,32,9);state['query.0.weight']=(old[:,:16]+old[:,16:]).reshape(d,16*9) +state['head.weight']=state['head.weight'].reshape(32,18,d)[:16].reshape(16*18,d).clone() +state['head.bias']=state['head.bias'].reshape(32,18)[:16].reshape(16*18).clone() +ck['config']['patch']=16 +ck['conversion']={'from_checkpoint':str(Path(a.input).resolve()),'from_sha256':hashlib.sha256(Path(a.input).read_bytes()).hexdigest(),'method':'fold input/query halves by summation; retain first 16 output rows; preserve physical positional units'} +ck['args']={**ck['args'],'initialize_from':str(Path(a.input).resolve()),'converted':True} +torch.save(ck,a.output) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/evaluate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..05f086d4d84def4a48165f9e65d2948877675e56 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/evaluate.py @@ -0,0 +1,16 @@ +import sys,json,argparse,time,hashlib +from pathlib import Path +import torch +from predict import load_model,run +sys.path.insert(0,'/workspace/evaluation') +from score import score,json_safe + +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);ap.add_argument('--valid',default='/workspace/research/valid_screen');ap.add_argument('--baseline',default='/workspace/research/valid_screen/baseline.json');a=ap.parse_args() +torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cuda.matmul.allow_tf32=False +t0=time.time();out=Path(a.out);v=Path(a.valid) +run(load_model(a.weights),v/'input',out) +base=json.loads(Path(a.baseline).read_text())['configs'] +rep=score(v/'truth',out,base) +rep['checkpoint_sha256']=hashlib.sha256(Path(a.weights).read_bytes()).hexdigest();rep['eval_seconds']=time.time()-t0 +(out/'report.json').write_text(json.dumps(json_safe(rep),indent=1)) +print(json.dumps({k:rep[k] for k in ('skill_score','rel_mase_gmean','rel_wql_gmean','n_failed','groups','eval_seconds')},indent=1)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/model.py new file mode 100644 index 0000000000000000000000000000000000000000..06cce56e2ce671b6683f0246900abfcac06bb3c0 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/model.py @@ -0,0 +1,154 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..e20c6630475d6b4fa6906eb4ed9454b7b5aeec2c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/predict.py @@ -0,0 +1,43 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):q=model.predict(x,p,h).float().cpu().numpy() + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf95c9aec5936076b881c340edb960786f2d40d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/publish.py @@ -0,0 +1,31 @@ +"""Assemble a relocatable package, then atomically exchange complete directories.""" +import json,os,shutil,ctypes,hashlib,argparse +from pathlib import Path +import torch +HERE=Path(__file__).resolve().parent + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',default='/workspace/submission');ap.add_argument('--report',required=True);ap.add_argument('--experiments',default=str(HERE/'EXPERIMENTS.md'));a=ap.parse_args() + final=Path(a.out);staging=final.parent/f'.{final.name}-staging-{os.getpid()}' + shutil.rmtree(staging,ignore_errors=True);staging.mkdir(parents=True) + for file in ('model.py','predict.py','infer.sh','ts_io.py'): + shutil.copy(HERE/file,staging/file) + shutil.copy(a.weights,staging/'weights.pt');shutil.copy('/opt/runtime/requirements.txt',staging/'requirements.txt') + ck=torch.load(a.weights,map_location='cpu',weights_only=False);digest=hashlib.sha256((staging/'weights.pt').read_bytes()).hexdigest() + sources=json.loads(Path('/workspace/research/packed_sample/meta.json').read_text())['dirs'] + manifest={'name':'direct-seasonal-quantile-v1','contract':'timeseries-forecast/v1','parameters':sum(x.numel() for x in ck['model'].values()),'pretrained_assets':[],'sources_used':[f'gifteval_pretrain/{d}' for d in sources]+['synthetic:direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; data.py generator seed 17'],'weights_sha256':digest,'training_step':ck['step'],'config':ck['config'],'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.'} + (staging/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') + (staging/'config.json').write_text(json.dumps(ck['config'],indent=2)+'\n') + shutil.copy(a.experiments,staging/'EXPERIMENTS.md');shutil.copy(a.report,staging/'validation_report.json') + # Include generator/sampler provenance, which is not imported by inference. + (staging/'provenance').mkdir() + for file in ('pack.py','data.py','train.py'):shutil.copy(HERE/file,staging/'provenance'/file) + (staging/'README.md').write_text('# Direct seasonal quantile foundation forecaster\n\nRun `bash infer.sh INPUT_DIR OUTPUT_DIR`. This package contains all inference assets and uses only its supplied input directory. The 6.76M 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.\n\nThe 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.\n') + if final.exists(): + libc=ctypes.CDLL(None,use_errno=True) + if libc.renameat2(-100,os.fsencode(staging),-100,os.fsencode(final),2):raise OSError(ctypes.get_errno(),os.strerror(ctypes.get_errno())) + shutil.rmtree(staging) + else:os.replace(staging,final) + print(json.dumps(manifest,indent=1)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/record.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/record.py new file mode 100644 index 0000000000000000000000000000000000000000..1850a33f46fa3ee4d78cac4a5d6152404801a131 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/record.py @@ -0,0 +1,9 @@ +import argparse,json,math +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('report');ap.add_argument('--label',required=True);ap.add_argument('--outcome',default='Screened for model selection.');a=ap.parse_args() +r=json.loads(Path(a.report).read_text());p=Path(__file__).with_name('EXPERIMENTS.md') +lines=[f'\n## {a.label}',f'- Checkpoint SHA-256: `{r.get("checkpoint_sha256","see model_manifest.json")}`.',f'- Evaluation: {r["n_configs"]} configurations, {r["n_instances"]} instances, {r["n_failed"]} failed configurations; {r.get("eval_seconds","not separately timed")} seconds.',f'- Overall skill {r["skill_score"]:.6f}; relative MASE {r["rel_mase_gmean"]:.6f}; relative WQL {r["rel_wql_gmean"]:.6f}.'] +for group,entries in r['groups'].items(): + lines.append(f'- {group} skill: '+', '.join(f'{k}={1-math.sqrt(v["rel_mase_gmean"]*v["rel_wql_gmean"]):.4f}' for k,v in entries.items())+'.') +lines.append('- Outcome: '+a.outcome) +with p.open('a') as f:f.write('\n'.join(lines)+'\n') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/train.py new file mode 100644 index 0000000000000000000000000000000000000000..3cdc106980371c99d81c71d6746943c47206be83 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/train.py @@ -0,0 +1,71 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(3);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/validation_subset.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..4df83e69c4f9a3365955e5d17ffcfc0af71372b7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch16/validation_subset.py @@ -0,0 +1,18 @@ +"""Model-selection-only subset spanning all 97 configurations, seed 2026.""" +import sys,json,copy +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +import ts_io + +root=Path('/workspace/data/valid');out=Path('/workspace/research/valid_screen') +idx=json.loads((root/'input/index.json').read_text());new=copy.deepcopy(idx);rng=np.random.default_rng(2026) +for cfg in new['configs']: + cid=cfg['config_id'];case=ts_io.CaseFile(root/'input/cases'/f'{cid}.h5') + ids=np.sort(rng.choice(case.n,min(case.n,192),replace=False)) + ts_io.write_case_subset(case,ids,out/'input/cases'/f'{cid}.h5') + lab,se,meta=ts_io.read_truth_file(root/'truth/cases'/f'{cid}.h5') + ts_io.write_truth_file(out/'truth/cases'/f'{cid}.h5',lab[ids],se[ids],meta) + cfg['n_instances']=len(ids);case.close() +for kind in ('input','truth'):(out/kind/'index.json').write_text(json.dumps(new,indent=1)) +print('screen instances',sum(c['n_instances'] for c in new['configs'])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch8/convert.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch8/convert.py new file mode 100644 index 0000000000000000000000000000000000000000..f758dcbc0d48b531889b71dc758a7d2fb9a3afb7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch8/convert.py @@ -0,0 +1,44 @@ +"""Convert our own 16-point model to 8-point patches, without external assets.""" +import argparse +import hashlib +import json +import time +from pathlib import Path + +import torch + +ap=argparse.ArgumentParser() +ap.add_argument('--input',required=True) +ap.add_argument('--output',required=True) +a=ap.parse_args() +torch.set_num_threads(2) +started=time.monotonic() +ck=torch.load(a.input,map_location='cpu',weights_only=False) +state=ck['model']; d=ck['config']['d'] +assert ck['config']['patch']==16 +old=state['embed.0.weight'].reshape(d,2,16) +state['embed.0.weight']=(old[:,:,:8]+old[:,:,8:]).reshape(d,16) +old=state['query.0.weight'].reshape(d,16,9) +state['query.0.weight']=(old[:,:8]+old[:,8:]).reshape(d,8*9) +if 'recency.weight' in state: + old=state['recency.weight'].reshape(d,16,4) + state['recency.weight']=(old[:,:8]+old[:,8:]).reshape(d,8*4) +state['head.weight']=state['head.weight'].reshape(16,18,d)[:8].reshape(8*18,d).clone() +state['head.bias']=state['head.bias'].reshape(16,18)[:8].reshape(8*18).clone() +ck['config']['patch']=8 +ck['config']['partial_target_lengths']=True +ck['conversion']={ + 'from_checkpoint':str(Path(a.input).resolve()), + 'from_sha256':hashlib.sha256(Path(a.input).read_bytes()).hexdigest(), + 'method':'fold input/query/recency halves by summation; retain first8 output rows; preserve physical position units', + 'exact_function_preservation':False} +ck['args']={**ck['args'],'initialize_from':str(Path(a.input).resolve()),'converted':True} +ck['parent_checkpoints']=[str(Path(a.input).resolve())] +torch.save(ck,a.output) +receipt=dict(input_sha256=ck['conversion']['from_sha256'], + checkpoint_sha256=hashlib.sha256(Path(a.output).read_bytes()).hexdigest(), + parameters=sum(v.numel() for v in state.values()), + cpu_seconds=time.monotonic()-started, + optimizer_updates=0,conversion=ck['conversion']) +Path(a.output).with_suffix('.json').write_text(json.dumps(receipt,indent=2)) +print(json.dumps(receipt)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch8/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch8/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch8/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch8/memory_check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch8/memory_check.py new file mode 100644 index 0000000000000000000000000000000000000000..d55bebeab8c6ff393f89b7ad031763f49531f56b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch8/memory_check.py @@ -0,0 +1,23 @@ +"""Maximum training-shape memory fixture, serialized with validation jobs.""" +import fcntl,json,sys,time +from pathlib import Path +import torch + +r=Path('/workspace/research');sys.path.insert(0,str(r/'patch8')) +from model import DirectForecaster,loss_fn +from data import Sampler +with open(r/'.evaluation.lock','a') as lock: + fcntl.flock(lock,fcntl.LOCK_EX) + torch.set_num_threads(1);torch.manual_seed(277);torch.backends.cuda.matmul.allow_tf32=True + started=time.monotonic() + ck=torch.load(r/'patch8_initial.pt',map_location='cpu',weights_only=False) + m=DirectForecaster(**ck['config']).cuda();m.load_state_dict(ck['model']) + x,y,p=[torch.from_numpy(a).cuda() for a in Sampler(r/'packed_sample',277).sample(64,4096,1024)] + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(m,x,y,p,paired=True) + loss.backward();torch.cuda.synchronize() + assert all(v.grad is not None and torch.isfinite(v.grad).all() for v in m.parameters()) + result={'seed':277,'batch':64,'signed_rows':128,'context':4096,'horizon':1024, + 'optimizer_updates':0,'loss':float(loss.detach()),'seconds':time.monotonic()-started, + 'peak_allocated_mib':torch.cuda.max_memory_allocated()/2**20, + 'peak_reserved_mib':torch.cuda.max_memory_reserved()/2**20} + (r/'patch8_memory_check.json').write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch8/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch8/model.py new file mode 100644 index 0000000000000000000000000000000000000000..dedcdff4698028a8ba655865f8425d0dc3ef0dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/patch8/model.py @@ -0,0 +1,204 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/recency_features/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/recency_features/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/recency_features/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/recency_features/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/recency_features/model.py new file mode 100644 index 0000000000000000000000000000000000000000..f8271c5b0bf9a5edb961e1c7839761fe50a2e40b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/recency_features/model.py @@ -0,0 +1,171 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024,recency_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + if self.recency is not None: + pos=torch.arange(c,device=z.device)[None,:];extras=[] + for j in range(2): + period=periods[:,j:j+1] + recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/recency_features/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/recency_features/train.py new file mode 100644 index 0000000000000000000000000000000000000000..3bfb8b90f1a6656881b7598f864becaa737a76f4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/recency_features/train.py @@ -0,0 +1,73 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(3);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/recovery/capacity_curves.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/recovery/capacity_curves.py new file mode 100644 index 0000000000000000000000000000000000000000..c89a28a84243dc16ae52a1215c182a00f15dbc4e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/recovery/capacity_curves.py @@ -0,0 +1,50 @@ +"""Summarize completed validation checkpoints and measured shared-GPU training time.""" +import csv +import json +import time +from pathlib import Path + +R = Path('/workspace/research') +started = time.monotonic() +names = ['random_capacity_512', 'random_capacity_1024', 'random_capacity_1024_halflr', + 'random_capacity_full', 'distill_ensemble', 'random_capacity_512_anneal'] +rows = [] +for name in names: + log = R/(name+'_train.log') + records = {} + if log.exists(): + for line in log.read_text().splitlines(): + try: + item = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(item,dict) and 'step' in item and 'seconds' in item: + records[item['step']] = item + config_path = R/'runs'/name/'config.json' + config = json.loads(config_path.read_text()) if config_path.exists() else {} + for report in sorted((R/'evals').glob(name+'_ema*/report.json')): + result = json.loads(report.read_text()) + step = int(report.parent.name.rsplit('ema',1)[1]) + if result['n_failed']: + continue + record = records.get(step,{}) + rows.append(dict(run=name,step=step,parameters=config.get('parameters'), + seed=config.get('seed'),batch=config.get('batch'),learning_rate=config.get('lr'), + packed=config.get('packed'),skill=result['skill_score'], + rel_mase=result['rel_mase_gmean'],rel_wql=result['rel_wql_gmean'], + checkpoint_sha256=result['checkpoint_sha256'], + training_phase_loop_seconds=record.get('seconds'), + evaluation_seconds=result.get('eval_seconds'),report=str(report))) +rows.sort(key=lambda item:(names.index(item['run']),item['step'])) +output = dict(generated_utc=time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()), + note='Validation selection only. Time is logged process wall on the shared single H100, not isolated GPU time. The cooldown arm starts from the same saved24000state; its phase clock resets. No missing log time is inferred.', + rows=rows,analysis_seconds=time.monotonic()-started,no_training_or_new_inference=True) +(R/'capacity_learning_curves.json').write_text(json.dumps(output,indent=2)) +with (R/'capacity_learning_curves.csv').open('w',newline='') as handle: + writer = csv.DictWriter(handle,fieldnames=list(rows[0]) if rows else ['run']) + writer.writeheader() + writer.writerows(rows) +for name in names: + selected = [r for r in rows if r['run']==name] + if selected: + print(json.dumps(selected[-1])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/recovery/exposure_audit.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/recovery/exposure_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..fb67738bc9ed77f87173feda2430365e66c75966 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/recovery/exposure_audit.py @@ -0,0 +1,46 @@ +"""Describe sampled observation exposure and training invested in selected ancestry.""" +import json +import sys +import time +from pathlib import Path +import numpy as np + +R=Path('/workspace/research') +sys.path.insert(0,str(R/'random_capacity')) +from data import Sampler + +started=time.monotonic() +seed=521 +sampler=Sampler(R/'packed_sample',seed=seed,source_weights_from=R/'packed_sample') +rng=np.random.default_rng(seed) +rows=context_points=target_points=0 +for _ in range(320): + 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])) + x,y,p=sampler.sample(64,c,h) + rows+=len(x) + context_points+=int(np.isfinite(x).sum()) + target_points+=int(np.isfinite(y).sum()) +manifest=json.loads(Path('/workspace/submission/model_manifest.json').read_text()) +runs={} +for item in manifest['training_lineage']: + path=Path(item['checkpoint']) + batch=item.get('training_settings',{}).get('batch') + if path.parts[0]!='runs' or not batch: + continue + run=path.parts[1] + step=item.get('step',0) + if step>runs.get(run,{}).get('step',0): + runs[run]=dict(step=step,batch=batch,rows=step*batch,checkpoint=item['checkpoint']) +ancestral_rows=sum(v['rows'] for v in runs.values()) +mean_points=(context_points+target_points)/rows +result=dict(seed=seed,seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False, + sampled_rows=rows,mean_finite_context_points=context_points/rows, + mean_finite_target_points=target_points/rows,mean_finite_points=mean_points, + selected_descriptor=manifest['checkpoint_sha256'],ancestral_runs=runs, + selected_ancestral_rows_before_sign_pairing=ancestral_rows, + fresh96000_batch48_rows=96000*48, + fresh96000_batch48_gross_observation_presentations_estimate=96000*48*mean_points, + note='Gross sampled presentations include overlapping/resampled windows and synthetic values, not unique observations. Ancestral run maxima count compute invested in different branches, including subtracted controls; they are not an equivalent single-model training trajectory. Sign pairing duplicates compute but not distinct sampled rows. No future training recipe is inferred from this audit alone.') +(R/'training_exposure_audit.json').write_text(json.dumps(result,indent=2)) +print(json.dumps({k:v for k,v in result.items() if k!='ancestral_runs'})) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/recovery/relaunch_20261022b.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/recovery/relaunch_20261022b.py new file mode 100644 index 0000000000000000000000000000000000000000..d16fc19cbbb86dba2ff53b445e368b8bbd2ca218 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/recovery/relaunch_20261022b.py @@ -0,0 +1,105 @@ +"""Resume interrupted research jobs and preserve phase-specific recovery receipts.""" +import datetime +import json +import os +from pathlib import Path +import shutil +import subprocess +import time + +R = Path('/workspace/research') +TAG = 'recovery2' +env = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1') +receipt = {'recovery_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(), + 'remaining_research_seconds_at_operator_recovery': 152594, + 'jobs': {}, 'queues': {}} +children = {} + +def launch(name, command, phase=TAG): + log = R / f'{name}_{phase}.log' + assert not log.exists(), log + with log.open('w') as f: + child = subprocess.Popen(command, stdout=f, stderr=subprocess.STDOUT, env=env) + children[name] = child + return {'pid': child.pid, 'command': command, 'log': str(log), 'started_monotonic': time.monotonic()} + +def persist(): + path = R / f'{TAG}_launch_receipt.json' + tmp = path.with_suffix('.tmp') + tmp.write_text(json.dumps(receipt, indent=2)); os.replace(tmp, path) + +for name in ['wide_capacity_146m_recovery', 'wide_capacity_control_recovery', + 'long_memory_synth_recovery', 'recent_normalization_recovery', 'wide_graft', 'patch8']: + run = R / 'runs' / name + cfg = json.loads((run / 'config.json').read_text()) + shutil.copy2(run / 'config.json', run / f'config_before_{TAG}.json') + command = ['python3', str(R / 'recovery/train.py')] + for key in ['code_dir', 'packed', 'source_weights_from', 'out', 'initialize_from', + 'initialize_ema', 'start_step', 'steps', 'batch', 'lr', 'seed', 'context', + 'sample_context', 'save_every', 'stop_file', 'reset_at', 'reset_seed', 'loss_mode']: + if cfg.get(key) is not None: + command += ['--' + key.replace('_', '-'), str(cfg[key])] + if (run / 'recovery.pt').exists(): + command += ['--resume', str(run / 'recovery.pt')] + mode = 'complete optimizer/EMA/RNG/prefetched-batch resume' + else: + mode = 'restart saved own initialization; no complete checkpoint existed' + if cfg.get('compile_loss'): + command += ['--compile-loss'] + command = ['env', 'TORCHINDUCTOR_COMPILE_THREADS=2', 'MAX_JOBS=2', + 'PYTHONPATH=/workspace/research/compiler_support', + 'TRITON_CACHE_MANAGER=sibling_cache:SiblingFileCacheManager', + 'TRITON_CACHE_DIR=/tmp/timeseries-triton-cache', + 'TORCHINDUCTOR_CACHE_DIR=/tmp/timeseries-inductor-cache'] + command + assert not Path(cfg['stop_file']).exists(), cfg['stop_file'] + receipt['jobs'][name] = dict(launch(name, command), mode=mode) + persist() + +watch_specs = { + 'wide_capacity_146m_recovery': ('wide_capacity_inference', '24000,32000'), + 'wide_capacity_control_recovery': ('wide_capacity_inference', '24000,32000'), + 'long_memory_synth_recovery': ('partial_targets_inference', '12000'), + 'recent_normalization_recovery': ('recent_normalization_inference', '12000'), + 'wide_graft': ('wide_graft_inference', '4000,8000,12000,16000,24000,32000'), + 'patch8': ('full_paired_inference', '1000,3000,6000,12000'), + 'volatility_synth': ('partial_targets_inference', '3000,6000,12000'), + 'postloss': ('full_paired_inference', '1000,3000,6000,12000'), + 'paired_long_memory': ('full_paired_inference', '1000,3000,6000,12000'), +} +for name, (runtime, steps) in watch_specs.items(): + command = ['python3', str(R / 'watch_evaluate.py'), '--run', str(R / 'runs' / name), + '--evaluator', str(R / runtime / 'evaluate.py'), '--name', name, '--steps', steps] + launch(name + '_watch', command) + +queue_specs = {'volatility_synth': 'long_memory_synth_recovery', + 'postloss': 'recent_normalization_recovery', + 'paired_long_memory': 'wide_capacity_control_recovery'} +for name, dependency in queue_specs.items(): + old = json.loads((R / (name + '_queue.json')).read_text()) + shutil.copy2(R / (name + '_queue.json'), R / (name + '_queue_before_' + TAG + '.json')) + receipt['queues'][name] = dict(old, dependency=dependency, status='waiting', + wait_pids=[children[dependency].pid]) +persist() + +while True: + for name, job in receipt['jobs'].items(): + if 'returncode' not in job and children[name].poll() is not None: + job.update(returncode=children[name].returncode, + phase_seconds=time.monotonic() - job['started_monotonic']) + persist() + for name, queue in receipt['queues'].items(): + if queue['status'] == 'waiting' and children[queue['dependency']].poll() is not None: + if children[queue['dependency']].returncode != 0 or not all(Path(p).exists() for p in queue['required_checkpoints']): + queue['status'] = 'blocked_by_incomplete_dependency' + else: + receipt['jobs'][name] = launch(name, queue['command']) + queue.update(status='running', pid=children[name].pid, + started_utc=datetime.datetime.now(datetime.timezone.utc).isoformat()) + with (R / 'direct_v1/EXPERIMENTS.md').open('a') as f: + f.write(f'\n{name} started {queue["started_utc"]} after {queue["dependency"]} completed. Original predeclared settings and seed retained.\n') + (R / (name + '_queue.json')).write_text(json.dumps(queue, indent=2)) + persist() + if all(p.poll() is not None for n,p in children.items() if not n.endswith('_watch')) and all(q['status'] != 'waiting' for q in receipt['queues'].values()): + break + time.sleep(5) +persist() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/recovery/relaunch_20261023.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/recovery/relaunch_20261023.py new file mode 100644 index 0000000000000000000000000000000000000000..5f35a9cfcbe7ea66c8837b6d4ada8b84be36b934 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/recovery/relaunch_20261023.py @@ -0,0 +1,104 @@ +"""Resume interrupted research jobs and preserve phase-specific recovery receipts.""" +import datetime +import json +import os +from pathlib import Path +import shutil +import subprocess +import time + +R = Path('/workspace/research') +TAG = 'recovery3' +env = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1') +receipt = {'recovery_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(), + 'remaining_research_seconds_at_operator_recovery': 151596, + 'jobs': {}, 'queues': {}} +children = {} + +def launch(name, command, phase=TAG): + log = R / f'{name}_{phase}.log' + assert not log.exists(), log + with log.open('w') as f: + child = subprocess.Popen(command, stdout=f, stderr=subprocess.STDOUT, env=env) + children[name] = child + return {'pid': child.pid, 'command': command, 'log': str(log), 'started_monotonic': time.monotonic()} + +def persist(): + path = R / f'{TAG}_launch_receipt.json' + tmp = path.with_suffix('.tmp') + tmp.write_text(json.dumps(receipt, indent=2)); os.replace(tmp, path) + +for name in ['wide_capacity_146m_recovery', 'wide_capacity_control_recovery', + 'long_memory_synth_recovery', 'wide_graft', 'patch8']: + run = R / 'runs' / name + cfg = json.loads((run / 'config.json').read_text()) + shutil.copy2(run / 'config.json', run / f'config_before_{TAG}.json') + command = ['python3', str(R / 'recovery/train.py')] + for key in ['code_dir', 'packed', 'source_weights_from', 'out', 'initialize_from', + 'initialize_ema', 'start_step', 'steps', 'batch', 'lr', 'seed', 'context', + 'sample_context', 'save_every', 'stop_file', 'reset_at', 'reset_seed', 'loss_mode']: + if cfg.get(key) is not None: + command += ['--' + key.replace('_', '-'), str(cfg[key])] + if (run / 'recovery.pt').exists(): + command += ['--resume', str(run / 'recovery.pt')] + mode = 'complete optimizer/EMA/RNG/prefetched-batch resume' + else: + mode = 'restart saved own initialization; no complete checkpoint existed' + if cfg.get('compile_loss'): + command += ['--compile-loss'] + command = ['env', 'TORCHINDUCTOR_COMPILE_THREADS=2', 'MAX_JOBS=2', + 'PYTHONPATH=/workspace/research/compiler_support', + 'TRITON_CACHE_MANAGER=sibling_cache:SiblingFileCacheManager', + 'TRITON_CACHE_DIR=/tmp/timeseries-triton-cache', + 'TORCHINDUCTOR_CACHE_DIR=/tmp/timeseries-inductor-cache'] + command + assert not Path(cfg['stop_file']).exists(), cfg['stop_file'] + receipt['jobs'][name] = dict(launch(name, command), mode=mode) + persist() + +watch_specs = { + 'wide_capacity_146m_recovery': ('wide_capacity_inference', '24000,32000'), + 'wide_capacity_control_recovery': ('wide_capacity_inference', '24000,32000'), + 'long_memory_synth_recovery': ('partial_targets_inference', '12000'), + 'recent_normalization_recovery': ('recent_normalization_inference', '12000'), + 'wide_graft': ('wide_graft_inference', '4000,8000,12000,16000,24000,32000'), + 'patch8': ('full_paired_inference', '1000,3000,6000,12000'), + 'volatility_synth': ('partial_targets_inference', '3000,6000,12000'), + 'postloss': ('full_paired_inference', '1000,3000,6000,12000'), + 'paired_long_memory': ('full_paired_inference', '1000,3000,6000,12000'), +} +for name, (runtime, steps) in watch_specs.items(): + command = ['python3', str(R / 'watch_evaluate.py'), '--run', str(R / 'runs' / name), + '--evaluator', str(R / runtime / 'evaluate.py'), '--name', name, '--steps', steps] + launch(name + '_watch', command) + +queue_specs = {'volatility_synth': 'long_memory_synth_recovery', + 'paired_long_memory': 'wide_capacity_control_recovery'} +for name, dependency in queue_specs.items(): + old = json.loads((R / (name + '_queue.json')).read_text()) + shutil.copy2(R / (name + '_queue.json'), R / (name + '_queue_before_' + TAG + '.json')) + receipt['queues'][name] = dict(old, dependency=dependency, status='waiting', + wait_pids=[children[dependency].pid]) +persist() + +while True: + for name, job in receipt['jobs'].items(): + if 'returncode' not in job and children[name].poll() is not None: + job.update(returncode=children[name].returncode, + phase_seconds=time.monotonic() - job['started_monotonic']) + persist() + for name, queue in receipt['queues'].items(): + if queue['status'] == 'waiting' and children[queue['dependency']].poll() is not None: + if children[queue['dependency']].returncode != 0 or not all(Path(p).exists() for p in queue['required_checkpoints']): + queue['status'] = 'blocked_by_incomplete_dependency' + else: + receipt['jobs'][name] = launch(name, queue['command']) + queue.update(status='running', pid=children[name].pid, + started_utc=datetime.datetime.now(datetime.timezone.utc).isoformat()) + with (R / 'direct_v1/EXPERIMENTS.md').open('a') as f: + f.write(f'\n{name} started {queue["started_utc"]} after {queue["dependency"]} completed. Original predeclared settings and seed retained.\n') + (R / (name + '_queue.json')).write_text(json.dumps(queue, indent=2)) + persist() + if all(p.poll() is not None for n,p in children.items() if not n.endswith('_watch')) and all(q['status'] != 'waiting' for q in receipt['queues'].values()): + break + time.sleep(5) +persist() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/recovery/schedules.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/recovery/schedules.py new file mode 100644 index 0000000000000000000000000000000000000000..4c8378f374144b802d2cd5a98afd71efc1ba0a4c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/recovery/schedules.py @@ -0,0 +1,13 @@ +"""Explicit training-only learning-rate schedules; default arithmetic unchanged.""" +import math + + +def learning_rate(step, steps, peak, reset_at=-1, anneal_from_step=None, + anneal_from_lr=None, anneal_final_lr=None): + if anneal_from_step is not None: + assert steps > anneal_from_step + assert 0 < anneal_final_lr <= anneal_from_lr + progress=max(0.,min(1.,(step-anneal_from_step)/(steps-anneal_from_step))) + return anneal_final_lr+.5*(anneal_from_lr-anneal_final_lr)*(1+math.cos(math.pi*progress)) + warm_step=step-reset_at if reset_at>=0 and step>reset_at else step + return peak*min(1,warm_step/400)*(.2+.4*(1+math.cos(math.pi*step/steps))) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/recovery/snapshot.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/recovery/snapshot.py new file mode 100644 index 0000000000000000000000000000000000000000..11ce27e43477f9c685cefeaa5f36e53c59634505 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/recovery/snapshot.py @@ -0,0 +1,99 @@ +"""Write a compact authoritative research recovery index without touching training state.""" +import datetime +import json +import os +from pathlib import Path + +R=Path('/workspace/research');p=R/'CURRENT_RESEARCH_STATE.json' +s=json.loads(p.read_text()) +s['snapshot_utc']=datetime.datetime.now(datetime.timezone.utc).isoformat() +receipt=json.loads((R/'recovery3_launch_receipt.json').read_text()) +s['runs']={} +for name,job in receipt['jobs'].items(): + run=R/'runs'/name + log=Path(job['log']) + records=[] + for line in log.read_text().splitlines(): + try: + record=json.loads(line) + if 'step' in record or 'completed_step' in record:records.append(record) + except json.JSONDecodeError:pass + s['runs'][name]={'config':json.loads((run/'config.json').read_text()) if (run/'config.json').exists() else None, + 'last_phase_record':records[-1] if records else None, + 'phase_log':str(log),'supervisor_receipt':str(R/'recovery3_launch_receipt.json'), + 'latest_saved_ema':str(max(run.glob('ema*.pt'))) if list(run.glob('ema*.pt')) else None, + 'complete_recovery_checkpoint':str(run/'recovery.pt') if (run/'recovery.pt').exists() else None, + 'pid_at_snapshot':job['pid'],'returncode':job.get('returncode'), + 'note':'Check actual live process and checkpoint state before resuming; this is only a snapshot.'} +s['queues']={name:{'status':q['status'],'dependency':q['dependency'],'command':q['command'], + 'required_checkpoints':q['required_checkpoints']} + for name,q in receipt['queues'].items()} +s.pop('prepared_not_launched',None) +s['deferred_unqueued']={'E72':'temporal_mixup, prepared and checked but not queued','ideas':'RESEARCH_IDEAS.md, no jobs attached'} +s['completed_since_previous_recovery']={ + 'E67_control12000':{'skill':.37724286394256845,'training_loop_seconds':2794.8358458959847}, + 'E67_paired12000':{'skill':.377427077277383,'training_loop_seconds':2794.867385860998}, + 'E63_expanded146M':'Stopped8501, complete recovery retained; allocation moved to E73; inconclusive data scaling', + 'E61_slowAR':'Complete12000; E76 used6000 correction, final transfer rejected', + 'E65_recent_normalization':'Complete12000; E81 equal ensemble rejected', + 'E58_small_control':'Complete32000', + 'E58_wide146M':'Complete32000; no gain over37Mcontrol; do not resume', + 'E71_patch8':'Complete12000; selected6000 used in E87/E96/E102 ensembles', + 'E69_volatility':'Complete12000; final below matched control; no transfer', + 'E89_patch8_control':'Complete12000; final0.380847096,loop2729.052105s; selected starting E71parent remains stronger', + 'E89_fullpatch4':'Complete12000,main0.381640078; E96 used6000, E103final cached alternative mixed; loop5066.016522s', + 'E93_split_patch':'Complete12000,main0.381711986; selected final is E102 published thirdmember; loop3153.565149s', + 'E92_robust_normalization':'Complete12000,final0.377099312 belowcontrol; rejected;E97started', + 'E90_metric_scale':'Complete12000; final0.377373344 ties/slightly trailsE80; no selection; loop2702.166704s', + 'E84_coarse':'Complete12000; daily gain but weekly regression; not selected', + 'E88_late_patch8_slowAR':'Complete12000; small9k gain lost atfinal; rejected', + 'E80_overflow':'Complete12000; finaltiesoriginal; selected3k compositeE91rejected', + 'E78_multiscaleAR':'Complete12000; no gain over single slowAR', + 'E86_protected_graft':'Complete8000; below own initialization; no publication', + 'E75_postloss':'Stopped3653 deliberately; immutable snapshot retained; E98 separately declared completion active in another output, original stopfile remains', + 'E73_independent_graft':'Stopped8683 after negative8000; replaced by E86; stopfile remains', + 'E95_stratified_corpus':'Complete12000,final0.377983250,earliermixed; E105collision destroyed only1000weights and optimizer recovery;2k..12k preserved; do not resume', + 'E97_weekly_synth':'Complete12000,final0.380439539; E112final weekly correction now published; loop2600.472750s', + 'E105_stratified_volume':'Complete12000,final0.377529200,earlier0.336713522/0.359535697/0.390349158 mixed; corrected continuationloop2013.982814s plus original incident phase', + 'E106_spectral_synth':'Complete12000,final0.377641399,earlier0.337647555/0.361626447/0.385497870, average matched gap negligible; loop2206.272278s; E114fixed6000transfers in selection', + 'E98_postloss_completion':'Complete12000,final0.376034254 below3000 andcontrol; rejected,loop1995.386513s', + 'E99_early_cooldown':'Complete36000,final0.363306598 trails original36k0.364859034; rejected,loop1603.635706s', + 'E77_pairedslowAR':'Complete12000;6000 strongest main/earlier comparison'} +s['external_receipts']=[str(R/'postloss_recovery3_receipt.json'),str(R/'random_capacity_512_queue.json'),str(R/'random_capacity_1024_queue.json'),str(R/'multiscale_ar_queue.json'),str(R/'overflow_control_queue.json'),str(R/'coarse_aggregate_queue.json'),str(R/'patch8_long_memory_queue.json'),str(R/'wide_graft_frozen_queue.json'),str(R/'patch4_candidate_queue.json'),str(R/'patch4_control_queue.json'),str(R/'metric_scale_queue.json'),str(R/'robust_normalization_queue.json'),str(R/'split_patch_queue.json'),str(R/'random_capacity_1024_halflr_queue.json'),str(R/'stratified_corpus_queue.json'),str(R/'weekly_synth_queue.json'),str(R/'postloss_completion_queue.json'),str(R/'random_capacity_512_anneal_queue.json'),str(R/'distill_ensemble_queue.json'),str(R/'stratified_volume_queue.json'),str(R/'spectral_synth_queue.json'),str(R/'long_seasonal_queue.json'),str(R/'random_capacity_full_queue.json'),str(R/'weekly_replication_control_queue.json'),str(R/'weekly_replication_candidate_queue.json'),str(R/'lowfreq_windows_queue.json'),str(R/'phase_joint_queue.json')] +queue_pids={'random_capacity_512_queue.json':965,'random_capacity_1024_queue.json':967, + 'multiscale_ar_queue.json':1678,'overflow_control_queue.json':1676, + 'coarse_aggregate_queue.json':3086,'patch8_long_memory_queue.json':3739, + 'wide_graft_frozen_queue.json':3931,'patch4_candidate_queue.json':4078, + 'patch4_control_queue.json':4080} +s['external_jobs']={} +for receipt_name in s['external_receipts']: + receipt_path=Path(receipt_name) + if not receipt_path.exists():continue + item=json.loads(receipt_path.read_text());command=item.get('command',[]) + if '--out' not in command:continue + run=Path(command[command.index('--out')+1]);log=Path(item.get('log',str(receipt_path).replace('_queue.json','_train.log'))) + last=None + if log.exists(): + for line in log.read_text().splitlines(): + try: + record=json.loads(line) + if isinstance(record,dict) and ('step' in record or 'completed_step' in record):last=record + except json.JSONDecodeError:pass + queue_pid=item.get('launcher_pid',queue_pids.get(receipt_path.name)) + children_file=Path(f'/proc/{queue_pid}/task/{queue_pid}/children') if queue_pid else None + children=list(map(int,children_file.read_text().split())) if children_file and children_file.exists() else [] + checkpoints=list(run.glob('ema*.pt')) + s['external_jobs'][run.name]={'receipt':str(receipt_path),'status':item.get('status'), + 'queue_pid_at_snapshot':queue_pid,'child_pids_at_snapshot':children, + 'last_phase_record':last,'log':str(log), + 'latest_saved_ema':str(max(checkpoints)) if checkpoints else None, + 'complete_recovery_checkpoint':str(run/'recovery.pt') if (run/'recovery.pt').exists() else None, + 'command':command,'note':'PIDs are only a snapshot; check actual processes and serialized state before recovery.'} +s['compiler_environment']={'OPENBLAS_NUM_THREADS':'1','OMP_NUM_THREADS':'1','TORCHINDUCTOR_COMPILE_THREADS':'2','MAX_JOBS':'2','PYTHONPATH':str(R/'compiler_support'),'TRITON_CACHE_MANAGER':'sibling_cache:SiblingFileCacheManager','TRITON_CACHE_DIR':'/tmp/timeseries-triton-cache','TORCHINDUCTOR_CACHE_DIR':'/tmp/timeseries-inductor-cache'} +for job in s['external_jobs'].values(): + job['environment']=s['compiler_environment'] if '--compile-loss' in job['command'] else {'OPENBLAS_NUM_THREADS':'1','OMP_NUM_THREADS':'1'} +s['compiler_cache_backup']=str(R/'compiler_cache_backup') +for stale in ['pending','pending_actions','active_experiments','next_experiments','prepared_experiments']: + s.pop(stale,None) +tmp=p.with_suffix('.tmp');tmp.write_text(json.dumps(s,indent=2));os.replace(tmp,p) +print(s['snapshot_utc']) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/recovery/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/recovery/train.py new file mode 100644 index 0000000000000000000000000000000000000000..536677ab542342e8e9b56298e5ddb7cb2983a258 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member1/training/recovery/train.py @@ -0,0 +1,201 @@ +"""Resumable continuation of our existing permitted-corpus experiments.""" +import argparse,copy,fcntl,inspect,json,math,os,sys,time +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import numpy as np +import torch + +ap=argparse.ArgumentParser() +ap.add_argument('--code-dir',required=True);ap.add_argument('--packed',required=True) +ap.add_argument('--source-weights-from');ap.add_argument('--out',required=True) +ap.add_argument('--initialize-from',required=True);ap.add_argument('--initialize-ema') +ap.add_argument('--start-step',type=int,default=0);ap.add_argument('--resume') +ap.add_argument('--steps',type=int,required=True);ap.add_argument('--batch',type=int,required=True) +ap.add_argument('--lr',type=float,required=True);ap.add_argument('--seed',type=int,required=True) +ap.add_argument('--context',type=int);ap.add_argument('--sample-context',type=int,default=4096) +ap.add_argument('--save-every',type=int,default=1000);ap.add_argument('--stop-file') +ap.add_argument('--recovery-every',type=int,default=250) +ap.add_argument('--halt-after',type=int) +ap.add_argument('--loss-mode',choices=['individual','paired']) +ap.add_argument('--compile-loss',action='store_true') +ap.add_argument('--reset-at',type=int,default=-1);ap.add_argument('--reset-seed',type=int,default=179) +ap.add_argument('--anneal-from-step',type=int);ap.add_argument('--anneal-from-lr',type=float) +ap.add_argument('--anneal-final-lr',type=float) +ap.add_argument('--teacher-package');ap.add_argument('--teacher-coefficient',type=float) +a=ap.parse_args() +# Hold a process-lifetime lock before loading a model or touching GPU state. +_run_out=Path(a.out);_run_out.mkdir(parents=True,exist_ok=True) +_run_lock=open(_run_out/'.training.lock','a') +try:fcntl.flock(_run_lock,fcntl.LOCK_EX|fcntl.LOCK_NB) +except BlockingIOError:raise SystemExit('Another trainer already owns this output directory: '+str(_run_out)) +if not a.resume: + _saved=list(_run_out.glob('ema*.pt'))+list(_run_out.glob('step*.pt')) + if (_run_out/'recovery.pt').exists():_saved.append(_run_out/'recovery.pt') + if _saved: + raise SystemExit('Refusing fresh training into an output with saved checkpoints; use a new directory or explicit --resume: '+str(_run_out)) +sys.path.insert(0,a.code_dir) +from model import DirectForecaster,loss_fn +from data import Sampler +from schedules import learning_rate +torch.set_num_threads(2);torch.manual_seed(a.seed);torch.backends.cuda.matmul.allow_tf32=True +out=Path(a.out);out.mkdir(parents=True,exist_ok=True);a.trainable_scope='all' +if Path(a.code_dir).name in ('long_memory_synth','paired_long_memory','multiscale_ar','random_capacity','patch8_long_memory','distill_ensemble'):a.synthetic_ar_time_constants=[1,10000] +if Path(a.code_dir).name in ('full_paired','patch8','temporal_mixup','postloss','paired_long_memory','multiscale_ar','random_capacity','overflow_control','coarse_aggregate','patch8_long_memory','patch4','metric_scale','robust_normalization','split_patch','weekly_synth','distill_ensemble'):a.requested_horizon_seed=a.seed+300003 +if Path(a.code_dir).name=='multiscale_ar': + a.synthetic_ar_components=4;a.multiscale_ar_seed=a.seed+700003 +if Path(a.code_dir).name=='volatility_synth':a.stochastic_volatility_seed=a.seed+500003 +if Path(a.code_dir).name=='coarse_aggregate': + a.coarse_aggregation_seed=a.seed+900003;a.coarse_aggregation_probability=.2;a.coarse_aggregation_frequencies=['D','W'] +if Path(a.code_dir).name=='temporal_mixup':a.temporal_mixup_seed=a.seed+600003 +if Path(a.code_dir).name=='postloss': + a.fixed_postprocessing_loss=True;a.normalization_overflow_fallback=True +if Path(a.code_dir).name in ('overflow_control','metric_scale','random_capacity','weekly_synth','distill_ensemble'):a.normalization_overflow_fallback=True +if Path(a.code_dir).name=='weekly_synth': + a.weekly_synthetic_seed=a.seed+1000003;a.weekly_replacement_probability=1/11 +if Path(a.code_dir).name=='spectral_synth': + a.spectral_synthetic_seed=a.seed+1100003;a.spectral_replacement_probability=.5 + a.spectral_length_scale=[1,10000];a.spectral_families=['Matern0.5','Matern1.5','Matern2.5','RBF'] + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True +if Path(a.code_dir).name in ('long_seasonal','phase_joint'): + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True +if Path(a.code_dir).name=='lowfreq_windows': + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True + a.lowfreq_window_seed=a.seed+1200003;a.lowfreq_window_probability=.5 + a.lowfreq_window_rule='period2=1,period1<=52;finite-target endpoint;log-uniform horizon4..min(H,max(8,2p),span-8) with available-length fallback;context cap min(C,max(64,32p));at least4finite history' +if Path(a.code_dir).name=='metric_scale':a.loss_seasonality='lag1 for exact daily[7,365] and weekly[52,1] period pairs; unchanged otherwise' +if Path(a.code_dir).name=='robust_normalization':a.normalization_kind='finite median plus/minus6 mean absolute deviations winsorized mean/RMS, float64; original normalized history clipped30' +if Path(a.code_dir).name=='wide_graft_frozen':a.trainable_scope='new feature stream and cross-stream blocks; inherited parameter blocks frozen' +ck=torch.load(a.resume or a.initialize_from,map_location='cpu',weights_only=False) +# Keep immutable branch ancestry across a later restart from this run's own recovery. +lineage_parents=list(ck.get('parent_checkpoints',[])) +if a.initialize_ema:lineage_parents.append(a.initialize_ema) +if a.resume and Path(a.resume).parent.resolve()!=out.resolve():lineage_parents.append(a.resume) +previous_args=ck.get('args',{}) +previous_resume=previous_args.get('resume') +if previous_resume and Path(previous_resume).parent.resolve()!=Path(previous_args.get('out',a.out)).resolve(): + lineage_parents.append(previous_resume) +lineage_parents=list(dict.fromkeys(lineage_parents)) +config=dict(ck['config']) +if a.context:config['max_context']=a.context +model=DirectForecaster(**config).cuda();model.load_state_dict(ck['model']) +teacher=None +if Path(a.code_dir).name=='distill_ensemble': + assert a.teacher_package and a.teacher_coefficient is not None +if a.teacher_package: + assert Path(a.code_dir).name=='distill_ensemble' + from teacher import OwnEnsembleTeacher + with torch.random.fork_rng(devices=[torch.cuda.current_device()]): + teacher=OwnEnsembleTeacher(a.teacher_package) + if ck.get('args',{}).get('teacher_descriptor_sha256'): + assert ck['args']['teacher_descriptor_sha256']==teacher.descriptor_sha256 + assert ck['args']['teacher_coefficient']==a.teacher_coefficient + a.teacher_descriptor_sha256=teacher.descriptor_sha256 + a.teacher_checkpoint_sha256=teacher.member_hashes + a.teacher_target_kind='equal average of own frozen E96 raw normalized sign-paired neural quantiles, before postprocessing' + +protector=None +if Path(a.code_dir).name=='wide_graft_frozen': + from frozen import FreezeInherited + protector=FreezeInherited(model) + a.protected_parameters=protector.inherited_numel +if a.compile_loss: + torch._dynamo.config.recompile_limit=64 + objective=torch.compile(loss_fn,fullgraph=True,dynamic=False) +else:objective=loss_fn +multipliers=ck.get('lr_multipliers',{}) +def optimizer(): + groups=[] + for mult in sorted(set(multipliers.values())|{1.}): + params=[p for n,p in model.named_parameters() if multipliers.get(n,1.)==mult] + if params:groups.append({'params':params,'lr':a.lr*mult,'lr_multiplier':mult,'weight_decay':.05/mult}) + return torch.optim.AdamW(groups,betas=(.9,.95),fused=True) +opt=optimizer() +if a.resume: + start_step=ck['step'];opt.load_state_dict(ck['optimizer']) + ema={k:v.cuda() for k,v in ck['ema_state'].items()} +else: + start_step=a.start_step + ema_ck=torch.load(a.initialize_ema,map_location='cpu',weights_only=False) if a.initialize_ema else ck + ema={k:v.cuda().clone() for k,v in ema_ck['model'].items()} +del ck +def make_sampler(seed): + kwargs={'seed':seed} + if 'source_weights_from' in inspect.signature(Sampler).parameters:kwargs['source_weights_from']=a.source_weights_from + return Sampler(a.packed,**kwargs),np.random.default_rng(seed) +stream_seed=a.reset_seed if a.reset_at>=0 and start_step>=a.reset_at else a.seed +sampler,rng=make_sampler(stream_seed) +def next_batch(): + c=int(rng.choice([512,1024,2048,a.sample_context],p=[.1,.15,.35,.4])) + h=int(rng.choice([32,128,512,1024],p=[.1,.2,.2,.5])) + x,y,p=sampler.sample(a.batch,c,h) + return x[:,-model.max_context:].copy(),y,p +pool=ThreadPoolExecutor(1) +if a.resume: + recovery=torch.load(a.resume,map_location='cpu',weights_only=False) + rng.bit_generator.state=recovery['batch_rng_state'];sampler.rng.bit_generator.state=recovery['sampler_rng_state'] + for name,state in recovery.get('sampler_rng_states',{}).items():getattr(sampler,name).bit_generator.state=state + torch.set_rng_state(recovery['torch_rng_state']);torch.cuda.set_rng_state_all(recovery['cuda_rng_state']) + pending=recovery['prefetched_batch'];del recovery + future=pool.submit(lambda:pending) +else:future=pool.submit(next_batch) +parameters=sum(p.numel() for p in model.parameters()) +(out/'config.json').write_text(json.dumps({**vars(a),'model':model.config,'parameters':parameters},indent=2)) +print(json.dumps({'parameters':parameters,'starting_step':start_step,'stream_seed':stream_seed,'restored_complete_training_state':bool(a.resume)}),flush=True) +started=time.monotonic();losses=[] +def atomic_save(obj,path): + torch.save(obj,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) +def save(step,include_selection_weights=True): + global future + pending_batch=future.result() + common={'config':model.config,'step':step,'args':vars(a),'lr_multipliers':multipliers, + 'parent_checkpoints':list(dict.fromkeys(lineage_parents+(teacher.checkpoints if teacher else [])))} + if include_selection_weights: + for prefix,state in [('step',model.state_dict()),('ema',ema)]: + atomic_save({**common,'model':state,'ema':prefix=='ema'},out/f'{prefix}{step:06d}.pt') + atomic_save({**common,'model':model.state_dict(),'optimizer':opt.state_dict(),'ema_state':ema, + 'prefetched_batch':pending_batch,'batch_rng_state':copy.deepcopy(rng.bit_generator.state), + 'sampler_rng_state':copy.deepcopy(sampler.rng.bit_generator.state), + 'sampler_rng_states':{name:copy.deepcopy(value.bit_generator.state) for name,value in vars(sampler).items() if isinstance(value,np.random.Generator)}, + 'torch_rng_state':torch.get_rng_state(),'cuda_rng_state':torch.cuda.get_rng_state_all()},out/'recovery.pt') + future=pool.submit(lambda:pending_batch) +for step in range(start_step+1,a.steps+1): + if a.reset_at>=0 and step==a.reset_at+1 and start_step=a.halt_after) + selection_checkpoint=step%a.save_every==0 or step==a.steps or stop + # Persist a complete state before a fresh/resumed job warms its remaining compiled shapes. + if selection_checkpoint or step%a.recovery_every==0 or step==start_step+1: + save(step,include_selection_weights=selection_checkpoint) + if stop:break +pool.shutdown() +print(json.dumps({'completed_step':step,'training_process_loop_seconds':time.monotonic()-started}),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/model_manifest.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/model_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..267b9cd31e3dcddf8fb57320edcd08e8bba1d9bb --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/model_manifest.json @@ -0,0 +1,744 @@ +{ + "name": "direct-seasonal-foundation", + "contract": "timeseries-forecast/v1", + "parameters": 36601928, + "pretrained_assets": [], + "sources_used": [ + "gifteval_pretrain/BEIJING_SUBWAY_30MIN", + "gifteval_pretrain/HZMETRO", + "gifteval_pretrain/LOS_LOOP", + "gifteval_pretrain/PEMS03", + "gifteval_pretrain/PEMS04", + "gifteval_pretrain/PEMS07", + "gifteval_pretrain/PEMS08", + "gifteval_pretrain/PEMS_BAY", + "gifteval_pretrain/Q-TRAFFIC", + "gifteval_pretrain/SHMETRO", + "gifteval_pretrain/alibaba_cluster_trace_2018", + "gifteval_pretrain/australian_electricity_demand", + "gifteval_pretrain/azure_vm_traces_2017", + "gifteval_pretrain/bdg-2_bear", + "gifteval_pretrain/bdg-2_fox", + "gifteval_pretrain/bdg-2_panther", + "gifteval_pretrain/bdg-2_rat", + "gifteval_pretrain/bitcoin_with_missing", + "gifteval_pretrain/borealis", + "gifteval_pretrain/borg_cluster_data_2011", + "gifteval_pretrain/buildings_900k", + "gifteval_pretrain/bull", + "gifteval_pretrain/cdc_fluview_ilinet", + "gifteval_pretrain/cdc_fluview_who_nrevss", + "gifteval_pretrain/china_air_quality", + "gifteval_pretrain/cif_2016_12", + "gifteval_pretrain/cif_2016_6", + "gifteval_pretrain/cmip6_2000", + "gifteval_pretrain/cmip6_2005", + "gifteval_pretrain/cmip6_2010", + "gifteval_pretrain/cockatoo", + "gifteval_pretrain/covid19_energy", + "gifteval_pretrain/covid_mobility", + "gifteval_pretrain/elecdemand", + "gifteval_pretrain/elf", + "gifteval_pretrain/era5_2010", + "gifteval_pretrain/era5_2011", + "gifteval_pretrain/era5_2012", + "gifteval_pretrain/era5_2013", + "gifteval_pretrain/era5_2014", + "gifteval_pretrain/era5_2015", + "gifteval_pretrain/era5_2016", + "gifteval_pretrain/era5_2017", + "gifteval_pretrain/era5_2018", + "gifteval_pretrain/extended_web_traffic_with_missing", + "gifteval_pretrain/favorita_sales", + "gifteval_pretrain/favorita_transactions", + "gifteval_pretrain/gfc12_load", + "gifteval_pretrain/gfc14_load", + "gifteval_pretrain/gfc17_load", + "gifteval_pretrain/godaddy", + "gifteval_pretrain/hog", + "gifteval_pretrain/ideal", + "gifteval_pretrain/kaggle_web_traffic_weekly", + "gifteval_pretrain/kdd2022", + "gifteval_pretrain/largest_2017", + "gifteval_pretrain/largest_2018", + "gifteval_pretrain/largest_2019", + "gifteval_pretrain/largest_2020", + "gifteval_pretrain/largest_2021", + "gifteval_pretrain/lcl", + "gifteval_pretrain/london_smart_meters_with_missing", + "gifteval_pretrain/m1_monthly", + "gifteval_pretrain/m1_quarterly", + "gifteval_pretrain/m1_yearly", + "gifteval_pretrain/m5", + "gifteval_pretrain/monash_m3_monthly", + "gifteval_pretrain/monash_m3_other", + "gifteval_pretrain/monash_m3_quarterly", + "gifteval_pretrain/nn5_daily_with_missing", + "gifteval_pretrain/nn5_weekly", + "gifteval_pretrain/oikolab_weather", + "gifteval_pretrain/pdb", + "gifteval_pretrain/project_tycho", + "gifteval_pretrain/residential_load_power", + "gifteval_pretrain/residential_pv_power", + "gifteval_pretrain/rideshare_with_missing", + "gifteval_pretrain/sceaux", + "gifteval_pretrain/smart", + "gifteval_pretrain/solar_power", + "gifteval_pretrain/spain", + "gifteval_pretrain/subseasonal", + "gifteval_pretrain/subseasonal_precip", + "gifteval_pretrain/sunspot_with_missing", + "gifteval_pretrain/taxi_30min", + "gifteval_pretrain/tourism_quarterly", + "gifteval_pretrain/tourism_yearly", + "gifteval_pretrain/traffic_hourly", + "gifteval_pretrain/traffic_weekly", + "gifteval_pretrain/uber_tlc_daily", + "gifteval_pretrain/uber_tlc_hourly", + "gifteval_pretrain/vehicle_trips_with_missing", + "gifteval_pretrain/wiki-rolling_nips", + "gifteval_pretrain/wind_farms_with_missing", + "gifteval_pretrain/wind_power", + "synthetic:both original and sign-reflected orientations of each sampled allowed or locally generated window; paired quantile loss, seed 197", + "synthetic:both original and sign-reflected orientations of each sampled allowed or locally generated window; paired quantile loss, seed 401", + "synthetic:both original and sign-reflected orientations of each sampled window, seed 197", + "synthetic:independent sign reflection of sampled allowed-corpus and locally generated windows; seeds 43,47,59,79,89,197", + "synthetic:own direct_v1 Fourier seasons, damped trends, AR noise, changepoints and intermittent demand; seeds 23,43,47,59,79,89,197,401", + "synthetic:own random requested-horizon prefixes, half of rows retain the full horizon and half use a patch-rounded prefix between one-quarter and the full horizon; independent seed 300200", + "synthetic:own random requested-horizon prefixes, half of rows retain the full horizon and half use a patch-rounded prefix between one-quarter and the full horizon; independent seed 300404" + ], + "weights_sha256": "1a2fb20a9fb5cae6526f2e36ea47559626bece78fd9c284899836505030ae9fe", + "config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 4, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "input_patch": 8 + }, + "training_lineage": [ + { + "checkpoint": "runs/split_patch/ema012000.pt", + "sha256": "1a2fb20a9fb5cae6526f2e36ea47559626bece78fd9c284899836505030ae9fe", + "step": 12000, + "seed": 401, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 32, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300404 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 4, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "input_patch": 8 + }, + "parents": [ + "split_patch_initial.pt" + ] + }, + { + "checkpoint": "split_patch_initial.pt", + "sha256": "0719b4dce554764ef69181d8b19d8da11849ef32b35391ffee6700e639a73114", + "step": 0, + "seed": null, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 4, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "input_patch": 8 + }, + "conversion": { + "method": "retain input8; sum query/recency halves and keep first4 output rows; same physical position coordinates", + "exact_function_preservation": false, + "parent_sha256": "308389b7217c080af9eb185559d4ee3cafa0f3e0f8c4dd8f5526b68198c89988" + }, + "parents": [ + "runs/patch8/ema006000.pt", + "runs/patch8/ema006000.pt" + ] + }, + { + "checkpoint": "runs/patch8/ema006000.pt", + "sha256": "308389b7217c080af9eb185559d4ee3cafa0f3e0f8c4dd8f5526b68198c89988", + "step": 6000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "patch8_initial.pt" + ] + }, + { + "checkpoint": "patch8_initial.pt", + "sha256": "e7da4d47a9cc984a9423296679d7c9127ef2d679be950b9e8d3758e6fca074cc", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "from_checkpoint": "/run-state/workspace/research/horizon_delta12k.pt", + "from_sha256": "22c08571978be31ba57368eb983089a40a44d56d4ae5e17da41afd2a761a258c", + "method": "fold input/query/recency halves by summation; retain first8 output rows; preserve physical position units", + "exact_function_preservation": false + }, + "parents": [ + "horizon_delta12k.pt", + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "horizon_delta12k.pt", + "sha256": "22c08571978be31ba57368eb983089a40a44d56d4ae5e17da41afd2a761a258c", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/runs/confidence_query/ema006000.pt": "0bad97e8994aac49ea173443db0a4fa8d72d33f9eb9e2660f06de75f7f1403eb", + "/workspace/research/runs/horizon_jitter/ema012000.pt": "830179d763916a1065fc615d2c5e22f4a3b5b19390dde707ab0f057e13cadff6", + "/workspace/research/runs/large_corpus_control/ema012000.pt": "7f9ba5e01ac59c51a3b63d3067b442e23e15d0abc51ddbcccdd04d6083ae4add" + }, + "seconds": 1.2663014469435439 + }, + "parents": [ + "runs/confidence_query/ema006000.pt", + "runs/horizon_jitter/ema012000.pt", + "runs/large_corpus_control/ema012000.pt" + ] + }, + { + "checkpoint": "runs/confidence_query/ema006000.pt", + "sha256": "0bad97e8994aac49ea173443db0a4fa8d72d33f9eb9e2660f06de75f7f1403eb", + "step": 6000, + "seed": 89, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 0.0002, + "steps": 6000 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true + }, + "parents": [ + "runs/recency_features/ema024000.pt" + ] + }, + { + "checkpoint": "runs/horizon_jitter/ema012000.pt", + "sha256": "830179d763916a1065fc615d2c5e22f4a3b5b19390dde707ab0f057e13cadff6", + "step": 12000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "partial_target_lengths": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/large_corpus_control/ema012000.pt", + "sha256": "7f9ba5e01ac59c51a3b63d3067b442e23e15d0abc51ddbcccdd04d6083ae4add", + "step": 12000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/recency_features/ema024000.pt", + "sha256": "1530fbb577a87ca4eb39da83d6fee9b8ee5bc924202e021e3a7b56493112f564", + "step": 24000, + "seed": 59, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/patch16_trial/ema006000.pt" + ] + }, + { + "checkpoint": "runs/recency_features/ema012000.pt", + "sha256": "8ccb6870a025e1097331a3a288b1183741a413f3460fbf3352d0c589c6a4394c", + "step": 12000, + "seed": 59, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/patch16_trial/ema006000.pt" + ] + }, + { + "checkpoint": "runs/patch16_trial/ema006000.pt", + "sha256": "0ff54447074e0271d2e331c7d3e6e9e0fdd73353e4d8cef0175ff627385f71c3", + "step": 6000, + "seed": 47, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024 + }, + "parents": [ + "patch16_init.pt" + ] + }, + { + "checkpoint": "patch16_init.pt", + "sha256": "d69531bfde5bf801e7f36c515bf15fd0cae0bd84f7d1479d35f4a7b67f26b508", + "step": 6000, + "seed": 43, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024 + }, + "conversion": { + "from_checkpoint": "/run-state/workspace/research/runs/large_sign/ema006000.pt", + "from_sha256": "96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547", + "method": "fold input/query halves by summation; retain first 16 output rows; preserve physical positional units" + }, + "parents": [ + "runs/large_sign/ema006000.pt" + ] + }, + { + "checkpoint": "runs/large_sign/ema006000.pt", + "sha256": "96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547", + "step": 6000, + "seed": 43, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 32, + "max_context": 4096, + "max_horizon": 1024 + }, + "parents": [ + "runs/direct_large/step024000.pt" + ] + }, + { + "checkpoint": "runs/direct_large/step024000.pt", + "sha256": "b7e4f38aebcd2cf38ce484edaad8d19851317fb3b8df485e2faa0d0423cbcb48", + "step": 24000, + "seed": 23, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 128, + "lr": 0.0002, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 32, + "max_context": 4096, + "max_horizon": 1024 + }, + "initialization": "random initialization in this workspace" + } + ], + "symmetric_averaging": true, + "seasonal_gate": { + "variance_ratio_threshold": 0.25, + "maximum_weight": 0.98, + "cycles_averaged": 4, + "template_mode": "aligned", + "amplitude_ratio_clip": [ + 0.5, + 2.0 + ], + "latest_cycle_minimum_coverage": 0.75, + "variance_noise_correction": "mean squared seasonal differences / 2" + }, + "continuity": { + "decay_steps": 24, + "variance_ratio_threshold": 0.5, + "maximum_weight": 0.95, + "lookback": 512, + "slope_median_differences": 8 + }, + "notes": "All training lineage originates from random initialization here, using only the declared corpus and locally generated series. Validation was used only for selection and diagnostics. Context transformations are fixed formulas; there is no inference-time fitting or parameter adaptation.", + "runtime_code_sha256": { + "infer.sh": "5fe66b4fe9a4787285d830cfd96975701e97286a75ba7c3687bd8891475edf68", + "predict.py": "9bde896945a2cd8f892e7eeb6328ed2dfda09293532f3a4a64d929c9943614ef", + "zero_mass.py": "f079d509009bcda409b80eb64467c869b838cfbab11b2bd4c660c2875b6642fe", + "continuity.py": "dbb08d2229ad80ad00f638b0b9f2f6ca13c663e0fd6730058e5fee8ff54545d5", + "seasonal.py": "b946e63048196ab5ea8b249137d48c80d8510943caccd0f180e4fb86d9b24b37", + "model.py": "89bb87b2501b117ac02daf001a68f389ec488931ce18905445d15874760685be", + "ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436" + }, + "final_training_stage": { + "trainable_scope": "all parameters", + "sign_loss": "paired", + "learning_rate_multipliers": {} + }, + "trend_summary": { + "fixed_averaging_width": 128, + "matches_all_pretraining_context_widths": true, + "independent_of_batch_padding": true + }, + "zero_mass_projection": { + "threshold_in_context_standard_deviations": 0.4, + "nonnegative_context_required": true, + "minimum_exact_zeros": 4, + "minimum_zero_fraction": 0.1, + "context_cap": 4096 + }, + "recency_features": { + "query_projection_parameters": 8192, + "latest_vs_four_cycle_level": true, + "amplitude_ratio_clip": [ + 0.5, + 2.0 + ], + "minimum_observed_cycles": 3 + }, + "confidence_features": { + "query_projection_parameters": 3072, + "backbone_frozen_during_projection_training": true, + "training_objective": "weighted quantile and median loss after averaging both sign orientations", + "statistics": [ + "mean absolute difference", + "root mean square difference" + ], + "lags": "one and the two frequency-derived periods", + "lookback": "512 for lag one; eight cycles for seasonal lags", + "minimum_valid_pairs": 8, + "insufficient_pair_defaults": [ + 1, + 1.4142135623730951 + ], + "statistic_clip": 10, + "transform": "log1p", + "stage_scope": "Frozen-backbone details refer to projection introduction; subsequent updates are recorded in training_lineage.training_settings." + }, + "partial_target_training": { + "available_horizon": "last finite training-label position rounded up to the patch boundary", + "decoder_future_key_mask": true, + "per_row_horizon_metadata": true, + "inference_uses_requested_horizon_only": true + }, + "training_provenance_code_sha256": { + "confidence_query/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "confidence_query/model.py": "b4f11ba2018e2b50879cdc33acf0138301548971508b58035a7c96a29aaa6f2d", + "confidence_query/train.py": "fc8a7555a5a6b0a6f91e80ac8cc9cbbfddaa2b26468c57f49dfb17671b22ce93", + "direct_large/data.py": "6e6db217936f8dd79380d2ceff3eaa8598a44f1b60b17acae7bfde2363116847", + "direct_large/evaluate.py": "eaea99e8cd44c9f7c70a45fa9abf51354ae5449dbad273fcb55e48ad02652223", + "direct_large/model.py": "146d93a3f95b13bda8b1b437bc36621b91356cf946e94f62999f89e7fb348071", + "direct_large/pack.py": "3bcc4ce9eb3361ad741ceebd7efce7a2fb86fb49543f52c72aabd0e3e8cd17ce", + "direct_large/predict.py": "930a9f18f9f5da47c03859698c9d2f5567d1e1c73fd61edac1ed20b3a6f9bb50", + "direct_large/publish.py": "3c167f33e8571731c26f1cb70168eda54ef9cb4c76423dfd374240b75ca5f106", + "direct_large/record.py": "b3b00b0ed14bc3af00c7b1ad97195238ecb8f06e96bc41f0c07913bc3f6ed949", + "direct_large/train.py": "b9ad6b2adddeaf12961b529d6535dd33f6d044a31979b5c9e49dceafbadd3ac0", + "direct_large/ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "direct_large/validation_subset.py": "8d3eb9d3f3aa124368761ef402ff066935c0be31a62b25b8551a45dcb922e28d", + "full_paired/check.py": "90ac1c78846439d51ab8acd62a19bd536c7c394bd02e94f6d5ff17c0af8bd116", + "full_paired/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "full_paired/model.py": "c27748fa4b1186b513f76eca26052753b8dcd1794994e5989addaf371ca70f2e", + "horizon_jitter/data.py": "5044cf648323420095ed6058d29f837c07ff5559b606df8b00cc8d1e95c8b58e", + "horizon_jitter/model.py": "186bb282236f23cc665a012194d26e58f51004c680393352ec053f5308f1240f", + "horizon_jitter/train.py": "4e9cbca1293f18f7eea2c72dba127815c0934a13c86e8f6cc881a749676d41a6", + "large_corpus/data.py": "27c078cb0ed085717a364f556b5ff976fd803d5af37612cf3a03a0a3ca12a678", + "large_corpus/model.py": "e3a1bc01e89a0d6d750ede2cc969272ad01e1ca580b174af7dee00db029f1cf7", + "large_corpus/train.py": "3baca16c3945e6ef241ccbc9c13644539e3c265f71095cbbaa61a3d338e4fafe", + "large_sign/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "large_sign/evaluate.py": "eaea99e8cd44c9f7c70a45fa9abf51354ae5449dbad273fcb55e48ad02652223", + "large_sign/model.py": "3fff6445a1982a1b3c92f06a9b5f1bb627dda6a291b0b2364bcfb1a6457830d7", + "large_sign/pack.py": "3bcc4ce9eb3361ad741ceebd7efce7a2fb86fb49543f52c72aabd0e3e8cd17ce", + "large_sign/predict.py": "930a9f18f9f5da47c03859698c9d2f5567d1e1c73fd61edac1ed20b3a6f9bb50", + "large_sign/publish.py": "3c167f33e8571731c26f1cb70168eda54ef9cb4c76423dfd374240b75ca5f106", + "large_sign/record.py": "b3b00b0ed14bc3af00c7b1ad97195238ecb8f06e96bc41f0c07913bc3f6ed949", + "large_sign/train.py": "a597f40ab87cce04e96dc654d12e56cdf40ffd87f00034d8bc4d56dff4eb7c68", + "large_sign/ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "large_sign/validation_subset.py": "8d3eb9d3f3aa124368761ef402ff066935c0be31a62b25b8551a45dcb922e28d", + "partial_delta/merge.py": "63984a0f46f7d48817037f5bf5a1c9319e45a9b1924cde62c667ac49ce47532e", + "partial_targets/data.py": "27c078cb0ed085717a364f556b5ff976fd803d5af37612cf3a03a0a3ca12a678", + "partial_targets/model.py": "186bb282236f23cc665a012194d26e58f51004c680393352ec053f5308f1240f", + "partial_targets/train.py": "3baca16c3945e6ef241ccbc9c13644539e3c265f71095cbbaa61a3d338e4fafe", + "patch16/convert.py": "11e1d30100ab25311020ac1f4ab8227ec66156836df5de613300867977091c45", + "patch16/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "patch16/evaluate.py": "eaea99e8cd44c9f7c70a45fa9abf51354ae5449dbad273fcb55e48ad02652223", + "patch16/model.py": "8031c597b354eb2cf464140bee40c3ec8dff86c775b5c55c5ce910302b443582", + "patch16/pack.py": "3bcc4ce9eb3361ad741ceebd7efce7a2fb86fb49543f52c72aabd0e3e8cd17ce", + "patch16/predict.py": "930a9f18f9f5da47c03859698c9d2f5567d1e1c73fd61edac1ed20b3a6f9bb50", + "patch16/publish.py": "3c167f33e8571731c26f1cb70168eda54ef9cb4c76423dfd374240b75ca5f106", + "patch16/record.py": "b3b00b0ed14bc3af00c7b1ad97195238ecb8f06e96bc41f0c07913bc3f6ed949", + "patch16/train.py": "3156710f76111a31447cbe638ee27fe2811d060917aa083aab0b5134d98accf8", + "patch16/ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "patch16/validation_subset.py": "8d3eb9d3f3aa124368761ef402ff066935c0be31a62b25b8551a45dcb922e28d", + "patch8/convert.py": "9edaa0c8349310b7419d649fb4f21dd3ddb9067ebe984d5df3701a234be73780", + "patch8/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "patch8/memory_check.py": "78e8e5cca960bf1225ec0104980363c82f4c3c13c2d77ed154cea37a5b6f3fd1", + "patch8/model.py": "c27748fa4b1186b513f76eca26052753b8dcd1794994e5989addaf371ca70f2e", + "recency_features/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "recency_features/model.py": "e3a1bc01e89a0d6d750ede2cc969272ad01e1ca580b174af7dee00db029f1cf7", + "recency_features/train.py": "a654b9a27b6c27141e1d4e517ab28fcae3f2c23d061742fa2f6c01e3d23c8a00", + "recovery/capacity_curves.py": "2bdc6635705b70a868e115cd13eb529563acacf6f47c71f250a50dce8e943be4", + "recovery/exposure_audit.py": "54c194a626b8876ece84686b39b22360155c9fada7248a393ca9b7d6ee38002b", + "recovery/relaunch_20261022b.py": "f90ddd77928a793c8e151ba74cfa9cc84c8aefad0c0d943a833c74bc07b79313", + "recovery/relaunch_20261023.py": "a4c40c5674b0d05cfe9bb1fffe907f02dec16c53cbddb8b86efbba1b96649097", + "recovery/schedules.py": "7748fd6b2bbbe64037472faf7e6583d03cf339138d2f3c07b1bac9e65bf2d4f5", + "recovery/snapshot.py": "0f241a7e139e47ffff7efea40572205fd84c12efe6fb3c2dccd87c50d678a6c3", + "recovery/train.py": "63bee736565af670877b4cd7c75015fab06a18c66bbe132b0bb3faff5ebd80c7", + "split_patch/check.py": "2e0917eec4b70741da84f62ba19d709229fefa29fd46a8b85dd91976952560f9", + "split_patch/convert.py": "115b3f518a2157529a3c26143dabd736abc8494b7f20cdd9bea57d569d77c36e", + "split_patch/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "split_patch/launch.py": "014b171e8b8dc1f4b84242a02813af1ee8b26c3b4dc839148718caf36d77ae77", + "split_patch/memory_check.py": "8a6f6af761ac37fb5118f71e38bba0ca5c446e5c1203b9e156657e7d68a5d3e9", + "split_patch/model.py": "89bb87b2501b117ac02daf001a68f389ec488931ce18905445d15874760685be" + } +} diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/confidence_query/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/confidence_query/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/confidence_query/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/confidence_query/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/confidence_query/model.py new file mode 100644 index 0000000000000000000000000000000000000000..b881039b3752b3396e06415a8d01d24956fa29a7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/confidence_query/model.py @@ -0,0 +1,190 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + if self.recency is not None: + pos=torch.arange(c,device=z.device)[None,:];extras=[] + for j in range(2): + period=periods[:,j:j+1] + recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + n=ctx.shape[0] + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1]) + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/confidence_query/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/confidence_query/train.py new file mode 100644 index 0000000000000000000000000000000000000000..fd9d2a3a0502cee1a67c41c832266c7f87cc5a80 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/confidence_query/train.py @@ -0,0 +1,54 @@ +"""Train only confidence-query features on a frozen model, using paired-sign forecast loss.""" +import argparse,json,math,time,os +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) +ap.add_argument('--initialize-from',required=True);ap.add_argument('--steps',type=int,default=6000) +ap.add_argument('--batch',type=int,default=128);ap.add_argument('--lr',type=float,default=2e-4) +ap.add_argument('--seed',type=int,default=89);ap.add_argument('--save-every',type=int,default=1000);a=ap.parse_args() +torch.set_num_threads(1);torch.manual_seed(a.seed);torch.backends.cuda.matmul.allow_tf32=True +out=Path(a.out);out.mkdir(parents=True,exist_ok=True) +ck=torch.load(a.initialize_from,map_location='cpu',weights_only=False) +config={**ck['config'],'confidence_features':True};model=DirectForecaster(**config).cuda() +missing,unexpected=model.load_state_dict(ck['model'],strict=False) +assert not unexpected and all(k.startswith('confidence.') for k in missing) +for name,param in model.named_parameters():param.requires_grad_(name.startswith('confidence.')) +params=[p for p in model.parameters() if p.requires_grad] +opt=torch.optim.AdamW(params,lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) +ema={k:v.detach().clone() for k,v in model.state_dict().items()};sampler=Sampler(a.packed,seed=a.seed) +(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)) +rng=np.random.default_rng(a.seed) +def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) +def save(step): + for prefix,weights in [('step',model.state_dict()),('ema',ema)]: + state={'model':weights,'config':model.config,'step':step,'args':vars(a),'ema':prefix=='ema'} + path=out/f'{prefix}{step:06d}.pt';torch.save(state,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) +save(0);pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] +for step in range(1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch);x,y,p=[torch.from_numpy(x).cuda() for x in arrays] + lr=a.lr*min(1,step/200)*(.2+.8*.5*(1+math.cos(math.pi*step/a.steps))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(params,1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items(): + if k.startswith('confidence.'):ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + if step%a.save_every==0 or step==a.steps:save(step) +pool.shutdown() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/direct_large/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/direct_large/data.py new file mode 100644 index 0000000000000000000000000000000000000000..2378e33d7352ba5ad97d566148782e63e64b367c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/direct_large/data.py @@ -0,0 +1,71 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + return ctx,tgt,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/direct_large/evaluate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/direct_large/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..05f086d4d84def4a48165f9e65d2948877675e56 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/direct_large/evaluate.py @@ -0,0 +1,16 @@ +import sys,json,argparse,time,hashlib +from pathlib import Path +import torch +from predict import load_model,run +sys.path.insert(0,'/workspace/evaluation') +from score import score,json_safe + +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);ap.add_argument('--valid',default='/workspace/research/valid_screen');ap.add_argument('--baseline',default='/workspace/research/valid_screen/baseline.json');a=ap.parse_args() +torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cuda.matmul.allow_tf32=False +t0=time.time();out=Path(a.out);v=Path(a.valid) +run(load_model(a.weights),v/'input',out) +base=json.loads(Path(a.baseline).read_text())['configs'] +rep=score(v/'truth',out,base) +rep['checkpoint_sha256']=hashlib.sha256(Path(a.weights).read_bytes()).hexdigest();rep['eval_seconds']=time.time()-t0 +(out/'report.json').write_text(json.dumps(json_safe(rep),indent=1)) +print(json.dumps({k:rep[k] for k in ('skill_score','rel_mase_gmean','rel_wql_gmean','n_failed','groups','eval_seconds')},indent=1)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/direct_large/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/direct_large/model.py new file mode 100644 index 0000000000000000000000000000000000000000..7a224cc12a159446a1e427b2052b53d1d1f7e83e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/direct_large/model.py @@ -0,0 +1,142 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional(torch.arange(-nt,0,device=z.device),self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + q=self.query(base.reshape(b,h//p,p*9))+positional(torch.arange(h//p,device=z.device),self.d)[None]+emb + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + pin=torch.maximum(levels*err,(levels-1)*err).mean(-1) + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + return per.mean() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/direct_large/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/direct_large/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/direct_large/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/direct_large/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/direct_large/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..e20c6630475d6b4fa6906eb4ed9454b7b5aeec2c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/direct_large/predict.py @@ -0,0 +1,43 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):q=model.predict(x,p,h).float().cpu().numpy() + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/direct_large/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/direct_large/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf95c9aec5936076b881c340edb960786f2d40d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/direct_large/publish.py @@ -0,0 +1,31 @@ +"""Assemble a relocatable package, then atomically exchange complete directories.""" +import json,os,shutil,ctypes,hashlib,argparse +from pathlib import Path +import torch +HERE=Path(__file__).resolve().parent + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',default='/workspace/submission');ap.add_argument('--report',required=True);ap.add_argument('--experiments',default=str(HERE/'EXPERIMENTS.md'));a=ap.parse_args() + final=Path(a.out);staging=final.parent/f'.{final.name}-staging-{os.getpid()}' + shutil.rmtree(staging,ignore_errors=True);staging.mkdir(parents=True) + for file in ('model.py','predict.py','infer.sh','ts_io.py'): + shutil.copy(HERE/file,staging/file) + shutil.copy(a.weights,staging/'weights.pt');shutil.copy('/opt/runtime/requirements.txt',staging/'requirements.txt') + ck=torch.load(a.weights,map_location='cpu',weights_only=False);digest=hashlib.sha256((staging/'weights.pt').read_bytes()).hexdigest() + sources=json.loads(Path('/workspace/research/packed_sample/meta.json').read_text())['dirs'] + manifest={'name':'direct-seasonal-quantile-v1','contract':'timeseries-forecast/v1','parameters':sum(x.numel() for x in ck['model'].values()),'pretrained_assets':[],'sources_used':[f'gifteval_pretrain/{d}' for d in sources]+['synthetic:direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; data.py generator seed 17'],'weights_sha256':digest,'training_step':ck['step'],'config':ck['config'],'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.'} + (staging/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') + (staging/'config.json').write_text(json.dumps(ck['config'],indent=2)+'\n') + shutil.copy(a.experiments,staging/'EXPERIMENTS.md');shutil.copy(a.report,staging/'validation_report.json') + # Include generator/sampler provenance, which is not imported by inference. + (staging/'provenance').mkdir() + for file in ('pack.py','data.py','train.py'):shutil.copy(HERE/file,staging/'provenance'/file) + (staging/'README.md').write_text('# Direct seasonal quantile foundation forecaster\n\nRun `bash infer.sh INPUT_DIR OUTPUT_DIR`. This package contains all inference assets and uses only its supplied input directory. The 6.76M 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.\n\nThe 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.\n') + if final.exists(): + libc=ctypes.CDLL(None,use_errno=True) + if libc.renameat2(-100,os.fsencode(staging),-100,os.fsencode(final),2):raise OSError(ctypes.get_errno(),os.strerror(ctypes.get_errno())) + shutil.rmtree(staging) + else:os.replace(staging,final) + print(json.dumps(manifest,indent=1)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/direct_large/record.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/direct_large/record.py new file mode 100644 index 0000000000000000000000000000000000000000..1850a33f46fa3ee4d78cac4a5d6152404801a131 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/direct_large/record.py @@ -0,0 +1,9 @@ +import argparse,json,math +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('report');ap.add_argument('--label',required=True);ap.add_argument('--outcome',default='Screened for model selection.');a=ap.parse_args() +r=json.loads(Path(a.report).read_text());p=Path(__file__).with_name('EXPERIMENTS.md') +lines=[f'\n## {a.label}',f'- Checkpoint SHA-256: `{r.get("checkpoint_sha256","see model_manifest.json")}`.',f'- Evaluation: {r["n_configs"]} configurations, {r["n_instances"]} instances, {r["n_failed"]} failed configurations; {r.get("eval_seconds","not separately timed")} seconds.',f'- Overall skill {r["skill_score"]:.6f}; relative MASE {r["rel_mase_gmean"]:.6f}; relative WQL {r["rel_wql_gmean"]:.6f}.'] +for group,entries in r['groups'].items(): + lines.append(f'- {group} skill: '+', '.join(f'{k}={1-math.sqrt(v["rel_mase_gmean"]*v["rel_wql_gmean"]):.4f}' for k,v in entries.items())+'.') +lines.append('- Outcome: '+a.outcome) +with p.open('a') as f:f.write('\n'.join(lines)+'\n') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/direct_large/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/direct_large/train.py new file mode 100644 index 0000000000000000000000000000000000000000..a2ccc736bfef804259199a2dd315347d9854b680 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/direct_large/train.py @@ -0,0 +1,67 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(6);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/direct_large/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/direct_large/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/direct_large/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/direct_large/validation_subset.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/direct_large/validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..4df83e69c4f9a3365955e5d17ffcfc0af71372b7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/direct_large/validation_subset.py @@ -0,0 +1,18 @@ +"""Model-selection-only subset spanning all 97 configurations, seed 2026.""" +import sys,json,copy +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +import ts_io + +root=Path('/workspace/data/valid');out=Path('/workspace/research/valid_screen') +idx=json.loads((root/'input/index.json').read_text());new=copy.deepcopy(idx);rng=np.random.default_rng(2026) +for cfg in new['configs']: + cid=cfg['config_id'];case=ts_io.CaseFile(root/'input/cases'/f'{cid}.h5') + ids=np.sort(rng.choice(case.n,min(case.n,192),replace=False)) + ts_io.write_case_subset(case,ids,out/'input/cases'/f'{cid}.h5') + lab,se,meta=ts_io.read_truth_file(root/'truth/cases'/f'{cid}.h5') + ts_io.write_truth_file(out/'truth/cases'/f'{cid}.h5',lab[ids],se[ids],meta) + cfg['n_instances']=len(ids);case.close() +for kind in ('input','truth'):(out/kind/'index.json').write_text(json.dumps(new,indent=1)) +print('screen instances',sum(c['n_instances'] for c in new['configs'])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/full_paired/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/full_paired/check.py new file mode 100644 index 0000000000000000000000000000000000000000..fda928e16338305fd9912f7bc08cacff58bd8aa4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/full_paired/check.py @@ -0,0 +1,34 @@ +import importlib.util,json,time +from pathlib import Path +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +r=Path('/workspace/research');torch.set_num_threads(1);torch.manual_seed(197);start=time.monotonic() +ck=torch.load(r/'horizon_delta12k.pt',map_location='cpu',weights_only=False) +spec=importlib.util.spec_from_file_location('parent_model',r/'confidence_inference/model.py') +old=importlib.util.module_from_spec(spec);spec.loader.exec_module(old) +parent=old.DirectForecaster(**ck['config']);parent.load_state_dict(ck['model']) +m=DirectForecaster(**ck['config']);m.load_state_dict(ck['model']) +x=torch.randn(4,512);x[0,:50]=float('nan');p=torch.tensor([[24,168]]*4);y=torch.randn(4,128);y[0,32:]=float('nan') +with torch.inference_mode(): + assert all(torch.equal(a,b) for a,b in zip(m(x,p,48),parent(x,p,48))) + short=m(x,p,32)[0];long=m(x,p,128,forecast_lengths=torch.full((4,),32))[0][:,:32] + assert torch.allclose(short,long,atol=3e-6,rtol=1e-6),(short-long).abs().max() + paired=float(loss_fn(m,x,y,p,paired=True));reverse=float(loss_fn(m,-x,-y,p,paired=True)) + assert abs(paired-reverse)<1e-7,(paired,reverse) +a=Sampler(r/'packed_sample',197);b=Sampler(r/'packed_sample',197) +for c,h in [(512,32),(4096,1024)]: + assert all(np.array_equal(v,w,equal_nan=True) for v,w in zip(a.sample(16,c,h),b.sample(16,c,h))) +assert a.rng.bit_generator.state==b.rng.bit_generator.state and a.horizon_rng.bit_generator.state==b.horizon_rng.bit_generator.state +cpu=time.monotonic()-start;del parent,ck,a,b +m=m.cuda();ema={k:v.detach().clone() for k,v in m.state_dict().items()} +moments=[torch.zeros_like(v) for v in m.parameters() for _ in range(2)] +torch.backends.cuda.matmul.allow_tf32=True;torch.cuda.reset_peak_memory_stats();start=time.monotonic() +x=torch.randn(64,4096,device='cuda');y=torch.randn(64,1024,device='cuda');p=torch.tensor([[24,168]]*64,device='cuda') +with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(m,x,y,p,paired=True) +loss.backward();torch.cuda.synchronize() +assert torch.isfinite(loss) and all(v.grad is not None and torch.isfinite(v.grad).all() for v in m.parameters()) +z={'cpu_seconds':cpu,'initial_forecast_bitwise_parent':True,'unused_future_tokens_do_not_change_requested_prefix':True,'paired_loss_sign_symmetric':True,'matched_sampler_main_and_horizon_rng':True,'gpu_fixture_seconds':time.monotonic()-start,'allocated_mib':torch.cuda.max_memory_allocated()/2**20,'reserved_mib':torch.cuda.max_memory_reserved()/2**20,'optimizer_updates':0} +(r/'full_paired_checks.json').write_text(json.dumps(z,indent=2));print(json.dumps(z),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/full_paired/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/full_paired/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/full_paired/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/full_paired/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/full_paired/model.py new file mode 100644 index 0000000000000000000000000000000000000000..dedcdff4698028a8ba655865f8425d0dc3ef0dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/full_paired/model.py @@ -0,0 +1,204 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/horizon_jitter/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/horizon_jitter/data.py new file mode 100644 index 0000000000000000000000000000000000000000..3d632af7e96a71f30b7964a2b3fd73bc1c3f3f3e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/horizon_jitter/data.py @@ -0,0 +1,86 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/horizon_jitter/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/horizon_jitter/model.py new file mode 100644 index 0000000000000000000000000000000000000000..4ffe50d9aadf21d73949e2052ceb7f3642bf65d3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/horizon_jitter/model.py @@ -0,0 +1,180 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(ctx,periods,target.shape[-1],forecast_lengths=lengths) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/horizon_jitter/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/horizon_jitter/train.py new file mode 100644 index 0000000000000000000000000000000000000000..768d33da4421b24bd760d7d9680d0c2cd9bd84e4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/horizon_jitter/train.py @@ -0,0 +1,74 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler,truncate_targets + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + horizon_rng=np.random.default_rng(a.seed+startstep+300003) + def nextbatch(): + 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])) + return truncate_targets(sampler.sample(a.batch,c,h),horizon_rng,a.patch) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_corpus/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_corpus/data.py new file mode 100644 index 0000000000000000000000000000000000000000..a51e912d3c4b63a3ec0cd85133bf0e7aa3429569 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_corpus/data.py @@ -0,0 +1,73 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_corpus/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_corpus/model.py new file mode 100644 index 0000000000000000000000000000000000000000..f8271c5b0bf9a5edb961e1c7839761fe50a2e40b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_corpus/model.py @@ -0,0 +1,171 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024,recency_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + if self.recency is not None: + pos=torch.arange(c,device=z.device)[None,:];extras=[] + for j in range(2): + period=periods[:,j:j+1] + recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_corpus/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_corpus/train.py new file mode 100644 index 0000000000000000000000000000000000000000..2e77612e443d78dd80bcb6a0cc6d01169f61a3a4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_corpus/train.py @@ -0,0 +1,73 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_sign/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_sign/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_sign/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_sign/evaluate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_sign/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..05f086d4d84def4a48165f9e65d2948877675e56 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_sign/evaluate.py @@ -0,0 +1,16 @@ +import sys,json,argparse,time,hashlib +from pathlib import Path +import torch +from predict import load_model,run +sys.path.insert(0,'/workspace/evaluation') +from score import score,json_safe + +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);ap.add_argument('--valid',default='/workspace/research/valid_screen');ap.add_argument('--baseline',default='/workspace/research/valid_screen/baseline.json');a=ap.parse_args() +torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cuda.matmul.allow_tf32=False +t0=time.time();out=Path(a.out);v=Path(a.valid) +run(load_model(a.weights),v/'input',out) +base=json.loads(Path(a.baseline).read_text())['configs'] +rep=score(v/'truth',out,base) +rep['checkpoint_sha256']=hashlib.sha256(Path(a.weights).read_bytes()).hexdigest();rep['eval_seconds']=time.time()-t0 +(out/'report.json').write_text(json.dumps(json_safe(rep),indent=1)) +print(json.dumps({k:rep[k] for k in ('skill_score','rel_mase_gmean','rel_wql_gmean','n_failed','groups','eval_seconds')},indent=1)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_sign/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_sign/model.py new file mode 100644 index 0000000000000000000000000000000000000000..60aeb14b5f4fa298521ddce8a3276d076c1bb631 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_sign/model.py @@ -0,0 +1,154 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional(torch.arange(-nt,0,device=z.device),self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + q=self.query(base.reshape(b,h//p,p*9))+positional(torch.arange(h//p,device=z.device),self.d)[None]+emb + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_sign/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_sign/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_sign/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_sign/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_sign/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..e20c6630475d6b4fa6906eb4ed9454b7b5aeec2c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_sign/predict.py @@ -0,0 +1,43 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):q=model.predict(x,p,h).float().cpu().numpy() + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_sign/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_sign/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf95c9aec5936076b881c340edb960786f2d40d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_sign/publish.py @@ -0,0 +1,31 @@ +"""Assemble a relocatable package, then atomically exchange complete directories.""" +import json,os,shutil,ctypes,hashlib,argparse +from pathlib import Path +import torch +HERE=Path(__file__).resolve().parent + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',default='/workspace/submission');ap.add_argument('--report',required=True);ap.add_argument('--experiments',default=str(HERE/'EXPERIMENTS.md'));a=ap.parse_args() + final=Path(a.out);staging=final.parent/f'.{final.name}-staging-{os.getpid()}' + shutil.rmtree(staging,ignore_errors=True);staging.mkdir(parents=True) + for file in ('model.py','predict.py','infer.sh','ts_io.py'): + shutil.copy(HERE/file,staging/file) + shutil.copy(a.weights,staging/'weights.pt');shutil.copy('/opt/runtime/requirements.txt',staging/'requirements.txt') + ck=torch.load(a.weights,map_location='cpu',weights_only=False);digest=hashlib.sha256((staging/'weights.pt').read_bytes()).hexdigest() + sources=json.loads(Path('/workspace/research/packed_sample/meta.json').read_text())['dirs'] + manifest={'name':'direct-seasonal-quantile-v1','contract':'timeseries-forecast/v1','parameters':sum(x.numel() for x in ck['model'].values()),'pretrained_assets':[],'sources_used':[f'gifteval_pretrain/{d}' for d in sources]+['synthetic:direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; data.py generator seed 17'],'weights_sha256':digest,'training_step':ck['step'],'config':ck['config'],'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.'} + (staging/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') + (staging/'config.json').write_text(json.dumps(ck['config'],indent=2)+'\n') + shutil.copy(a.experiments,staging/'EXPERIMENTS.md');shutil.copy(a.report,staging/'validation_report.json') + # Include generator/sampler provenance, which is not imported by inference. + (staging/'provenance').mkdir() + for file in ('pack.py','data.py','train.py'):shutil.copy(HERE/file,staging/'provenance'/file) + (staging/'README.md').write_text('# Direct seasonal quantile foundation forecaster\n\nRun `bash infer.sh INPUT_DIR OUTPUT_DIR`. This package contains all inference assets and uses only its supplied input directory. The 6.76M 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.\n\nThe 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.\n') + if final.exists(): + libc=ctypes.CDLL(None,use_errno=True) + if libc.renameat2(-100,os.fsencode(staging),-100,os.fsencode(final),2):raise OSError(ctypes.get_errno(),os.strerror(ctypes.get_errno())) + shutil.rmtree(staging) + else:os.replace(staging,final) + print(json.dumps(manifest,indent=1)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_sign/record.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_sign/record.py new file mode 100644 index 0000000000000000000000000000000000000000..1850a33f46fa3ee4d78cac4a5d6152404801a131 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_sign/record.py @@ -0,0 +1,9 @@ +import argparse,json,math +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('report');ap.add_argument('--label',required=True);ap.add_argument('--outcome',default='Screened for model selection.');a=ap.parse_args() +r=json.loads(Path(a.report).read_text());p=Path(__file__).with_name('EXPERIMENTS.md') +lines=[f'\n## {a.label}',f'- Checkpoint SHA-256: `{r.get("checkpoint_sha256","see model_manifest.json")}`.',f'- Evaluation: {r["n_configs"]} configurations, {r["n_instances"]} instances, {r["n_failed"]} failed configurations; {r.get("eval_seconds","not separately timed")} seconds.',f'- Overall skill {r["skill_score"]:.6f}; relative MASE {r["rel_mase_gmean"]:.6f}; relative WQL {r["rel_wql_gmean"]:.6f}.'] +for group,entries in r['groups'].items(): + lines.append(f'- {group} skill: '+', '.join(f'{k}={1-math.sqrt(v["rel_mase_gmean"]*v["rel_wql_gmean"]):.4f}' for k,v in entries.items())+'.') +lines.append('- Outcome: '+a.outcome) +with p.open('a') as f:f.write('\n'.join(lines)+'\n') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_sign/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_sign/train.py new file mode 100644 index 0000000000000000000000000000000000000000..d089166fb1612ddf4955fcd2f096cb0b33624dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_sign/train.py @@ -0,0 +1,70 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(3);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_sign/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_sign/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_sign/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_sign/validation_subset.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_sign/validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..4df83e69c4f9a3365955e5d17ffcfc0af71372b7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/large_sign/validation_subset.py @@ -0,0 +1,18 @@ +"""Model-selection-only subset spanning all 97 configurations, seed 2026.""" +import sys,json,copy +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +import ts_io + +root=Path('/workspace/data/valid');out=Path('/workspace/research/valid_screen') +idx=json.loads((root/'input/index.json').read_text());new=copy.deepcopy(idx);rng=np.random.default_rng(2026) +for cfg in new['configs']: + cid=cfg['config_id'];case=ts_io.CaseFile(root/'input/cases'/f'{cid}.h5') + ids=np.sort(rng.choice(case.n,min(case.n,192),replace=False)) + ts_io.write_case_subset(case,ids,out/'input/cases'/f'{cid}.h5') + lab,se,meta=ts_io.read_truth_file(root/'truth/cases'/f'{cid}.h5') + ts_io.write_truth_file(out/'truth/cases'/f'{cid}.h5',lab[ids],se[ids],meta) + cfg['n_instances']=len(ids);case.close() +for kind in ('input','truth'):(out/kind/'index.json').write_text(json.dumps(new,indent=1)) +print('screen instances',sum(c['n_instances'] for c in new['configs'])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/partial_delta/merge.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/partial_delta/merge.py new file mode 100644 index 0000000000000000000000000000000000000000..3dde47d52d25ed2b013942b3887f1bf686e42ed8 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/partial_delta/merge.py @@ -0,0 +1,16 @@ +"""Apply the difference of two matched, locally trained checkpoints to our selected model.""" +import argparse,torch,hashlib,json,time +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('--base',required=True);ap.add_argument('--candidate',required=True);ap.add_argument('--control',required=True);ap.add_argument('--out',required=True);a=ap.parse_args() +torch.set_num_threads(1);start=time.monotonic() +base=torch.load(a.base,map_location='cpu',weights_only=False);candidate=torch.load(a.candidate,map_location='cpu',weights_only=False);control=torch.load(a.control,map_location='cpu',weights_only=False) +assert set(candidate['model'])==set(control['model']) +weights={k:v.clone() for k,v in base['model'].items()} +for k in candidate['model']: + assert k in weights and weights[k].shape==candidate['model'][k].shape==control['model'][k].shape + weights[k].add_(candidate['model'][k]-control['model'][k]) +assert all(torch.isfinite(v).all() for v in weights.values()) +parents=[a.base,a.candidate,a.control] +conversion={'method':'matched training delta','formula':'base + candidate - control','coefficient':1.0,'parent_hashes':{p:hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in parents},'seconds':time.monotonic()-start} +ck={'model':weights,'config':base['config'],'step':0,'args':{'packed':base['args']['packed']},'parent_checkpoints':parents,'conversion':conversion} +torch.save(ck,a.out);print(json.dumps(conversion)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/partial_targets/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/partial_targets/data.py new file mode 100644 index 0000000000000000000000000000000000000000..a51e912d3c4b63a3ec0cd85133bf0e7aa3429569 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/partial_targets/data.py @@ -0,0 +1,73 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/partial_targets/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/partial_targets/model.py new file mode 100644 index 0000000000000000000000000000000000000000..4ffe50d9aadf21d73949e2052ceb7f3642bf65d3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/partial_targets/model.py @@ -0,0 +1,180 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(ctx,periods,target.shape[-1],forecast_lengths=lengths) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/partial_targets/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/partial_targets/train.py new file mode 100644 index 0000000000000000000000000000000000000000..2e77612e443d78dd80bcb6a0cc6d01169f61a3a4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/partial_targets/train.py @@ -0,0 +1,73 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/convert.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/convert.py new file mode 100644 index 0000000000000000000000000000000000000000..b2cbc8fc919be6a77eca9ab19c4faa06060a2e0d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/convert.py @@ -0,0 +1,18 @@ +"""Convert only our own trained checkpoint from 32- to 16-point patches. + +Context/query projections fold the two halves by summation, preserving the +embedding of constant features. The output projection keeps the first half. +Attention/MLP weights are inherited unchanged; position units remain 32 points. +""" +import argparse,torch,hashlib +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('--input',required=True);ap.add_argument('--output',required=True);a=ap.parse_args() +ck=torch.load(a.input,map_location='cpu',weights_only=False);state=ck['model'];d=ck['config']['d'];assert ck['config']['patch']==32 +old=state['embed.0.weight'].reshape(d,2,32);state['embed.0.weight']=(old[:,:,:16]+old[:,:,16:]).reshape(d,32) +old=state['query.0.weight'].reshape(d,32,9);state['query.0.weight']=(old[:,:16]+old[:,16:]).reshape(d,16*9) +state['head.weight']=state['head.weight'].reshape(32,18,d)[:16].reshape(16*18,d).clone() +state['head.bias']=state['head.bias'].reshape(32,18)[:16].reshape(16*18).clone() +ck['config']['patch']=16 +ck['conversion']={'from_checkpoint':str(Path(a.input).resolve()),'from_sha256':hashlib.sha256(Path(a.input).read_bytes()).hexdigest(),'method':'fold input/query halves by summation; retain first 16 output rows; preserve physical positional units'} +ck['args']={**ck['args'],'initialize_from':str(Path(a.input).resolve()),'converted':True} +torch.save(ck,a.output) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/evaluate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..05f086d4d84def4a48165f9e65d2948877675e56 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/evaluate.py @@ -0,0 +1,16 @@ +import sys,json,argparse,time,hashlib +from pathlib import Path +import torch +from predict import load_model,run +sys.path.insert(0,'/workspace/evaluation') +from score import score,json_safe + +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);ap.add_argument('--valid',default='/workspace/research/valid_screen');ap.add_argument('--baseline',default='/workspace/research/valid_screen/baseline.json');a=ap.parse_args() +torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cuda.matmul.allow_tf32=False +t0=time.time();out=Path(a.out);v=Path(a.valid) +run(load_model(a.weights),v/'input',out) +base=json.loads(Path(a.baseline).read_text())['configs'] +rep=score(v/'truth',out,base) +rep['checkpoint_sha256']=hashlib.sha256(Path(a.weights).read_bytes()).hexdigest();rep['eval_seconds']=time.time()-t0 +(out/'report.json').write_text(json.dumps(json_safe(rep),indent=1)) +print(json.dumps({k:rep[k] for k in ('skill_score','rel_mase_gmean','rel_wql_gmean','n_failed','groups','eval_seconds')},indent=1)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/model.py new file mode 100644 index 0000000000000000000000000000000000000000..06cce56e2ce671b6683f0246900abfcac06bb3c0 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/model.py @@ -0,0 +1,154 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..e20c6630475d6b4fa6906eb4ed9454b7b5aeec2c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/predict.py @@ -0,0 +1,43 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):q=model.predict(x,p,h).float().cpu().numpy() + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf95c9aec5936076b881c340edb960786f2d40d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/publish.py @@ -0,0 +1,31 @@ +"""Assemble a relocatable package, then atomically exchange complete directories.""" +import json,os,shutil,ctypes,hashlib,argparse +from pathlib import Path +import torch +HERE=Path(__file__).resolve().parent + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',default='/workspace/submission');ap.add_argument('--report',required=True);ap.add_argument('--experiments',default=str(HERE/'EXPERIMENTS.md'));a=ap.parse_args() + final=Path(a.out);staging=final.parent/f'.{final.name}-staging-{os.getpid()}' + shutil.rmtree(staging,ignore_errors=True);staging.mkdir(parents=True) + for file in ('model.py','predict.py','infer.sh','ts_io.py'): + shutil.copy(HERE/file,staging/file) + shutil.copy(a.weights,staging/'weights.pt');shutil.copy('/opt/runtime/requirements.txt',staging/'requirements.txt') + ck=torch.load(a.weights,map_location='cpu',weights_only=False);digest=hashlib.sha256((staging/'weights.pt').read_bytes()).hexdigest() + sources=json.loads(Path('/workspace/research/packed_sample/meta.json').read_text())['dirs'] + manifest={'name':'direct-seasonal-quantile-v1','contract':'timeseries-forecast/v1','parameters':sum(x.numel() for x in ck['model'].values()),'pretrained_assets':[],'sources_used':[f'gifteval_pretrain/{d}' for d in sources]+['synthetic:direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; data.py generator seed 17'],'weights_sha256':digest,'training_step':ck['step'],'config':ck['config'],'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.'} + (staging/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') + (staging/'config.json').write_text(json.dumps(ck['config'],indent=2)+'\n') + shutil.copy(a.experiments,staging/'EXPERIMENTS.md');shutil.copy(a.report,staging/'validation_report.json') + # Include generator/sampler provenance, which is not imported by inference. + (staging/'provenance').mkdir() + for file in ('pack.py','data.py','train.py'):shutil.copy(HERE/file,staging/'provenance'/file) + (staging/'README.md').write_text('# Direct seasonal quantile foundation forecaster\n\nRun `bash infer.sh INPUT_DIR OUTPUT_DIR`. This package contains all inference assets and uses only its supplied input directory. The 6.76M 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.\n\nThe 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.\n') + if final.exists(): + libc=ctypes.CDLL(None,use_errno=True) + if libc.renameat2(-100,os.fsencode(staging),-100,os.fsencode(final),2):raise OSError(ctypes.get_errno(),os.strerror(ctypes.get_errno())) + shutil.rmtree(staging) + else:os.replace(staging,final) + print(json.dumps(manifest,indent=1)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/record.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/record.py new file mode 100644 index 0000000000000000000000000000000000000000..1850a33f46fa3ee4d78cac4a5d6152404801a131 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/record.py @@ -0,0 +1,9 @@ +import argparse,json,math +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('report');ap.add_argument('--label',required=True);ap.add_argument('--outcome',default='Screened for model selection.');a=ap.parse_args() +r=json.loads(Path(a.report).read_text());p=Path(__file__).with_name('EXPERIMENTS.md') +lines=[f'\n## {a.label}',f'- Checkpoint SHA-256: `{r.get("checkpoint_sha256","see model_manifest.json")}`.',f'- Evaluation: {r["n_configs"]} configurations, {r["n_instances"]} instances, {r["n_failed"]} failed configurations; {r.get("eval_seconds","not separately timed")} seconds.',f'- Overall skill {r["skill_score"]:.6f}; relative MASE {r["rel_mase_gmean"]:.6f}; relative WQL {r["rel_wql_gmean"]:.6f}.'] +for group,entries in r['groups'].items(): + lines.append(f'- {group} skill: '+', '.join(f'{k}={1-math.sqrt(v["rel_mase_gmean"]*v["rel_wql_gmean"]):.4f}' for k,v in entries.items())+'.') +lines.append('- Outcome: '+a.outcome) +with p.open('a') as f:f.write('\n'.join(lines)+'\n') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/train.py new file mode 100644 index 0000000000000000000000000000000000000000..3cdc106980371c99d81c71d6746943c47206be83 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/train.py @@ -0,0 +1,71 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(3);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/validation_subset.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..4df83e69c4f9a3365955e5d17ffcfc0af71372b7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch16/validation_subset.py @@ -0,0 +1,18 @@ +"""Model-selection-only subset spanning all 97 configurations, seed 2026.""" +import sys,json,copy +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +import ts_io + +root=Path('/workspace/data/valid');out=Path('/workspace/research/valid_screen') +idx=json.loads((root/'input/index.json').read_text());new=copy.deepcopy(idx);rng=np.random.default_rng(2026) +for cfg in new['configs']: + cid=cfg['config_id'];case=ts_io.CaseFile(root/'input/cases'/f'{cid}.h5') + ids=np.sort(rng.choice(case.n,min(case.n,192),replace=False)) + ts_io.write_case_subset(case,ids,out/'input/cases'/f'{cid}.h5') + lab,se,meta=ts_io.read_truth_file(root/'truth/cases'/f'{cid}.h5') + ts_io.write_truth_file(out/'truth/cases'/f'{cid}.h5',lab[ids],se[ids],meta) + cfg['n_instances']=len(ids);case.close() +for kind in ('input','truth'):(out/kind/'index.json').write_text(json.dumps(new,indent=1)) +print('screen instances',sum(c['n_instances'] for c in new['configs'])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch8/convert.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch8/convert.py new file mode 100644 index 0000000000000000000000000000000000000000..f758dcbc0d48b531889b71dc758a7d2fb9a3afb7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch8/convert.py @@ -0,0 +1,44 @@ +"""Convert our own 16-point model to 8-point patches, without external assets.""" +import argparse +import hashlib +import json +import time +from pathlib import Path + +import torch + +ap=argparse.ArgumentParser() +ap.add_argument('--input',required=True) +ap.add_argument('--output',required=True) +a=ap.parse_args() +torch.set_num_threads(2) +started=time.monotonic() +ck=torch.load(a.input,map_location='cpu',weights_only=False) +state=ck['model']; d=ck['config']['d'] +assert ck['config']['patch']==16 +old=state['embed.0.weight'].reshape(d,2,16) +state['embed.0.weight']=(old[:,:,:8]+old[:,:,8:]).reshape(d,16) +old=state['query.0.weight'].reshape(d,16,9) +state['query.0.weight']=(old[:,:8]+old[:,8:]).reshape(d,8*9) +if 'recency.weight' in state: + old=state['recency.weight'].reshape(d,16,4) + state['recency.weight']=(old[:,:8]+old[:,8:]).reshape(d,8*4) +state['head.weight']=state['head.weight'].reshape(16,18,d)[:8].reshape(8*18,d).clone() +state['head.bias']=state['head.bias'].reshape(16,18)[:8].reshape(8*18).clone() +ck['config']['patch']=8 +ck['config']['partial_target_lengths']=True +ck['conversion']={ + 'from_checkpoint':str(Path(a.input).resolve()), + 'from_sha256':hashlib.sha256(Path(a.input).read_bytes()).hexdigest(), + 'method':'fold input/query/recency halves by summation; retain first8 output rows; preserve physical position units', + 'exact_function_preservation':False} +ck['args']={**ck['args'],'initialize_from':str(Path(a.input).resolve()),'converted':True} +ck['parent_checkpoints']=[str(Path(a.input).resolve())] +torch.save(ck,a.output) +receipt=dict(input_sha256=ck['conversion']['from_sha256'], + checkpoint_sha256=hashlib.sha256(Path(a.output).read_bytes()).hexdigest(), + parameters=sum(v.numel() for v in state.values()), + cpu_seconds=time.monotonic()-started, + optimizer_updates=0,conversion=ck['conversion']) +Path(a.output).with_suffix('.json').write_text(json.dumps(receipt,indent=2)) +print(json.dumps(receipt)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch8/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch8/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch8/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch8/memory_check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch8/memory_check.py new file mode 100644 index 0000000000000000000000000000000000000000..d55bebeab8c6ff393f89b7ad031763f49531f56b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch8/memory_check.py @@ -0,0 +1,23 @@ +"""Maximum training-shape memory fixture, serialized with validation jobs.""" +import fcntl,json,sys,time +from pathlib import Path +import torch + +r=Path('/workspace/research');sys.path.insert(0,str(r/'patch8')) +from model import DirectForecaster,loss_fn +from data import Sampler +with open(r/'.evaluation.lock','a') as lock: + fcntl.flock(lock,fcntl.LOCK_EX) + torch.set_num_threads(1);torch.manual_seed(277);torch.backends.cuda.matmul.allow_tf32=True + started=time.monotonic() + ck=torch.load(r/'patch8_initial.pt',map_location='cpu',weights_only=False) + m=DirectForecaster(**ck['config']).cuda();m.load_state_dict(ck['model']) + x,y,p=[torch.from_numpy(a).cuda() for a in Sampler(r/'packed_sample',277).sample(64,4096,1024)] + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(m,x,y,p,paired=True) + loss.backward();torch.cuda.synchronize() + assert all(v.grad is not None and torch.isfinite(v.grad).all() for v in m.parameters()) + result={'seed':277,'batch':64,'signed_rows':128,'context':4096,'horizon':1024, + 'optimizer_updates':0,'loss':float(loss.detach()),'seconds':time.monotonic()-started, + 'peak_allocated_mib':torch.cuda.max_memory_allocated()/2**20, + 'peak_reserved_mib':torch.cuda.max_memory_reserved()/2**20} + (r/'patch8_memory_check.json').write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch8/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch8/model.py new file mode 100644 index 0000000000000000000000000000000000000000..dedcdff4698028a8ba655865f8425d0dc3ef0dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/patch8/model.py @@ -0,0 +1,204 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/recency_features/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/recency_features/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/recency_features/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/recency_features/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/recency_features/model.py new file mode 100644 index 0000000000000000000000000000000000000000..f8271c5b0bf9a5edb961e1c7839761fe50a2e40b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/recency_features/model.py @@ -0,0 +1,171 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024,recency_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + if self.recency is not None: + pos=torch.arange(c,device=z.device)[None,:];extras=[] + for j in range(2): + period=periods[:,j:j+1] + recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/recency_features/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/recency_features/train.py new file mode 100644 index 0000000000000000000000000000000000000000..3bfb8b90f1a6656881b7598f864becaa737a76f4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/recency_features/train.py @@ -0,0 +1,73 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(3);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/recovery/capacity_curves.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/recovery/capacity_curves.py new file mode 100644 index 0000000000000000000000000000000000000000..c89a28a84243dc16ae52a1215c182a00f15dbc4e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/recovery/capacity_curves.py @@ -0,0 +1,50 @@ +"""Summarize completed validation checkpoints and measured shared-GPU training time.""" +import csv +import json +import time +from pathlib import Path + +R = Path('/workspace/research') +started = time.monotonic() +names = ['random_capacity_512', 'random_capacity_1024', 'random_capacity_1024_halflr', + 'random_capacity_full', 'distill_ensemble', 'random_capacity_512_anneal'] +rows = [] +for name in names: + log = R/(name+'_train.log') + records = {} + if log.exists(): + for line in log.read_text().splitlines(): + try: + item = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(item,dict) and 'step' in item and 'seconds' in item: + records[item['step']] = item + config_path = R/'runs'/name/'config.json' + config = json.loads(config_path.read_text()) if config_path.exists() else {} + for report in sorted((R/'evals').glob(name+'_ema*/report.json')): + result = json.loads(report.read_text()) + step = int(report.parent.name.rsplit('ema',1)[1]) + if result['n_failed']: + continue + record = records.get(step,{}) + rows.append(dict(run=name,step=step,parameters=config.get('parameters'), + seed=config.get('seed'),batch=config.get('batch'),learning_rate=config.get('lr'), + packed=config.get('packed'),skill=result['skill_score'], + rel_mase=result['rel_mase_gmean'],rel_wql=result['rel_wql_gmean'], + checkpoint_sha256=result['checkpoint_sha256'], + training_phase_loop_seconds=record.get('seconds'), + evaluation_seconds=result.get('eval_seconds'),report=str(report))) +rows.sort(key=lambda item:(names.index(item['run']),item['step'])) +output = dict(generated_utc=time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()), + note='Validation selection only. Time is logged process wall on the shared single H100, not isolated GPU time. The cooldown arm starts from the same saved24000state; its phase clock resets. No missing log time is inferred.', + rows=rows,analysis_seconds=time.monotonic()-started,no_training_or_new_inference=True) +(R/'capacity_learning_curves.json').write_text(json.dumps(output,indent=2)) +with (R/'capacity_learning_curves.csv').open('w',newline='') as handle: + writer = csv.DictWriter(handle,fieldnames=list(rows[0]) if rows else ['run']) + writer.writeheader() + writer.writerows(rows) +for name in names: + selected = [r for r in rows if r['run']==name] + if selected: + print(json.dumps(selected[-1])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/recovery/exposure_audit.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/recovery/exposure_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..fb67738bc9ed77f87173feda2430365e66c75966 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/recovery/exposure_audit.py @@ -0,0 +1,46 @@ +"""Describe sampled observation exposure and training invested in selected ancestry.""" +import json +import sys +import time +from pathlib import Path +import numpy as np + +R=Path('/workspace/research') +sys.path.insert(0,str(R/'random_capacity')) +from data import Sampler + +started=time.monotonic() +seed=521 +sampler=Sampler(R/'packed_sample',seed=seed,source_weights_from=R/'packed_sample') +rng=np.random.default_rng(seed) +rows=context_points=target_points=0 +for _ in range(320): + 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])) + x,y,p=sampler.sample(64,c,h) + rows+=len(x) + context_points+=int(np.isfinite(x).sum()) + target_points+=int(np.isfinite(y).sum()) +manifest=json.loads(Path('/workspace/submission/model_manifest.json').read_text()) +runs={} +for item in manifest['training_lineage']: + path=Path(item['checkpoint']) + batch=item.get('training_settings',{}).get('batch') + if path.parts[0]!='runs' or not batch: + continue + run=path.parts[1] + step=item.get('step',0) + if step>runs.get(run,{}).get('step',0): + runs[run]=dict(step=step,batch=batch,rows=step*batch,checkpoint=item['checkpoint']) +ancestral_rows=sum(v['rows'] for v in runs.values()) +mean_points=(context_points+target_points)/rows +result=dict(seed=seed,seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False, + sampled_rows=rows,mean_finite_context_points=context_points/rows, + mean_finite_target_points=target_points/rows,mean_finite_points=mean_points, + selected_descriptor=manifest['checkpoint_sha256'],ancestral_runs=runs, + selected_ancestral_rows_before_sign_pairing=ancestral_rows, + fresh96000_batch48_rows=96000*48, + fresh96000_batch48_gross_observation_presentations_estimate=96000*48*mean_points, + note='Gross sampled presentations include overlapping/resampled windows and synthetic values, not unique observations. Ancestral run maxima count compute invested in different branches, including subtracted controls; they are not an equivalent single-model training trajectory. Sign pairing duplicates compute but not distinct sampled rows. No future training recipe is inferred from this audit alone.') +(R/'training_exposure_audit.json').write_text(json.dumps(result,indent=2)) +print(json.dumps({k:v for k,v in result.items() if k!='ancestral_runs'})) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/recovery/relaunch_20261022b.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/recovery/relaunch_20261022b.py new file mode 100644 index 0000000000000000000000000000000000000000..d16fc19cbbb86dba2ff53b445e368b8bbd2ca218 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/recovery/relaunch_20261022b.py @@ -0,0 +1,105 @@ +"""Resume interrupted research jobs and preserve phase-specific recovery receipts.""" +import datetime +import json +import os +from pathlib import Path +import shutil +import subprocess +import time + +R = Path('/workspace/research') +TAG = 'recovery2' +env = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1') +receipt = {'recovery_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(), + 'remaining_research_seconds_at_operator_recovery': 152594, + 'jobs': {}, 'queues': {}} +children = {} + +def launch(name, command, phase=TAG): + log = R / f'{name}_{phase}.log' + assert not log.exists(), log + with log.open('w') as f: + child = subprocess.Popen(command, stdout=f, stderr=subprocess.STDOUT, env=env) + children[name] = child + return {'pid': child.pid, 'command': command, 'log': str(log), 'started_monotonic': time.monotonic()} + +def persist(): + path = R / f'{TAG}_launch_receipt.json' + tmp = path.with_suffix('.tmp') + tmp.write_text(json.dumps(receipt, indent=2)); os.replace(tmp, path) + +for name in ['wide_capacity_146m_recovery', 'wide_capacity_control_recovery', + 'long_memory_synth_recovery', 'recent_normalization_recovery', 'wide_graft', 'patch8']: + run = R / 'runs' / name + cfg = json.loads((run / 'config.json').read_text()) + shutil.copy2(run / 'config.json', run / f'config_before_{TAG}.json') + command = ['python3', str(R / 'recovery/train.py')] + for key in ['code_dir', 'packed', 'source_weights_from', 'out', 'initialize_from', + 'initialize_ema', 'start_step', 'steps', 'batch', 'lr', 'seed', 'context', + 'sample_context', 'save_every', 'stop_file', 'reset_at', 'reset_seed', 'loss_mode']: + if cfg.get(key) is not None: + command += ['--' + key.replace('_', '-'), str(cfg[key])] + if (run / 'recovery.pt').exists(): + command += ['--resume', str(run / 'recovery.pt')] + mode = 'complete optimizer/EMA/RNG/prefetched-batch resume' + else: + mode = 'restart saved own initialization; no complete checkpoint existed' + if cfg.get('compile_loss'): + command += ['--compile-loss'] + command = ['env', 'TORCHINDUCTOR_COMPILE_THREADS=2', 'MAX_JOBS=2', + 'PYTHONPATH=/workspace/research/compiler_support', + 'TRITON_CACHE_MANAGER=sibling_cache:SiblingFileCacheManager', + 'TRITON_CACHE_DIR=/tmp/timeseries-triton-cache', + 'TORCHINDUCTOR_CACHE_DIR=/tmp/timeseries-inductor-cache'] + command + assert not Path(cfg['stop_file']).exists(), cfg['stop_file'] + receipt['jobs'][name] = dict(launch(name, command), mode=mode) + persist() + +watch_specs = { + 'wide_capacity_146m_recovery': ('wide_capacity_inference', '24000,32000'), + 'wide_capacity_control_recovery': ('wide_capacity_inference', '24000,32000'), + 'long_memory_synth_recovery': ('partial_targets_inference', '12000'), + 'recent_normalization_recovery': ('recent_normalization_inference', '12000'), + 'wide_graft': ('wide_graft_inference', '4000,8000,12000,16000,24000,32000'), + 'patch8': ('full_paired_inference', '1000,3000,6000,12000'), + 'volatility_synth': ('partial_targets_inference', '3000,6000,12000'), + 'postloss': ('full_paired_inference', '1000,3000,6000,12000'), + 'paired_long_memory': ('full_paired_inference', '1000,3000,6000,12000'), +} +for name, (runtime, steps) in watch_specs.items(): + command = ['python3', str(R / 'watch_evaluate.py'), '--run', str(R / 'runs' / name), + '--evaluator', str(R / runtime / 'evaluate.py'), '--name', name, '--steps', steps] + launch(name + '_watch', command) + +queue_specs = {'volatility_synth': 'long_memory_synth_recovery', + 'postloss': 'recent_normalization_recovery', + 'paired_long_memory': 'wide_capacity_control_recovery'} +for name, dependency in queue_specs.items(): + old = json.loads((R / (name + '_queue.json')).read_text()) + shutil.copy2(R / (name + '_queue.json'), R / (name + '_queue_before_' + TAG + '.json')) + receipt['queues'][name] = dict(old, dependency=dependency, status='waiting', + wait_pids=[children[dependency].pid]) +persist() + +while True: + for name, job in receipt['jobs'].items(): + if 'returncode' not in job and children[name].poll() is not None: + job.update(returncode=children[name].returncode, + phase_seconds=time.monotonic() - job['started_monotonic']) + persist() + for name, queue in receipt['queues'].items(): + if queue['status'] == 'waiting' and children[queue['dependency']].poll() is not None: + if children[queue['dependency']].returncode != 0 or not all(Path(p).exists() for p in queue['required_checkpoints']): + queue['status'] = 'blocked_by_incomplete_dependency' + else: + receipt['jobs'][name] = launch(name, queue['command']) + queue.update(status='running', pid=children[name].pid, + started_utc=datetime.datetime.now(datetime.timezone.utc).isoformat()) + with (R / 'direct_v1/EXPERIMENTS.md').open('a') as f: + f.write(f'\n{name} started {queue["started_utc"]} after {queue["dependency"]} completed. Original predeclared settings and seed retained.\n') + (R / (name + '_queue.json')).write_text(json.dumps(queue, indent=2)) + persist() + if all(p.poll() is not None for n,p in children.items() if not n.endswith('_watch')) and all(q['status'] != 'waiting' for q in receipt['queues'].values()): + break + time.sleep(5) +persist() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/recovery/relaunch_20261023.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/recovery/relaunch_20261023.py new file mode 100644 index 0000000000000000000000000000000000000000..5f35a9cfcbe7ea66c8837b6d4ada8b84be36b934 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/recovery/relaunch_20261023.py @@ -0,0 +1,104 @@ +"""Resume interrupted research jobs and preserve phase-specific recovery receipts.""" +import datetime +import json +import os +from pathlib import Path +import shutil +import subprocess +import time + +R = Path('/workspace/research') +TAG = 'recovery3' +env = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1') +receipt = {'recovery_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(), + 'remaining_research_seconds_at_operator_recovery': 151596, + 'jobs': {}, 'queues': {}} +children = {} + +def launch(name, command, phase=TAG): + log = R / f'{name}_{phase}.log' + assert not log.exists(), log + with log.open('w') as f: + child = subprocess.Popen(command, stdout=f, stderr=subprocess.STDOUT, env=env) + children[name] = child + return {'pid': child.pid, 'command': command, 'log': str(log), 'started_monotonic': time.monotonic()} + +def persist(): + path = R / f'{TAG}_launch_receipt.json' + tmp = path.with_suffix('.tmp') + tmp.write_text(json.dumps(receipt, indent=2)); os.replace(tmp, path) + +for name in ['wide_capacity_146m_recovery', 'wide_capacity_control_recovery', + 'long_memory_synth_recovery', 'wide_graft', 'patch8']: + run = R / 'runs' / name + cfg = json.loads((run / 'config.json').read_text()) + shutil.copy2(run / 'config.json', run / f'config_before_{TAG}.json') + command = ['python3', str(R / 'recovery/train.py')] + for key in ['code_dir', 'packed', 'source_weights_from', 'out', 'initialize_from', + 'initialize_ema', 'start_step', 'steps', 'batch', 'lr', 'seed', 'context', + 'sample_context', 'save_every', 'stop_file', 'reset_at', 'reset_seed', 'loss_mode']: + if cfg.get(key) is not None: + command += ['--' + key.replace('_', '-'), str(cfg[key])] + if (run / 'recovery.pt').exists(): + command += ['--resume', str(run / 'recovery.pt')] + mode = 'complete optimizer/EMA/RNG/prefetched-batch resume' + else: + mode = 'restart saved own initialization; no complete checkpoint existed' + if cfg.get('compile_loss'): + command += ['--compile-loss'] + command = ['env', 'TORCHINDUCTOR_COMPILE_THREADS=2', 'MAX_JOBS=2', + 'PYTHONPATH=/workspace/research/compiler_support', + 'TRITON_CACHE_MANAGER=sibling_cache:SiblingFileCacheManager', + 'TRITON_CACHE_DIR=/tmp/timeseries-triton-cache', + 'TORCHINDUCTOR_CACHE_DIR=/tmp/timeseries-inductor-cache'] + command + assert not Path(cfg['stop_file']).exists(), cfg['stop_file'] + receipt['jobs'][name] = dict(launch(name, command), mode=mode) + persist() + +watch_specs = { + 'wide_capacity_146m_recovery': ('wide_capacity_inference', '24000,32000'), + 'wide_capacity_control_recovery': ('wide_capacity_inference', '24000,32000'), + 'long_memory_synth_recovery': ('partial_targets_inference', '12000'), + 'recent_normalization_recovery': ('recent_normalization_inference', '12000'), + 'wide_graft': ('wide_graft_inference', '4000,8000,12000,16000,24000,32000'), + 'patch8': ('full_paired_inference', '1000,3000,6000,12000'), + 'volatility_synth': ('partial_targets_inference', '3000,6000,12000'), + 'postloss': ('full_paired_inference', '1000,3000,6000,12000'), + 'paired_long_memory': ('full_paired_inference', '1000,3000,6000,12000'), +} +for name, (runtime, steps) in watch_specs.items(): + command = ['python3', str(R / 'watch_evaluate.py'), '--run', str(R / 'runs' / name), + '--evaluator', str(R / runtime / 'evaluate.py'), '--name', name, '--steps', steps] + launch(name + '_watch', command) + +queue_specs = {'volatility_synth': 'long_memory_synth_recovery', + 'paired_long_memory': 'wide_capacity_control_recovery'} +for name, dependency in queue_specs.items(): + old = json.loads((R / (name + '_queue.json')).read_text()) + shutil.copy2(R / (name + '_queue.json'), R / (name + '_queue_before_' + TAG + '.json')) + receipt['queues'][name] = dict(old, dependency=dependency, status='waiting', + wait_pids=[children[dependency].pid]) +persist() + +while True: + for name, job in receipt['jobs'].items(): + if 'returncode' not in job and children[name].poll() is not None: + job.update(returncode=children[name].returncode, + phase_seconds=time.monotonic() - job['started_monotonic']) + persist() + for name, queue in receipt['queues'].items(): + if queue['status'] == 'waiting' and children[queue['dependency']].poll() is not None: + if children[queue['dependency']].returncode != 0 or not all(Path(p).exists() for p in queue['required_checkpoints']): + queue['status'] = 'blocked_by_incomplete_dependency' + else: + receipt['jobs'][name] = launch(name, queue['command']) + queue.update(status='running', pid=children[name].pid, + started_utc=datetime.datetime.now(datetime.timezone.utc).isoformat()) + with (R / 'direct_v1/EXPERIMENTS.md').open('a') as f: + f.write(f'\n{name} started {queue["started_utc"]} after {queue["dependency"]} completed. Original predeclared settings and seed retained.\n') + (R / (name + '_queue.json')).write_text(json.dumps(queue, indent=2)) + persist() + if all(p.poll() is not None for n,p in children.items() if not n.endswith('_watch')) and all(q['status'] != 'waiting' for q in receipt['queues'].values()): + break + time.sleep(5) +persist() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/recovery/schedules.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/recovery/schedules.py new file mode 100644 index 0000000000000000000000000000000000000000..4c8378f374144b802d2cd5a98afd71efc1ba0a4c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/recovery/schedules.py @@ -0,0 +1,13 @@ +"""Explicit training-only learning-rate schedules; default arithmetic unchanged.""" +import math + + +def learning_rate(step, steps, peak, reset_at=-1, anneal_from_step=None, + anneal_from_lr=None, anneal_final_lr=None): + if anneal_from_step is not None: + assert steps > anneal_from_step + assert 0 < anneal_final_lr <= anneal_from_lr + progress=max(0.,min(1.,(step-anneal_from_step)/(steps-anneal_from_step))) + return anneal_final_lr+.5*(anneal_from_lr-anneal_final_lr)*(1+math.cos(math.pi*progress)) + warm_step=step-reset_at if reset_at>=0 and step>reset_at else step + return peak*min(1,warm_step/400)*(.2+.4*(1+math.cos(math.pi*step/steps))) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/recovery/snapshot.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/recovery/snapshot.py new file mode 100644 index 0000000000000000000000000000000000000000..11ce27e43477f9c685cefeaa5f36e53c59634505 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/recovery/snapshot.py @@ -0,0 +1,99 @@ +"""Write a compact authoritative research recovery index without touching training state.""" +import datetime +import json +import os +from pathlib import Path + +R=Path('/workspace/research');p=R/'CURRENT_RESEARCH_STATE.json' +s=json.loads(p.read_text()) +s['snapshot_utc']=datetime.datetime.now(datetime.timezone.utc).isoformat() +receipt=json.loads((R/'recovery3_launch_receipt.json').read_text()) +s['runs']={} +for name,job in receipt['jobs'].items(): + run=R/'runs'/name + log=Path(job['log']) + records=[] + for line in log.read_text().splitlines(): + try: + record=json.loads(line) + if 'step' in record or 'completed_step' in record:records.append(record) + except json.JSONDecodeError:pass + s['runs'][name]={'config':json.loads((run/'config.json').read_text()) if (run/'config.json').exists() else None, + 'last_phase_record':records[-1] if records else None, + 'phase_log':str(log),'supervisor_receipt':str(R/'recovery3_launch_receipt.json'), + 'latest_saved_ema':str(max(run.glob('ema*.pt'))) if list(run.glob('ema*.pt')) else None, + 'complete_recovery_checkpoint':str(run/'recovery.pt') if (run/'recovery.pt').exists() else None, + 'pid_at_snapshot':job['pid'],'returncode':job.get('returncode'), + 'note':'Check actual live process and checkpoint state before resuming; this is only a snapshot.'} +s['queues']={name:{'status':q['status'],'dependency':q['dependency'],'command':q['command'], + 'required_checkpoints':q['required_checkpoints']} + for name,q in receipt['queues'].items()} +s.pop('prepared_not_launched',None) +s['deferred_unqueued']={'E72':'temporal_mixup, prepared and checked but not queued','ideas':'RESEARCH_IDEAS.md, no jobs attached'} +s['completed_since_previous_recovery']={ + 'E67_control12000':{'skill':.37724286394256845,'training_loop_seconds':2794.8358458959847}, + 'E67_paired12000':{'skill':.377427077277383,'training_loop_seconds':2794.867385860998}, + 'E63_expanded146M':'Stopped8501, complete recovery retained; allocation moved to E73; inconclusive data scaling', + 'E61_slowAR':'Complete12000; E76 used6000 correction, final transfer rejected', + 'E65_recent_normalization':'Complete12000; E81 equal ensemble rejected', + 'E58_small_control':'Complete32000', + 'E58_wide146M':'Complete32000; no gain over37Mcontrol; do not resume', + 'E71_patch8':'Complete12000; selected6000 used in E87/E96/E102 ensembles', + 'E69_volatility':'Complete12000; final below matched control; no transfer', + 'E89_patch8_control':'Complete12000; final0.380847096,loop2729.052105s; selected starting E71parent remains stronger', + 'E89_fullpatch4':'Complete12000,main0.381640078; E96 used6000, E103final cached alternative mixed; loop5066.016522s', + 'E93_split_patch':'Complete12000,main0.381711986; selected final is E102 published thirdmember; loop3153.565149s', + 'E92_robust_normalization':'Complete12000,final0.377099312 belowcontrol; rejected;E97started', + 'E90_metric_scale':'Complete12000; final0.377373344 ties/slightly trailsE80; no selection; loop2702.166704s', + 'E84_coarse':'Complete12000; daily gain but weekly regression; not selected', + 'E88_late_patch8_slowAR':'Complete12000; small9k gain lost atfinal; rejected', + 'E80_overflow':'Complete12000; finaltiesoriginal; selected3k compositeE91rejected', + 'E78_multiscaleAR':'Complete12000; no gain over single slowAR', + 'E86_protected_graft':'Complete8000; below own initialization; no publication', + 'E75_postloss':'Stopped3653 deliberately; immutable snapshot retained; E98 separately declared completion active in another output, original stopfile remains', + 'E73_independent_graft':'Stopped8683 after negative8000; replaced by E86; stopfile remains', + 'E95_stratified_corpus':'Complete12000,final0.377983250,earliermixed; E105collision destroyed only1000weights and optimizer recovery;2k..12k preserved; do not resume', + 'E97_weekly_synth':'Complete12000,final0.380439539; E112final weekly correction now published; loop2600.472750s', + 'E105_stratified_volume':'Complete12000,final0.377529200,earlier0.336713522/0.359535697/0.390349158 mixed; corrected continuationloop2013.982814s plus original incident phase', + 'E106_spectral_synth':'Complete12000,final0.377641399,earlier0.337647555/0.361626447/0.385497870, average matched gap negligible; loop2206.272278s; E114fixed6000transfers in selection', + 'E98_postloss_completion':'Complete12000,final0.376034254 below3000 andcontrol; rejected,loop1995.386513s', + 'E99_early_cooldown':'Complete36000,final0.363306598 trails original36k0.364859034; rejected,loop1603.635706s', + 'E77_pairedslowAR':'Complete12000;6000 strongest main/earlier comparison'} +s['external_receipts']=[str(R/'postloss_recovery3_receipt.json'),str(R/'random_capacity_512_queue.json'),str(R/'random_capacity_1024_queue.json'),str(R/'multiscale_ar_queue.json'),str(R/'overflow_control_queue.json'),str(R/'coarse_aggregate_queue.json'),str(R/'patch8_long_memory_queue.json'),str(R/'wide_graft_frozen_queue.json'),str(R/'patch4_candidate_queue.json'),str(R/'patch4_control_queue.json'),str(R/'metric_scale_queue.json'),str(R/'robust_normalization_queue.json'),str(R/'split_patch_queue.json'),str(R/'random_capacity_1024_halflr_queue.json'),str(R/'stratified_corpus_queue.json'),str(R/'weekly_synth_queue.json'),str(R/'postloss_completion_queue.json'),str(R/'random_capacity_512_anneal_queue.json'),str(R/'distill_ensemble_queue.json'),str(R/'stratified_volume_queue.json'),str(R/'spectral_synth_queue.json'),str(R/'long_seasonal_queue.json'),str(R/'random_capacity_full_queue.json'),str(R/'weekly_replication_control_queue.json'),str(R/'weekly_replication_candidate_queue.json'),str(R/'lowfreq_windows_queue.json'),str(R/'phase_joint_queue.json')] +queue_pids={'random_capacity_512_queue.json':965,'random_capacity_1024_queue.json':967, + 'multiscale_ar_queue.json':1678,'overflow_control_queue.json':1676, + 'coarse_aggregate_queue.json':3086,'patch8_long_memory_queue.json':3739, + 'wide_graft_frozen_queue.json':3931,'patch4_candidate_queue.json':4078, + 'patch4_control_queue.json':4080} +s['external_jobs']={} +for receipt_name in s['external_receipts']: + receipt_path=Path(receipt_name) + if not receipt_path.exists():continue + item=json.loads(receipt_path.read_text());command=item.get('command',[]) + if '--out' not in command:continue + run=Path(command[command.index('--out')+1]);log=Path(item.get('log',str(receipt_path).replace('_queue.json','_train.log'))) + last=None + if log.exists(): + for line in log.read_text().splitlines(): + try: + record=json.loads(line) + if isinstance(record,dict) and ('step' in record or 'completed_step' in record):last=record + except json.JSONDecodeError:pass + queue_pid=item.get('launcher_pid',queue_pids.get(receipt_path.name)) + children_file=Path(f'/proc/{queue_pid}/task/{queue_pid}/children') if queue_pid else None + children=list(map(int,children_file.read_text().split())) if children_file and children_file.exists() else [] + checkpoints=list(run.glob('ema*.pt')) + s['external_jobs'][run.name]={'receipt':str(receipt_path),'status':item.get('status'), + 'queue_pid_at_snapshot':queue_pid,'child_pids_at_snapshot':children, + 'last_phase_record':last,'log':str(log), + 'latest_saved_ema':str(max(checkpoints)) if checkpoints else None, + 'complete_recovery_checkpoint':str(run/'recovery.pt') if (run/'recovery.pt').exists() else None, + 'command':command,'note':'PIDs are only a snapshot; check actual processes and serialized state before recovery.'} +s['compiler_environment']={'OPENBLAS_NUM_THREADS':'1','OMP_NUM_THREADS':'1','TORCHINDUCTOR_COMPILE_THREADS':'2','MAX_JOBS':'2','PYTHONPATH':str(R/'compiler_support'),'TRITON_CACHE_MANAGER':'sibling_cache:SiblingFileCacheManager','TRITON_CACHE_DIR':'/tmp/timeseries-triton-cache','TORCHINDUCTOR_CACHE_DIR':'/tmp/timeseries-inductor-cache'} +for job in s['external_jobs'].values(): + job['environment']=s['compiler_environment'] if '--compile-loss' in job['command'] else {'OPENBLAS_NUM_THREADS':'1','OMP_NUM_THREADS':'1'} +s['compiler_cache_backup']=str(R/'compiler_cache_backup') +for stale in ['pending','pending_actions','active_experiments','next_experiments','prepared_experiments']: + s.pop(stale,None) +tmp=p.with_suffix('.tmp');tmp.write_text(json.dumps(s,indent=2));os.replace(tmp,p) +print(s['snapshot_utc']) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/recovery/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/recovery/train.py new file mode 100644 index 0000000000000000000000000000000000000000..536677ab542342e8e9b56298e5ddb7cb2983a258 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/recovery/train.py @@ -0,0 +1,201 @@ +"""Resumable continuation of our existing permitted-corpus experiments.""" +import argparse,copy,fcntl,inspect,json,math,os,sys,time +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import numpy as np +import torch + +ap=argparse.ArgumentParser() +ap.add_argument('--code-dir',required=True);ap.add_argument('--packed',required=True) +ap.add_argument('--source-weights-from');ap.add_argument('--out',required=True) +ap.add_argument('--initialize-from',required=True);ap.add_argument('--initialize-ema') +ap.add_argument('--start-step',type=int,default=0);ap.add_argument('--resume') +ap.add_argument('--steps',type=int,required=True);ap.add_argument('--batch',type=int,required=True) +ap.add_argument('--lr',type=float,required=True);ap.add_argument('--seed',type=int,required=True) +ap.add_argument('--context',type=int);ap.add_argument('--sample-context',type=int,default=4096) +ap.add_argument('--save-every',type=int,default=1000);ap.add_argument('--stop-file') +ap.add_argument('--recovery-every',type=int,default=250) +ap.add_argument('--halt-after',type=int) +ap.add_argument('--loss-mode',choices=['individual','paired']) +ap.add_argument('--compile-loss',action='store_true') +ap.add_argument('--reset-at',type=int,default=-1);ap.add_argument('--reset-seed',type=int,default=179) +ap.add_argument('--anneal-from-step',type=int);ap.add_argument('--anneal-from-lr',type=float) +ap.add_argument('--anneal-final-lr',type=float) +ap.add_argument('--teacher-package');ap.add_argument('--teacher-coefficient',type=float) +a=ap.parse_args() +# Hold a process-lifetime lock before loading a model or touching GPU state. +_run_out=Path(a.out);_run_out.mkdir(parents=True,exist_ok=True) +_run_lock=open(_run_out/'.training.lock','a') +try:fcntl.flock(_run_lock,fcntl.LOCK_EX|fcntl.LOCK_NB) +except BlockingIOError:raise SystemExit('Another trainer already owns this output directory: '+str(_run_out)) +if not a.resume: + _saved=list(_run_out.glob('ema*.pt'))+list(_run_out.glob('step*.pt')) + if (_run_out/'recovery.pt').exists():_saved.append(_run_out/'recovery.pt') + if _saved: + raise SystemExit('Refusing fresh training into an output with saved checkpoints; use a new directory or explicit --resume: '+str(_run_out)) +sys.path.insert(0,a.code_dir) +from model import DirectForecaster,loss_fn +from data import Sampler +from schedules import learning_rate +torch.set_num_threads(2);torch.manual_seed(a.seed);torch.backends.cuda.matmul.allow_tf32=True +out=Path(a.out);out.mkdir(parents=True,exist_ok=True);a.trainable_scope='all' +if Path(a.code_dir).name in ('long_memory_synth','paired_long_memory','multiscale_ar','random_capacity','patch8_long_memory','distill_ensemble'):a.synthetic_ar_time_constants=[1,10000] +if Path(a.code_dir).name in ('full_paired','patch8','temporal_mixup','postloss','paired_long_memory','multiscale_ar','random_capacity','overflow_control','coarse_aggregate','patch8_long_memory','patch4','metric_scale','robust_normalization','split_patch','weekly_synth','distill_ensemble'):a.requested_horizon_seed=a.seed+300003 +if Path(a.code_dir).name=='multiscale_ar': + a.synthetic_ar_components=4;a.multiscale_ar_seed=a.seed+700003 +if Path(a.code_dir).name=='volatility_synth':a.stochastic_volatility_seed=a.seed+500003 +if Path(a.code_dir).name=='coarse_aggregate': + a.coarse_aggregation_seed=a.seed+900003;a.coarse_aggregation_probability=.2;a.coarse_aggregation_frequencies=['D','W'] +if Path(a.code_dir).name=='temporal_mixup':a.temporal_mixup_seed=a.seed+600003 +if Path(a.code_dir).name=='postloss': + a.fixed_postprocessing_loss=True;a.normalization_overflow_fallback=True +if Path(a.code_dir).name in ('overflow_control','metric_scale','random_capacity','weekly_synth','distill_ensemble'):a.normalization_overflow_fallback=True +if Path(a.code_dir).name=='weekly_synth': + a.weekly_synthetic_seed=a.seed+1000003;a.weekly_replacement_probability=1/11 +if Path(a.code_dir).name=='spectral_synth': + a.spectral_synthetic_seed=a.seed+1100003;a.spectral_replacement_probability=.5 + a.spectral_length_scale=[1,10000];a.spectral_families=['Matern0.5','Matern1.5','Matern2.5','RBF'] + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True +if Path(a.code_dir).name in ('long_seasonal','phase_joint'): + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True +if Path(a.code_dir).name=='lowfreq_windows': + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True + a.lowfreq_window_seed=a.seed+1200003;a.lowfreq_window_probability=.5 + a.lowfreq_window_rule='period2=1,period1<=52;finite-target endpoint;log-uniform horizon4..min(H,max(8,2p),span-8) with available-length fallback;context cap min(C,max(64,32p));at least4finite history' +if Path(a.code_dir).name=='metric_scale':a.loss_seasonality='lag1 for exact daily[7,365] and weekly[52,1] period pairs; unchanged otherwise' +if Path(a.code_dir).name=='robust_normalization':a.normalization_kind='finite median plus/minus6 mean absolute deviations winsorized mean/RMS, float64; original normalized history clipped30' +if Path(a.code_dir).name=='wide_graft_frozen':a.trainable_scope='new feature stream and cross-stream blocks; inherited parameter blocks frozen' +ck=torch.load(a.resume or a.initialize_from,map_location='cpu',weights_only=False) +# Keep immutable branch ancestry across a later restart from this run's own recovery. +lineage_parents=list(ck.get('parent_checkpoints',[])) +if a.initialize_ema:lineage_parents.append(a.initialize_ema) +if a.resume and Path(a.resume).parent.resolve()!=out.resolve():lineage_parents.append(a.resume) +previous_args=ck.get('args',{}) +previous_resume=previous_args.get('resume') +if previous_resume and Path(previous_resume).parent.resolve()!=Path(previous_args.get('out',a.out)).resolve(): + lineage_parents.append(previous_resume) +lineage_parents=list(dict.fromkeys(lineage_parents)) +config=dict(ck['config']) +if a.context:config['max_context']=a.context +model=DirectForecaster(**config).cuda();model.load_state_dict(ck['model']) +teacher=None +if Path(a.code_dir).name=='distill_ensemble': + assert a.teacher_package and a.teacher_coefficient is not None +if a.teacher_package: + assert Path(a.code_dir).name=='distill_ensemble' + from teacher import OwnEnsembleTeacher + with torch.random.fork_rng(devices=[torch.cuda.current_device()]): + teacher=OwnEnsembleTeacher(a.teacher_package) + if ck.get('args',{}).get('teacher_descriptor_sha256'): + assert ck['args']['teacher_descriptor_sha256']==teacher.descriptor_sha256 + assert ck['args']['teacher_coefficient']==a.teacher_coefficient + a.teacher_descriptor_sha256=teacher.descriptor_sha256 + a.teacher_checkpoint_sha256=teacher.member_hashes + a.teacher_target_kind='equal average of own frozen E96 raw normalized sign-paired neural quantiles, before postprocessing' + +protector=None +if Path(a.code_dir).name=='wide_graft_frozen': + from frozen import FreezeInherited + protector=FreezeInherited(model) + a.protected_parameters=protector.inherited_numel +if a.compile_loss: + torch._dynamo.config.recompile_limit=64 + objective=torch.compile(loss_fn,fullgraph=True,dynamic=False) +else:objective=loss_fn +multipliers=ck.get('lr_multipliers',{}) +def optimizer(): + groups=[] + for mult in sorted(set(multipliers.values())|{1.}): + params=[p for n,p in model.named_parameters() if multipliers.get(n,1.)==mult] + if params:groups.append({'params':params,'lr':a.lr*mult,'lr_multiplier':mult,'weight_decay':.05/mult}) + return torch.optim.AdamW(groups,betas=(.9,.95),fused=True) +opt=optimizer() +if a.resume: + start_step=ck['step'];opt.load_state_dict(ck['optimizer']) + ema={k:v.cuda() for k,v in ck['ema_state'].items()} +else: + start_step=a.start_step + ema_ck=torch.load(a.initialize_ema,map_location='cpu',weights_only=False) if a.initialize_ema else ck + ema={k:v.cuda().clone() for k,v in ema_ck['model'].items()} +del ck +def make_sampler(seed): + kwargs={'seed':seed} + if 'source_weights_from' in inspect.signature(Sampler).parameters:kwargs['source_weights_from']=a.source_weights_from + return Sampler(a.packed,**kwargs),np.random.default_rng(seed) +stream_seed=a.reset_seed if a.reset_at>=0 and start_step>=a.reset_at else a.seed +sampler,rng=make_sampler(stream_seed) +def next_batch(): + c=int(rng.choice([512,1024,2048,a.sample_context],p=[.1,.15,.35,.4])) + h=int(rng.choice([32,128,512,1024],p=[.1,.2,.2,.5])) + x,y,p=sampler.sample(a.batch,c,h) + return x[:,-model.max_context:].copy(),y,p +pool=ThreadPoolExecutor(1) +if a.resume: + recovery=torch.load(a.resume,map_location='cpu',weights_only=False) + rng.bit_generator.state=recovery['batch_rng_state'];sampler.rng.bit_generator.state=recovery['sampler_rng_state'] + for name,state in recovery.get('sampler_rng_states',{}).items():getattr(sampler,name).bit_generator.state=state + torch.set_rng_state(recovery['torch_rng_state']);torch.cuda.set_rng_state_all(recovery['cuda_rng_state']) + pending=recovery['prefetched_batch'];del recovery + future=pool.submit(lambda:pending) +else:future=pool.submit(next_batch) +parameters=sum(p.numel() for p in model.parameters()) +(out/'config.json').write_text(json.dumps({**vars(a),'model':model.config,'parameters':parameters},indent=2)) +print(json.dumps({'parameters':parameters,'starting_step':start_step,'stream_seed':stream_seed,'restored_complete_training_state':bool(a.resume)}),flush=True) +started=time.monotonic();losses=[] +def atomic_save(obj,path): + torch.save(obj,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) +def save(step,include_selection_weights=True): + global future + pending_batch=future.result() + common={'config':model.config,'step':step,'args':vars(a),'lr_multipliers':multipliers, + 'parent_checkpoints':list(dict.fromkeys(lineage_parents+(teacher.checkpoints if teacher else [])))} + if include_selection_weights: + for prefix,state in [('step',model.state_dict()),('ema',ema)]: + atomic_save({**common,'model':state,'ema':prefix=='ema'},out/f'{prefix}{step:06d}.pt') + atomic_save({**common,'model':model.state_dict(),'optimizer':opt.state_dict(),'ema_state':ema, + 'prefetched_batch':pending_batch,'batch_rng_state':copy.deepcopy(rng.bit_generator.state), + 'sampler_rng_state':copy.deepcopy(sampler.rng.bit_generator.state), + 'sampler_rng_states':{name:copy.deepcopy(value.bit_generator.state) for name,value in vars(sampler).items() if isinstance(value,np.random.Generator)}, + 'torch_rng_state':torch.get_rng_state(),'cuda_rng_state':torch.cuda.get_rng_state_all()},out/'recovery.pt') + future=pool.submit(lambda:pending_batch) +for step in range(start_step+1,a.steps+1): + if a.reset_at>=0 and step==a.reset_at+1 and start_step=a.halt_after) + selection_checkpoint=step%a.save_every==0 or step==a.steps or stop + # Persist a complete state before a fresh/resumed job warms its remaining compiled shapes. + if selection_checkpoint or step%a.recovery_every==0 or step==start_step+1: + save(step,include_selection_weights=selection_checkpoint) + if stop:break +pool.shutdown() +print(json.dumps({'completed_step':step,'training_process_loop_seconds':time.monotonic()-started}),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/split_patch/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/split_patch/check.py new file mode 100644 index 0000000000000000000000000000000000000000..1f2b82a5b0b0ad5477066245356808138d166400 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/split_patch/check.py @@ -0,0 +1,49 @@ +"""Verify equal input/output patches preserve the old implementation exactly.""" +import importlib.util +import json +import sys +import time +from pathlib import Path +import torch + +R = Path('/workspace/research') +sys.path.insert(0, str(R / 'split_patch')) +from model import DirectForecaster + +started = time.monotonic() +torch.set_num_threads(2) +torch.manual_seed(457) +spec = importlib.util.spec_from_file_location('original_patch_model', R / 'full_paired_inference/model.py') +old = importlib.util.module_from_spec(spec) +spec.loader.exec_module(old) +ck = torch.load(R / 'runs/patch8/ema006000.pt', map_location='cpu', weights_only=False) +control = old.DirectForecaster(**ck['config']) +control.load_state_dict(ck['model']) +same = DirectForecaster(**ck['config'], input_patch=8) +same.load_state_dict(ck['model']) +x = torch.randn(6, 251) +x[0, :90] = float('nan') +x[1, ::7] = float('nan') +p = torch.tensor([[12, 1], [52, 1], [24, 168], [7, 365], [1, 1], [96, 672]]) +with torch.no_grad(): + before = control(x, p, 57) + after = same(x, p, 57) +assert all(torch.equal(a, b) for a, b in zip(before, after)) +candidate = torch.load(R / 'split_patch_initial.pt', map_location='cpu', weights_only=False) +full4 = torch.load(R / 'patch4_initial.pt', map_location='cpu', weights_only=False) +for name, value in candidate['model'].items(): + reference = ck['model'][name] if name == 'embed.0.weight' else full4['model'][name] + assert torch.equal(value, reference), name +net = DirectForecaster(**candidate['config']) +net.load_state_dict(candidate['model']) +with torch.no_grad(): + q = net.predict(x, p, 57) +assert q.shape == (6, 9, 57) +assert torch.isfinite(q).all() and (q[:, 1:] >= q[:, :-1]).all() +receipt = dict(seed=457, cpu_seconds=time.monotonic() - started, + equal_patch_forward_bitwise_unchanged=True, + input_tensor_retained_from_patch8=True, + output_tensors_identical_to_full_patch4_conversion=True, + candidate_finite_ordered=True, optimizer_updates=0) +(R / 'split_patch_checks.json').write_text(json.dumps(receipt, indent=2)) +print(json.dumps(receipt)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/split_patch/convert.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/split_patch/convert.py new file mode 100644 index 0000000000000000000000000000000000000000..9a16c87c0cf45b0efb1b2e56008a821c8391b471 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/split_patch/convert.py @@ -0,0 +1,13 @@ +"""Convert the already locally trained patch8 model to input8/output4 without external assets.""" +import argparse,hashlib,json,time +from pathlib import Path +import torch +ap=argparse.ArgumentParser();ap.add_argument('--input',required=True);ap.add_argument('--output',required=True);a=ap.parse_args() +torch.set_num_threads(1);started=time.monotonic();ck=torch.load(a.input,map_location='cpu',weights_only=False);state=ck['model'];d=ck['config']['d'];assert ck['config']['patch']==8 +x=state['query.0.weight'].reshape(d,8,9);state['query.0.weight']=(x[:,:4]+x[:,4:]).reshape(d,36) +x=state['recency.weight'].reshape(d,8,4);state['recency.weight']=(x[:,:4]+x[:,4:]).reshape(d,16) +state['head.weight']=state['head.weight'].reshape(8,18,d)[:4].reshape(72,d).clone();state['head.bias']=state['head.bias'].reshape(8,18)[:4].reshape(72).clone() +ck['config']['patch']=4;ck['config']['input_patch']=8 +conversion={'method':'retain input8; sum query/recency halves and keep first4 output rows; same physical position coordinates','exact_function_preservation':False,'parent_sha256':hashlib.sha256(Path(a.input).read_bytes()).hexdigest()} +ck.update(step=0,args={'packed':ck['args']['packed'],'initialize_from':str(Path(a.input).resolve()),'converted':True},parent_checkpoints=[str(Path(a.input).resolve())],conversion=conversion) +torch.save(ck,a.output);receipt={**conversion,'checkpoint_sha256':hashlib.sha256(Path(a.output).read_bytes()).hexdigest(),'parameters':sum(v.numel() for v in state.values()),'cpu_seconds':time.monotonic()-started,'optimizer_updates':0};Path(a.output).with_suffix('.json').write_text(json.dumps(receipt,indent=2));print(json.dumps(receipt)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/split_patch/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/split_patch/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/split_patch/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/split_patch/launch.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/split_patch/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..d3156fc48da2d25d324c5fb7cc2a50f7f70738d7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/split_patch/launch.py @@ -0,0 +1,33 @@ +"""Run input8/output4 after late patch8 slowAR releases its allocation.""" +def main(): + import json + import os + import subprocess + from pathlib import Path + R = Path('/workspace/research') + assert json.loads((R / 'split_patch_checks.json').read_text())['equal_patch_forward_bitwise_unchanged'] + assert json.loads((R / 'split_patch_memory_check.json').read_text())['peak_reserved_mib'] < 14000 + env = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1') + command = ['python3', str(R / 'recovery/train.py'), '--code-dir', str(R / 'split_patch'), + '--packed', str(R / 'packed_sample'), '--source-weights-from', str(R / 'packed_sample'), + '--out', str(R / 'runs/split_patch'), '--initialize-from', str(R / 'split_patch_initial.pt'), + '--steps', '12000', '--batch', '32', '--lr', '.00002', '--seed', '401', + '--loss-mode', 'paired', '--stop-file', str(R / 'split_patch.stop')] + with (R / 'split_patch_queue.log').open('w') as qlog, (R / 'split_patch_watch.log').open('w') as wlog: + queued = subprocess.Popen(['python3', str(R / 'queued_train.py'), '--label', 'E93 input8/output4 seed401', + '--log', str(R / 'split_patch_train.log'), '--receipt', str(R / 'split_patch_queue.json'), + '--wait-pid', '7349', '--require-checkpoint', str(R / 'runs/patch8_long_memory/recovery.pt'), + '--', *command], stdout=qlog, stderr=subprocess.STDOUT, env=env) + watch = subprocess.Popen(['python3', str(R / 'watch_evaluate.py'), '--run', str(R / 'runs/split_patch'), + '--evaluator', str(R / 'split_patch_inference/evaluate.py'), + '--name', 'split_patch', '--steps', '1000,3000,6000,12000'], + stdout=wlog, stderr=subprocess.STDOUT, env=env) + print({'queue_pid': queued.pid, 'watch_pid': watch.pid}, flush=True) + result = queued.wait() + if result: + watch.terminate() + watch.wait() + raise SystemExit(result) + +if __name__ == '__main__': + main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/split_patch/memory_check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/split_patch/memory_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7ae2014f738a03f54cbd2208eb9095efe16b009c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/split_patch/memory_check.py @@ -0,0 +1,18 @@ +"""Maximum-shape memory check for the matched patch comparison, including training state.""" +import argparse,fcntl,json,sys,time +from pathlib import Path +import torch +R=Path('/workspace/research');sys.path.insert(0,str(R/'split_patch')) +from model import DirectForecaster,loss_fn +from data import Sampler +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);a=ap.parse_args() +with open(R/'.evaluation.lock','a') as lock: + fcntl.flock(lock,fcntl.LOCK_EX);torch.set_num_threads(1);torch.manual_seed(401);torch.backends.cuda.matmul.allow_tf32=True + started=time.monotonic();ck=torch.load(a.weights,map_location='cpu',weights_only=False);model=DirectForecaster(**ck['config']).cuda();model.load_state_dict(ck['model']) + ema=[p.detach().clone() for p in model.parameters()];moments=[(torch.zeros_like(p),torch.zeros_like(p)) for p in model.parameters()] + x,y,p=[torch.from_numpy(v).cuda() for v in Sampler(R/'packed_sample',seed=401).sample(32,4096,1024)] + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p,paired=True) + loss.backward();torch.cuda.synchronize();assert torch.isfinite(loss) + assert all(v.grad is not None and torch.isfinite(v.grad).all() for v in model.parameters()) + result={'seed':401,'batch':32,'signed_rows':64,'patch':model.patch,'input_patch':model.input_patch,'context':4096,'horizon':1024,'EMA_and_AdamW_moment_storage_present':True,'optimizer_updates':0,'loss':float(loss.detach()),'seconds':time.monotonic()-started,'peak_allocated_mib':torch.cuda.max_memory_allocated()/2**20,'peak_reserved_mib':torch.cuda.max_memory_reserved()/2**20} + Path(a.out).write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/split_patch/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/split_patch/model.py new file mode 100644 index 0000000000000000000000000000000000000000..af1af318784c94a1d9ee75ed377582745bd30136 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member2/training/split_patch/model.py @@ -0,0 +1,204 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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,input_patch=None): + super().__init__();self.patch=patch;self.input_patch=patch if input_patch is None else input_patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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,input_patch=self.input_patch) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(self.input_patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;ip=self.input_patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%ip,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//ip + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,ip),valid.view(b,nt,ip).float()),-1)) + pmask=valid.view(b,nt,ip).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/model_manifest.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/model_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..6523a23540d6f4ef6c66842beceb26018876a99b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/model_manifest.json @@ -0,0 +1,308 @@ +{ + "name": "fresh146m-96000", + "contract": "timeseries-forecast/v1", + "parameters": 146477344, + "pretrained_assets": [], + "sources_used": [ + "gifteval_pretrain/BEIJING_SUBWAY_30MIN", + "gifteval_pretrain/HZMETRO", + "gifteval_pretrain/LOS_LOOP", + "gifteval_pretrain/PEMS03", + "gifteval_pretrain/PEMS04", + "gifteval_pretrain/PEMS07", + "gifteval_pretrain/PEMS08", + "gifteval_pretrain/PEMS_BAY", + "gifteval_pretrain/Q-TRAFFIC", + "gifteval_pretrain/SHMETRO", + "gifteval_pretrain/alibaba_cluster_trace_2018", + "gifteval_pretrain/australian_electricity_demand", + "gifteval_pretrain/azure_vm_traces_2017", + "gifteval_pretrain/bdg-2_bear", + "gifteval_pretrain/bdg-2_fox", + "gifteval_pretrain/bdg-2_panther", + "gifteval_pretrain/bdg-2_rat", + "gifteval_pretrain/bitcoin_with_missing", + "gifteval_pretrain/borealis", + "gifteval_pretrain/borg_cluster_data_2011", + "gifteval_pretrain/buildings_900k", + "gifteval_pretrain/bull", + "gifteval_pretrain/cdc_fluview_ilinet", + "gifteval_pretrain/cdc_fluview_who_nrevss", + "gifteval_pretrain/china_air_quality", + "gifteval_pretrain/cif_2016_12", + "gifteval_pretrain/cif_2016_6", + "gifteval_pretrain/cmip6_2000", + "gifteval_pretrain/cmip6_2005", + "gifteval_pretrain/cmip6_2010", + "gifteval_pretrain/cockatoo", + "gifteval_pretrain/covid19_energy", + "gifteval_pretrain/covid_mobility", + "gifteval_pretrain/elecdemand", + "gifteval_pretrain/elf", + "gifteval_pretrain/era5_2010", + "gifteval_pretrain/era5_2011", + "gifteval_pretrain/era5_2012", + "gifteval_pretrain/era5_2013", + "gifteval_pretrain/era5_2014", + "gifteval_pretrain/era5_2015", + "gifteval_pretrain/era5_2016", + "gifteval_pretrain/era5_2017", + "gifteval_pretrain/era5_2018", + "gifteval_pretrain/extended_web_traffic_with_missing", + "gifteval_pretrain/favorita_sales", + "gifteval_pretrain/favorita_transactions", + "gifteval_pretrain/gfc12_load", + "gifteval_pretrain/gfc14_load", + "gifteval_pretrain/gfc17_load", + "gifteval_pretrain/godaddy", + "gifteval_pretrain/hog", + "gifteval_pretrain/ideal", + "gifteval_pretrain/kaggle_web_traffic_weekly", + "gifteval_pretrain/kdd2022", + "gifteval_pretrain/largest_2017", + "gifteval_pretrain/largest_2018", + "gifteval_pretrain/largest_2019", + "gifteval_pretrain/largest_2020", + "gifteval_pretrain/largest_2021", + "gifteval_pretrain/lcl", + "gifteval_pretrain/london_smart_meters_with_missing", + "gifteval_pretrain/m1_monthly", + "gifteval_pretrain/m1_quarterly", + "gifteval_pretrain/m1_yearly", + "gifteval_pretrain/m5", + "gifteval_pretrain/monash_m3_monthly", + "gifteval_pretrain/monash_m3_other", + "gifteval_pretrain/monash_m3_quarterly", + "gifteval_pretrain/nn5_daily_with_missing", + "gifteval_pretrain/nn5_weekly", + "gifteval_pretrain/oikolab_weather", + "gifteval_pretrain/pdb", + "gifteval_pretrain/project_tycho", + "gifteval_pretrain/residential_load_power", + "gifteval_pretrain/residential_pv_power", + "gifteval_pretrain/rideshare_with_missing", + "gifteval_pretrain/sceaux", + "gifteval_pretrain/smart", + "gifteval_pretrain/solar_power", + "gifteval_pretrain/spain", + "gifteval_pretrain/subseasonal", + "gifteval_pretrain/subseasonal_precip", + "gifteval_pretrain/sunspot_with_missing", + "gifteval_pretrain/taxi_30min", + "gifteval_pretrain/tourism_quarterly", + "gifteval_pretrain/tourism_yearly", + "gifteval_pretrain/traffic_hourly", + "gifteval_pretrain/traffic_weekly", + "gifteval_pretrain/uber_tlc_daily", + "gifteval_pretrain/uber_tlc_hourly", + "gifteval_pretrain/vehicle_trips_with_missing", + "gifteval_pretrain/wiki-rolling_nips", + "gifteval_pretrain/wind_farms_with_missing", + "gifteval_pretrain/wind_power", + "synthetic:both original and sign-reflected orientations of each sampled allowed or locally generated window; paired quantile loss, seed 307", + "synthetic:own Fourier/trend/intermittent generator with AR time constant log-uniform from 1 to 10000 steps and zero initial state; seed 307", + "synthetic:own direct_v1 Fourier seasons, damped trends, AR noise, changepoints and intermittent demand; seeds 307", + "synthetic:own random requested-horizon prefixes, half of rows retain the full horizon and half use a patch-rounded prefix between one-quarter and the full horizon; independent seed 300310" + ], + "weights_sha256": "d7cfcd72c3cb84aa69e447b76c4c3ab98c21b7c600a463f0b805f4b4300baf33", + "config": { + "d": 1024, + "heads": 16, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "training_lineage": [ + { + "checkpoint": "runs/random_capacity_1024/ema096000.pt", + "sha256": "d7cfcd72c3cb84aa69e447b76c4c3ab98c21b7c600a463f0b805f4b4300baf33", + "step": 96000, + "seed": 307, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 48, + "lr": 0.0002, + "steps": 96000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": true, + "synthetic_ar_time_constants": [ + 1, + 10000 + ], + "requested_horizon_seed": 300310, + "normalization_overflow_fallback": true + }, + "model_config": { + "d": 1024, + "heads": 16, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "random_capacity_1024_initial.pt" + ] + }, + { + "checkpoint": "random_capacity_1024_initial.pt", + "sha256": "c9693619ca6277c26fef3b2bde37ff6796bec97b3af9f94588bbc5ddd329ec90", + "step": 0, + "seed": 307, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 1024, + "heads": 16, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "initialization": "random initialization in this workspace" + } + ], + "symmetric_averaging": true, + "seasonal_gate": { + "variance_ratio_threshold": 0.25, + "maximum_weight": 0.98, + "cycles_averaged": 4, + "template_mode": "aligned", + "amplitude_ratio_clip": [ + 0.5, + 2.0 + ], + "latest_cycle_minimum_coverage": 0.75, + "variance_noise_correction": "mean squared seasonal differences / 2" + }, + "continuity": { + "decay_steps": 24, + "variance_ratio_threshold": 0.5, + "maximum_weight": 0.95, + "lookback": 512, + "slope_median_differences": 8 + }, + "notes": "All training lineage originates from random initialization here, using only the declared corpus and locally generated series. Validation was used only for selection and diagnostics. Context transformations are fixed formulas; there is no inference-time fitting or parameter adaptation.", + "runtime_code_sha256": { + "infer.sh": "5fe66b4fe9a4787285d830cfd96975701e97286a75ba7c3687bd8891475edf68", + "ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "seasonal.py": "b946e63048196ab5ea8b249137d48c80d8510943caccd0f180e4fb86d9b24b37", + "continuity.py": "dbb08d2229ad80ad00f638b0b9f2f6ca13c663e0fd6730058e5fee8ff54545d5", + "zero_mass.py": "f079d509009bcda409b80eb64467c869b838cfbab11b2bd4c660c2875b6642fe", + "predict.py": "5583ff7e00623f91b7ef4cfbefa8ba8e08c7a0666efb3be58915c1296892f19c", + "model.py": "44eeb23c037e91b8f67e432615ce46540a7ac4242919785f9c4218de23121499" + }, + "normalization_overflow_fallback": { + "trigger": "nonfinite float32 context mean or scale", + "arithmetic": "float64 context statistics on affected rows; original arithmetic on ordinary rows", + "inference_fitting": false + }, + "final_training_stage": { + "trainable_scope": "all parameters", + "sign_loss": "paired", + "learning_rate_multipliers": {} + }, + "trend_summary": { + "fixed_averaging_width": 128, + "matches_all_pretraining_context_widths": true, + "independent_of_batch_padding": true + }, + "zero_mass_projection": { + "threshold_in_context_standard_deviations": 0.4, + "nonnegative_context_required": true, + "minimum_exact_zeros": 4, + "minimum_zero_fraction": 0.1, + "context_cap": 4096 + }, + "recency_features": { + "query_projection_parameters": 65536, + "latest_vs_four_cycle_level": true, + "amplitude_ratio_clip": [ + 0.5, + 2.0 + ], + "minimum_observed_cycles": 3 + }, + "confidence_features": { + "query_projection_parameters": 6144, + "backbone_frozen_during_projection_training": false, + "training_objective": "weighted quantile and median loss after averaging both sign orientations", + "statistics": [ + "mean absolute difference", + "root mean square difference" + ], + "lags": "one and the two frequency-derived periods", + "lookback": "512 for lag one; eight cycles for seasonal lags", + "minimum_valid_pairs": 8, + "insufficient_pair_defaults": [ + 1, + 1.4142135623730951 + ], + "statistic_clip": 10, + "transform": "log1p", + "stage_scope": "Projection trained jointly from random initialization; all training stages are recorded in training_lineage.training_settings." + }, + "partial_target_training": { + "available_horizon": "last finite training-label position rounded up to the patch boundary", + "decoder_future_key_mask": true, + "per_row_horizon_metadata": true, + "inference_uses_requested_horizon_only": true + }, + "training_provenance_code_sha256": { + "random_capacity/check.py": "c5090883cc4e983a41041a319a5260f4d1d5c88bb3133b0651ea5e077845fb8d", + "random_capacity/check_anneal_schedule.py": "e7a431afbd93b3a542786781a4065d5802743965dadc42759cb1d3d50c3adbd5", + "random_capacity/data.py": "d84032a33937a465acfc9e1b97004ca8d9db221509bb2710e74500703ade4344", + "random_capacity/initialize.py": "2a3326d8f2340e9f3fb9ccdea4a69c94c25f9cb969b883ec5e89bb7a53e1e317", + "random_capacity/launch_anneal.py": "3e3b8784781519f77fffac9f683eea847d14df92bf829c2022e520a6074fbb25", + "random_capacity/launch_legacy.py": "d9bd7980146ccb62c292907aa50713e37d0be2dfeac829cf075c140747e9041a", + "random_capacity/launch_lower_rate.py": "44ce2d26ce1adc76023893e82734c2634c840541e7f88f9cef5b51e503a1ef97", + "random_capacity/model.py": "44eeb23c037e91b8f67e432615ce46540a7ac4242919785f9c4218de23121499", + "random_capacity/queue_recovery3.py": "72b59dff33a62ccb584cece127fb3e0d1631a893ab3d5ffb791a3398f9d902f2", + "random_capacity/restart_corrected.py": "1f020aa304f1ce92d452ed884d0dbe5a0607f2d2c2fb6537f9e0bcf42412fde9", + "recovery/brief.py": "99a691dd3055ebfa63bf4423fb36de4d0e320e233fcfa811aa146c8800a614a1", + "recovery/capacity_curves.py": "2bdc6635705b70a868e115cd13eb529563acacf6f47c71f250a50dce8e943be4", + "recovery/exposure_audit.py": "54c194a626b8876ece84686b39b22360155c9fada7248a393ca9b7d6ee38002b", + "recovery/launch_matched_cutoffs.py": "7d5b9b569df284c143bb4fe50033ed6be21ff1b54cb4405723b2ebcdefe6e562", + "recovery/matched_report.py": "82696104e2e7da9cee48611e42aebc0f5c4916f2273fdeb9a3158c4dd3700b04", + "recovery/median_error_structure.py": "f6e126496eba2e0aa1fce1efeac7e926f0fbc28005ab81c0f1c9cf73ecd93782", + "recovery/pack_composition.py": "66c198e44b55fc4dce50dec505a0127eb9d97390e04d0f97c271ace11ad0f49f", + "recovery/quantile_coverage.py": "7a4057d1aa38c5e7de0ca601db0003a8fd3a9a2e6123b2fdb81fa8aedbc34787", + "recovery/reclaim_completed_cache.py": "d0a23e5a73b362f03a3be0d9fcc8dd5292d17da0489484a9c52af84bd05d9638", + "recovery/refresh_journal.py": "6ccbbbf7494f3b310f2e4d47e572487b62494ae52ef6598de93ce8ae28c8a7a5", + "recovery/relaunch_20261022b.py": "f90ddd77928a793c8e151ba74cfa9cc84c8aefad0c0d943a833c74bc07b79313", + "recovery/relaunch_20261023.py": "a4c40c5674b0d05cfe9bb1fffe907f02dec16c53cbddb8b86efbba1b96649097", + "recovery/schedules.py": "7748fd6b2bbbe64037472faf7e6583d03cf339138d2f3c07b1bac9e65bf2d4f5", + "recovery/seasonal_history_support.py": "fe2da1a695715c3add9472f0bfebc946783b179b1a8415f85565a937885f7076", + "recovery/snapshot.py": "4f54a6eecee56150395ce60a9b721b035b718d3cffab0500614eaca3620ad1bf", + "recovery/synthetic_window_audit.py": "912e38fd094f35fb528a77388d8076600207b369bb3b2c2133a24c3c485019a1", + "recovery/train.py": "7b980656e2962268d7995bafe9398b60239f4075f1d91a62c7173f7b2cd3f29c", + "recovery/watch_matched_cutoffs.py": "177dbe6d8b5186dd3ce1c4b261a55cd5cfb44f6ed2922ef64b489deb2117fa6b" + } +} diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/random_capacity/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/random_capacity/check.py new file mode 100644 index 0000000000000000000000000000000000000000..3b6d1440f762d7e57f47bb267df05b5dd786c223 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/random_capacity/check.py @@ -0,0 +1,49 @@ +"""Measure maximum training memory and verify compiled paired-loss gradients.""" +import argparse +import fcntl +import json +from pathlib import Path +import time +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +ap=argparse.ArgumentParser();ap.add_argument('--width',type=int,required=True);a=ap.parse_args() +R=Path('/workspace/research');lock=open(R/'.evaluation.lock','a');fcntl.flock(lock,fcntl.LOCK_EX) +torch.set_num_threads(1);torch.manual_seed(313);torch.backends.cuda.matmul.allow_tf32=True +started=time.monotonic();ck=torch.load(R/f'random_capacity_{a.width}_initial.pt',map_location='cpu',weights_only=False) +m=DirectForecaster(**ck['config']).cuda();m.load_state_dict(ck['model']) +sampler=Sampler(R/'packed_sample',seed=313,source_weights_from=R/'packed_sample') +arrays=sampler.sample(48,4096,1024);x,y,p=[torch.from_numpy(v).cuda() for v in arrays] +# Placeholders account for the EMA and two Adam moments without taking any update. +state_placeholders=[torch.empty_like(v) for v in m.parameters() for _ in range(3)] +with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(m,x,y,p,paired=True) +loss.backward();torch.cuda.synchronize() +assert torch.isfinite(loss) and all(v.grad is not None and torch.isfinite(v.grad).all() for v in m.parameters()) +memory={'batch':48,'signed_rows':96,'context':4096,'horizon':1024,'loss':float(loss.detach()), + 'peak_allocated_mib':torch.cuda.max_memory_allocated()/2**20, + 'peak_reserved_mib':torch.cuda.max_memory_reserved()/2**20} +del state_placeholders,loss,x,y,p,arrays +m.zero_grad(set_to_none=True);torch.cuda.empty_cache() +x,y,p=[torch.from_numpy(v).cuda() for v in sampler.sample(8,512,128)] +def step(fn): + m.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=fn(m,x,y,p,paired=True) + loss.backward() + return float(loss.detach()) +reference=step(loss_fn);grads={n:v.grad.detach().clone() for n,v in m.named_parameters()} +compile_started=time.monotonic();actual=step(torch.compile(loss_fn,fullgraph=True,dynamic=False));torch.cuda.synchronize() +dot=norma=normb=0.;maximum=0. +for name,v in m.named_parameters(): + left,right=grads[name],v.grad + assert torch.isfinite(right).all() + dot+=float((left*right).sum());norma+=float(left.square().sum());normb+=float(right.square().sum()) + maximum=max(maximum,float((left-right).abs().max())) +cosine=dot/(norma*normb)**.5 +assert abs(reference-actual)<.003*max(reference,.1) and cosine>.995 +result={'normalization_overflow_fallback':True,'width':a.width,'initialization_seed':307,'fixture_seed':313,'optimizer_updates':0, + 'maximum_shape_memory':memory,'eager_loss':reference,'compiled_loss':actual, + 'gradient_cosine':cosine,'max_gradient_difference':maximum, + 'compile_comparison_seconds':time.monotonic()-compile_started, + 'total_seconds':time.monotonic()-started,'source':'allowed packed_sample and own synthetic generator only'} +(R/f'random_capacity_{a.width}_checks.json').write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/random_capacity/check_anneal_schedule.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/random_capacity/check_anneal_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..6c52591b8672097d4dd3466bc7850131929588ce --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/random_capacity/check_anneal_schedule.py @@ -0,0 +1,24 @@ +"""Check the new cooldown and unchanged default learning-rate arithmetic.""" +import json +import math +import sys +import time +from pathlib import Path +R=Path('/workspace/research');sys.path.insert(0,str(R/'recovery')) +from schedules import learning_rate +started=time.monotonic() +checked=0 +for total,peak,reset in [(12000,2e-5,-1),(96000,2e-4,-1),(32000,3e-5,8000)]: + for step in range(1,total+1): + warm=step-reset if reset>=0 and step>reset else step + original=peak*min(1,warm/400)*(.2+.4*(1+math.cos(math.pi*step/total))) + assert learning_rate(step,total,peak,reset)==original + checked+=1 +start=learning_rate(24000,96000,2e-4) +values=[learning_rate(i,36000,2e-4,-1,24000,start,1e-5) for i in range(24000,36001)] +assert values[0]==start and values[-1]==1e-5 +assert all(08 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/random_capacity/initialize.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/random_capacity/initialize.py new file mode 100644 index 0000000000000000000000000000000000000000..ff8f0f3e2d3f9dfa2e8378e90c31bab5ecf4d22e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/random_capacity/initialize.py @@ -0,0 +1,26 @@ +"""Create fresh local random initializations for the matched capacity comparison.""" +import hashlib +import json +from pathlib import Path +import time +import torch +from model import DirectForecaster + +R=Path('/workspace/research');torch.set_num_threads(2) +receipts=[] +for d,heads in [(512,8),(1024,16)]: + start=time.monotonic();torch.manual_seed(307) + model=DirectForecaster(d=d,heads=heads,enc_layers=6,dec_layers=4,patch=16, + recency_features=True,confidence_features=True,partial_target_lengths=True) + path=R/f'random_capacity_{d}_initial.pt' + assert not path.exists(),path + ck={'model':model.state_dict(),'config':model.config,'step':0, + 'args':{'packed':str(R/'packed_sample'),'seed':307}, + 'initialization':{'method':'torch modules initialized locally, zero output weights with fixed seasonal-mixture and interval biases', + 'seed':307,'parent_weights':[]}, + 'parent_checkpoints':[],'lr_multipliers':{}} + torch.save(ck,path) + receipts.append({'path':str(path),'sha256':hashlib.sha256(path.read_bytes()).hexdigest(), + 'parameters':sum(p.numel() for p in model.parameters()),'seed':307, + 'cpu_seconds':time.monotonic()-start,'optimizer_updates':0}) +(R/'random_capacity_initialization.json').write_text(json.dumps(receipts,indent=2));print(json.dumps(receipts)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/random_capacity/launch_anneal.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/random_capacity/launch_anneal.py new file mode 100644 index 0000000000000000000000000000000000000000..b192187a1714510e172dd17378cc6b85bff26744 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/random_capacity/launch_anneal.py @@ -0,0 +1,38 @@ +"""Branch one fresh37M run for a matched training-only cooldown comparison.""" +def main(): + import json + import os + import subprocess + from pathlib import Path + R=Path('/workspace/research') + snapshot=json.loads((R/'random_capacity_512_recovery024000.json').read_text());assert snapshot['step']==24000 + check=json.loads((R/'random_capacity_anneal_checks.json').read_text());assert check['default_steps_bitwise_equal']==140000 + env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1',TORCHINDUCTOR_COMPILE_THREADS='2',MAX_JOBS='2', + PYTHONPATH=str(R/'compiler_support'),TRITON_CACHE_MANAGER='sibling_cache:SiblingFileCacheManager', + TRITON_CACHE_DIR='/tmp/timeseries-triton-cache',TORCHINDUCTOR_CACHE_DIR='/tmp/timeseries-inductor-cache') + command=['python3',str(R/'recovery/train.py'),'--code-dir',str(R/'random_capacity'), + '--packed',str(R/'packed_sample'),'--source-weights-from',str(R/'packed_sample'), + '--out',str(R/'runs/random_capacity_512_anneal'),'--initialize-from',str(R/'random_capacity_512_initial.pt'), + '--resume',str(R/'random_capacity_512_recovery024000.pt'),'--steps','36000','--batch','48', + '--lr','.0002','--seed','307','--loss-mode','paired','--compile-loss', + '--anneal-from-step','24000','--anneal-from-lr',str(check['join_lr']),'--anneal-final-lr','.00001', + '--stop-file',str(R/'random_capacity_512_anneal.stop')] + with (R/'random_capacity_512_anneal_queue.log').open('w') as qlog: + queued=subprocess.Popen(['python3',str(R/'queued_train.py'),'--label','E99 fresh37M early cooldown', + '--log',str(R/'random_capacity_512_anneal_train.log'), + '--receipt',str(R/'random_capacity_512_anneal_queue.json'), + '--wait-pid','5689','--require-checkpoint',str(R/'runs/patch4_candidate/recovery.pt'), + '--',*command],stdout=qlog,stderr=subprocess.STDOUT,env=env) + watchers=[] + for name in ['random_capacity_512_anneal','random_capacity_512']: + with (R/(name+'_cooldown_watch.log')).open('w') as log: + watchers.append(subprocess.Popen(['python3',str(R/'watch_evaluate.py'),'--run',str(R/'runs'/name), + '--evaluator',str(R/'random_capacity_inference/evaluate.py'),'--name',name, + '--steps','30000,36000'],stdout=log,stderr=subprocess.STDOUT,env=env)) + print({'queue_pid':queued.pid,'watch_pids':[p.pid for p in watchers]},flush=True) + result=queued.wait() + if result: + for p in watchers:p.terminate() + for p in watchers:p.wait() + raise SystemExit(result) +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/random_capacity/launch_legacy.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/random_capacity/launch_legacy.py new file mode 100644 index 0000000000000000000000000000000000000000..5bf7ac326ec15b02e9caea0b6357babc57c3d6e5 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/random_capacity/launch_legacy.py @@ -0,0 +1,43 @@ +def main(): + """Queue the matched fresh-width pair after two existing allocations are released.""" + import json + from pathlib import Path + import subprocess + + R=Path('/workspace/research') + recovery=json.loads((R/'recovery2_launch_receipt.json').read_text()) + dependencies=['wide_capacity_146m_recovery','patch8'] + wait_pids=[recovery['jobs'][name]['pid'] for name in dependencies] + children=[] + for width in [512,1024]: + checks=json.loads((R/f'random_capacity_{width}_checks.json').read_text()) + assert checks['gradient_cosine']>.995 + name=f'random_capacity_{width}' + train=['env','OPENBLAS_NUM_THREADS=1','OMP_NUM_THREADS=1', + 'TORCHINDUCTOR_COMPILE_THREADS=2','MAX_JOBS=2', + 'PYTHONPATH=/workspace/research/compiler_support', + 'TRITON_CACHE_MANAGER=sibling_cache:SiblingFileCacheManager', + 'TRITON_CACHE_DIR=/tmp/timeseries-triton-cache', + 'TORCHINDUCTOR_CACHE_DIR=/tmp/timeseries-inductor-cache', + 'python3',str(R/'recovery/train.py'),'--code-dir',str(R/'random_capacity'), + '--packed',str(R/'packed_sample'),'--source-weights-from',str(R/'packed_sample'), + '--out',str(R/'runs'/name),'--initialize-from',str(R/f'{name}_initial.pt'), + '--steps','96000','--batch','48','--lr','.0002','--seed','307', + '--loss-mode','paired','--compile-loss','--stop-file',str(R/f'{name}.stop')] + command=['python3',str(R/'queued_train.py'),'--label',f'E79 fresh{width} seed307', + '--log',str(R/f'{name}_train.log'),'--receipt',str(R/f'{name}_queue.json')] + for pid in wait_pids:command+=['--wait-pid',str(pid)] + for dep in dependencies:command+=['--require-checkpoint',str(R/'runs'/dep/'recovery.pt')] + command+=['--']+train + with (R/f'{name}_queue.log').open('w') as f: + children.append(subprocess.Popen(command,stdout=f,stderr=subprocess.STDOUT)) + watch=['python3',str(R/'watch_evaluate.py'),'--run',str(R/'runs'/name), + '--evaluator',str(R/'random_capacity_inference/evaluate.py'),'--name',name, + '--steps','4000,8000,16000,24000,48000,72000,96000'] + with (R/f'{name}_watch.log').open('w') as f: + subprocess.Popen(watch,stdout=f,stderr=subprocess.STDOUT) + for child in children:child.wait() + assert all(child.returncode==0 for child in children) + +if __name__ == "__main__": + main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/random_capacity/launch_lower_rate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/random_capacity/launch_lower_rate.py new file mode 100644 index 0000000000000000000000000000000000000000..a9b2c79450b71b081832e7eaf0dce361c7da2a8d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/random_capacity/launch_lower_rate.py @@ -0,0 +1,40 @@ +"""Queue a single-factor lower-learning-rate arm for the fresh146M model.""" +def main(): + import json + import os + import subprocess + from pathlib import Path + R = Path('/workspace/research') + checks = json.loads((R / 'random_capacity_1024_checks.json').read_text()) + assert checks['gradient_cosine'] > .995 and checks['normalization_overflow_fallback'] + name = 'random_capacity_1024_halflr' + env = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1') + train = ['env', 'OPENBLAS_NUM_THREADS=1', 'OMP_NUM_THREADS=1', + 'TORCHINDUCTOR_COMPILE_THREADS=2', 'MAX_JOBS=2', + 'PYTHONPATH=/workspace/research/compiler_support', + 'TRITON_CACHE_MANAGER=sibling_cache:SiblingFileCacheManager', + 'TRITON_CACHE_DIR=/tmp/timeseries-triton-cache', + 'TORCHINDUCTOR_CACHE_DIR=/tmp/timeseries-inductor-cache', + 'python3', str(R / 'recovery/train.py'), '--code-dir', str(R / 'random_capacity'), + '--packed', str(R / 'packed_sample'), '--source-weights-from', str(R / 'packed_sample'), + '--out', str(R / 'runs' / name), '--initialize-from', str(R / 'random_capacity_1024_initial.pt'), + '--steps', '96000', '--batch', '48', '--lr', '.0001', '--seed', '307', + '--loss-mode', 'paired', '--compile-loss', '--stop-file', str(R / (name + '.stop'))] + with (R / (name + '_queue.log')).open('w') as qlog, (R / (name + '_watch.log')).open('w') as wlog: + queued = subprocess.Popen(['python3', str(R / 'queued_train.py'), '--label', 'E94 fresh146M halfLR seed307', + '--log', str(R / (name + '_train.log')), '--receipt', str(R / (name + '_queue.json')), + '--wait-pid', '5690', '--require-checkpoint', str(R / 'runs/patch4_control/recovery.pt'), + '--', *train], stdout=qlog, stderr=subprocess.STDOUT, env=env) + watch = subprocess.Popen(['python3', str(R / 'watch_evaluate.py'), '--run', str(R / 'runs' / name), + '--evaluator', str(R / 'random_capacity_inference/evaluate.py'), '--name', name, + '--steps', '4000,8000,16000,24000,48000,72000,96000'], + stdout=wlog, stderr=subprocess.STDOUT, env=env) + print(json.dumps({'queue_pid': queued.pid, 'watch_pid': watch.pid}), flush=True) + result = queued.wait() + if result: + watch.terminate() + watch.wait() + raise SystemExit(result) + +if __name__ == '__main__': + main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/random_capacity/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/random_capacity/model.py new file mode 100644 index 0000000000000000000000000000000000000000..3532e5063bd8b5013f6b6e35703707ffef66e00b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/random_capacity/model.py @@ -0,0 +1,213 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/random_capacity/queue_recovery3.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/random_capacity/queue_recovery3.py new file mode 100644 index 0000000000000000000000000000000000000000..ca60d7ce3a745482824790ba818da843c84274fc --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/random_capacity/queue_recovery3.py @@ -0,0 +1,44 @@ +def main(): + """Queue the matched fresh-width pair after two existing allocations are released.""" + import json + from pathlib import Path + import subprocess + + R=Path('/workspace/research') + recovery=json.loads((R/'recovery3_launch_receipt.json').read_text()) + dependencies=['wide_capacity_146m_recovery','patch8'] + wait_pids=[recovery['jobs'][name]['pid'] for name in dependencies] + children=[] + for width in [512,1024]: + checks=json.loads((R/f'random_capacity_{width}_checks.json').read_text()) + assert checks['gradient_cosine']>.995 and checks.get('normalization_overflow_fallback') is True + name=f'random_capacity_{width}' + train=['env','OPENBLAS_NUM_THREADS=1','OMP_NUM_THREADS=1', + 'TORCHINDUCTOR_COMPILE_THREADS=2','MAX_JOBS=2', + 'PYTHONPATH=/workspace/research/compiler_support', + 'TRITON_CACHE_MANAGER=sibling_cache:SiblingFileCacheManager', + 'TRITON_CACHE_DIR=/tmp/timeseries-triton-cache', + 'TORCHINDUCTOR_CACHE_DIR=/tmp/timeseries-inductor-cache', + 'python3',str(R/'recovery/train.py'),'--code-dir',str(R/'random_capacity'), + '--packed',str(R/'packed_sample'),'--source-weights-from',str(R/'packed_sample'), + '--out',str(R/'runs'/name),'--initialize-from',str(R/f'{name}_initial.pt'), + '--steps','96000','--batch','48','--lr','.0002','--seed','307', + '--loss-mode','paired','--compile-loss','--stop-file',str(R/f'{name}.stop')] + command=['python3',str(R/'queued_train.py'),'--label',f'E79 fresh{width} seed307', + '--log',str(R/f'{name}_train.log'),'--receipt',str(R/f'{name}_queue.json')] + for pid in wait_pids:command+=['--wait-pid',str(pid)] + for dep in dependencies:command+=['--require-checkpoint',str(R/'runs'/dep/'recovery.pt')] + command+=['--']+train + with (R/f'{name}_queue.log').open('w') as f: + children.append(subprocess.Popen(command,stdout=f,stderr=subprocess.STDOUT)) + watch=['python3',str(R/'watch_evaluate.py'),'--run',str(R/'runs'/name), + '--evaluator',str(R/'random_capacity_inference/evaluate.py'),'--name',name, + '--steps','4000,8000,16000,24000,48000,72000,96000'] + with (R/f'{name}_watch.log').open('w') as f: + watcher=subprocess.Popen(watch,stdout=f,stderr=subprocess.STDOUT) + print(json.dumps({'width':width,'queue_pid':children[-1].pid,'watch_pid':watcher.pid}),flush=True) + for child in children:child.wait() + assert all(child.returncode==0 for child in children) + +if __name__ == "__main__": + main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/random_capacity/restart_corrected.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/random_capacity/restart_corrected.py new file mode 100644 index 0000000000000000000000000000000000000000..0fa492437cc10d940ab177575b4583064dedfcb5 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/random_capacity/restart_corrected.py @@ -0,0 +1,13 @@ +"""Validate the shared numerical correction, then start exactly one matched fresh pair.""" +def main(): + import json,os,subprocess,time + from pathlib import Path + R=Path('/workspace/research');env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1',TORCHINDUCTOR_COMPILE_THREADS='2',MAX_JOBS='2',PYTHONPATH=str(R/'compiler_support'),TRITON_CACHE_MANAGER='sibling_cache:SiblingFileCacheManager',TRITON_CACHE_DIR='/tmp/timeseries-triton-cache',TORCHINDUCTOR_CACHE_DIR='/tmp/timeseries-inductor-cache') + for width in (512,1024): + assert not list((R/'runs'/f'random_capacity_{width}').glob('*.pt')) + log=R/f'random_capacity_{width}_corrected_check.log' + with log.open('w') as f:subprocess.run(['python3',str(R/'random_capacity/check.py'),'--width',str(width)],stdout=f,stderr=subprocess.STDOUT,env=env,check=True) + result=json.loads((R/f'random_capacity_{width}_checks.json').read_text());print(json.dumps(result),flush=True) + with (R/'direct_v1/EXPERIMENTS.md').open('a') as f:f.write('\nE79 corrected-normalization fixture: '+json.dumps(result)+'\n') + subprocess.run(['python3',str(R/'random_capacity/queue_recovery3.py')],env=env,check=True) +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/brief.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/brief.py new file mode 100644 index 0000000000000000000000000000000000000000..393c1bd2df50c28b82a75d584d6f0f4d0e317fe4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/brief.py @@ -0,0 +1,34 @@ +"""Write a short, current recovery handoff; never modify training state.""" +import datetime +import json +from pathlib import Path + +R = Path('/workspace/research') +s = json.loads((R/'CURRENT_RESEARCH_STATE.json').read_text()) +lines = ['# Current recovery brief', '', datetime.datetime.now(datetime.timezone.utc).isoformat(), '', + 'Continuous research; no endpoint/final hand-in. One H10080GB,22CPUs,224GiB requested RAM; no network or pretrained assets. Do not inspect credentials or spawn agents.', '', + '## Published', '', json.dumps(s['published']), '', '## Pending selection', '', + json.dumps(s.get('next_candidate',{})), '', json.dumps({k:v for k,v in s.get('selection_probes',{}).items() if k in ['E128','E130','E132','E133','E134','E135','E136','E137','E138','E139','E140']}), '', '## Active and queued training', ''] +for name, job in s.get('external_jobs',{}).items(): + if job['status'] not in ['running','waiting']: + continue + lines += [f'- {name}: {job["status"]}; receipt {job["receipt"]}; queue PID snapshot {job["queue_pid_at_snapshot"]}; children {job["child_pids_at_snapshot"]}.', + f' Last logged record: {json.dumps(job["last_phase_record"])}', + f' Complete recovery: {job["complete_recovery_checkpoint"]}; latest EMA: {job["latest_saved_ema"]}.'] +lines += ['', '## Recovery rules', '', + '- PIDs and launch-script dependencies are snapshots. After an operator restart, restore running jobs from each complete recovery.pt, preserving optimizer/EMA/RNG/prefetched batch and original schedules. Rewire waiting jobs to the newly launched dependency PIDs; do not blindly rerun old launch scripts.', + '- Waiting dependency chain: weekly_replication_control after long_seasonal; weekly_replication_candidate after that control; lowfreq_windows after that candidate; long_seasonal_replication after lowfreq_windows. phase_joint waits for random_capacity_512 final96000; seasonal_dispersion waits for phase_joint final12000; seasonal_history waits for seasonal_dispersion final12000. random_capacity_original_ar waits for random_capacity_1024 final96000; log_horizon waits for long_seasonal_replication final12000; seasonal_width waits for seasonal_history final12000; random_capacity_long_seasonal waits for both E94halfLR and E79wide final96000 and replaces only the E94allocation. visibility_curriculum waits for E110full and E79wide final96000 and replaces only the E110allocation; preserve --visibility-curriculum on any resume. direct_trend_head waits for E129seasonal_width final12000 and replaces that allocation. random_capacity_deep waits for E122originalAR and E79wide final96000, replacing only the E122allocation.', + '- E121 history-aware ensemble runtime is prepared at history_three_patch_ensemble; synthetic audit checks exact standalone composition and ordinary legacy equality. It also applies member finite cleanup before averaging, correcting a pre-existing extreme-value discrepancy. Use this separate publisher and complete public replay before any E121 publication; E130 now publishes four members using four_member_ensemble/publish.py, retaining both finite cleanup and per-member history support. Use that publisher for four-member packages.', + '- E126 compiled_teacher_trial completed its mandatory17000stop; do not resume it. It preserved original96000 LR schedule from immutable distill_ensemble_recovery016000.pt. Original E101 stays active. Compiler takeover rejected: max cutoff drift0.001964 exceeded0.0005 tolerance, with only3to5percent warm shared-device timing gain. No coefficient change selected. E125 component ablations completed; both paths help. E127 finite-member numerical fix is published with all97predictions bitwise unchanged; do not republish it. E128 dispersion transfers6000 and12000 both lost full validation; neither is published. E130 equal-quarter package is the current best. E132 checks scheduled E79wide96000 as the fourth member; E133 passed both source replication gates but its fixed averaged correction failed the ensemble gate (2of4positive, mean-0.0000154271); no full replay or averaging sweep. Receipts are indexed in CURRENT_RESEARCH_STATE.json.', + '- E138 learned gate uses immutable /workspace/research/gating_experts_E130, descriptorfa97880d..., even if submission improves. CPU/GPU/recovery/publicruntime/relocation audits passed; queued after E123final12000. Check queue receipt and rewire dependencies after restart. Training must preserve --gate-package and restore complete optimizer/EMA/RNG/prefetched batch. No expert tensors enter the gate optimizer. Gate publisher is ensemble_gate/publish.py. E139width primary6k is published at0.3843356309048914 after allfour diagnostics/fullsuite/bitwisecomposition;12k requires matched-source gate. E140separate loader-only candidate is in timing/identity checks, not published; gate trainer/experts loader unchanged. Use seasonal_width_transfer/promote.py only after better full replay and all checks.', + '- E101 distillation teacher is immutable /workspace/research/distill_teacher_E96, even after later publications. Do not substitute the current submission.', + '- Restore compiler_cache_backup to the same /tmp cache paths before restarting compiled trainers. Exact environment and commands are in CURRENT_RESEARCH_STATE.json.', + '- E105 output collision is documented in incidents/stratified_volume_output_collision. Correct E105 output is runs/stratified_volume. E95final and2k..12k weights survive, but E95optimizer recovery and original1k weights were lost. Do not resume completed E95.', + '- All previous negative/stopped branches stay stopped unless a new matched experiment explicitly revisits them. Never retrain the supplied baselines.', + '- Current training-source publisher archives all Python modules from explicitly declared directories, fixing earlier omissions of spectral.py and schedules.py. Complete-source members carry a -complete suffix when rebuilt. Runtime/weight hashes were unchanged.', + '- Full evaluation and GPU diagnostics use .evaluation.lock; the six main trainers share the one H100. The bounded E126 seventh-process probe completed17000 and should remain stopped. Dataset windows under data/valid and all earlier cutoffs are selection only, never training.', + '- Master journal direct_v1/EXPERIMENTS.md, chronological SESSION_20261023_PROGRESS.md, and RESEARCH_IDEAS.md contain decisions and rejected candidates. Recheck live processes and latest reports before acting.', + '', '## Time anchor', '', + 'Latest operator recovery allowance:151596research seconds at2026-10-23T02:45:51UTC. Pauses/preflight excluded. The goal remains active and has no requested token budget.', ''] +(R/'RECOVERY_BRIEF.md').write_text('\n'.join(lines)) +print('Wrote RECOVERY_BRIEF.md with '+str(sum(j['status'] in ['running','waiting'] for j in s.get('external_jobs',{}).values()))+' active/queued jobs.') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/capacity_curves.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/capacity_curves.py new file mode 100644 index 0000000000000000000000000000000000000000..c89a28a84243dc16ae52a1215c182a00f15dbc4e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/capacity_curves.py @@ -0,0 +1,50 @@ +"""Summarize completed validation checkpoints and measured shared-GPU training time.""" +import csv +import json +import time +from pathlib import Path + +R = Path('/workspace/research') +started = time.monotonic() +names = ['random_capacity_512', 'random_capacity_1024', 'random_capacity_1024_halflr', + 'random_capacity_full', 'distill_ensemble', 'random_capacity_512_anneal'] +rows = [] +for name in names: + log = R/(name+'_train.log') + records = {} + if log.exists(): + for line in log.read_text().splitlines(): + try: + item = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(item,dict) and 'step' in item and 'seconds' in item: + records[item['step']] = item + config_path = R/'runs'/name/'config.json' + config = json.loads(config_path.read_text()) if config_path.exists() else {} + for report in sorted((R/'evals').glob(name+'_ema*/report.json')): + result = json.loads(report.read_text()) + step = int(report.parent.name.rsplit('ema',1)[1]) + if result['n_failed']: + continue + record = records.get(step,{}) + rows.append(dict(run=name,step=step,parameters=config.get('parameters'), + seed=config.get('seed'),batch=config.get('batch'),learning_rate=config.get('lr'), + packed=config.get('packed'),skill=result['skill_score'], + rel_mase=result['rel_mase_gmean'],rel_wql=result['rel_wql_gmean'], + checkpoint_sha256=result['checkpoint_sha256'], + training_phase_loop_seconds=record.get('seconds'), + evaluation_seconds=result.get('eval_seconds'),report=str(report))) +rows.sort(key=lambda item:(names.index(item['run']),item['step'])) +output = dict(generated_utc=time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()), + note='Validation selection only. Time is logged process wall on the shared single H100, not isolated GPU time. The cooldown arm starts from the same saved24000state; its phase clock resets. No missing log time is inferred.', + rows=rows,analysis_seconds=time.monotonic()-started,no_training_or_new_inference=True) +(R/'capacity_learning_curves.json').write_text(json.dumps(output,indent=2)) +with (R/'capacity_learning_curves.csv').open('w',newline='') as handle: + writer = csv.DictWriter(handle,fieldnames=list(rows[0]) if rows else ['run']) + writer.writeheader() + writer.writerows(rows) +for name in names: + selected = [r for r in rows if r['run']==name] + if selected: + print(json.dumps(selected[-1])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/exposure_audit.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/exposure_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..fb67738bc9ed77f87173feda2430365e66c75966 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/exposure_audit.py @@ -0,0 +1,46 @@ +"""Describe sampled observation exposure and training invested in selected ancestry.""" +import json +import sys +import time +from pathlib import Path +import numpy as np + +R=Path('/workspace/research') +sys.path.insert(0,str(R/'random_capacity')) +from data import Sampler + +started=time.monotonic() +seed=521 +sampler=Sampler(R/'packed_sample',seed=seed,source_weights_from=R/'packed_sample') +rng=np.random.default_rng(seed) +rows=context_points=target_points=0 +for _ in range(320): + 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])) + x,y,p=sampler.sample(64,c,h) + rows+=len(x) + context_points+=int(np.isfinite(x).sum()) + target_points+=int(np.isfinite(y).sum()) +manifest=json.loads(Path('/workspace/submission/model_manifest.json').read_text()) +runs={} +for item in manifest['training_lineage']: + path=Path(item['checkpoint']) + batch=item.get('training_settings',{}).get('batch') + if path.parts[0]!='runs' or not batch: + continue + run=path.parts[1] + step=item.get('step',0) + if step>runs.get(run,{}).get('step',0): + runs[run]=dict(step=step,batch=batch,rows=step*batch,checkpoint=item['checkpoint']) +ancestral_rows=sum(v['rows'] for v in runs.values()) +mean_points=(context_points+target_points)/rows +result=dict(seed=seed,seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False, + sampled_rows=rows,mean_finite_context_points=context_points/rows, + mean_finite_target_points=target_points/rows,mean_finite_points=mean_points, + selected_descriptor=manifest['checkpoint_sha256'],ancestral_runs=runs, + selected_ancestral_rows_before_sign_pairing=ancestral_rows, + fresh96000_batch48_rows=96000*48, + fresh96000_batch48_gross_observation_presentations_estimate=96000*48*mean_points, + note='Gross sampled presentations include overlapping/resampled windows and synthetic values, not unique observations. Ancestral run maxima count compute invested in different branches, including subtracted controls; they are not an equivalent single-model training trajectory. Sign pairing duplicates compute but not distinct sampled rows. No future training recipe is inferred from this audit alone.') +(R/'training_exposure_audit.json').write_text(json.dumps(result,indent=2)) +print(json.dumps({k:v for k,v in result.items() if k!='ancestral_runs'})) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/launch_matched_cutoffs.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/launch_matched_cutoffs.py new file mode 100644 index 0000000000000000000000000000000000000000..6d33e64b8212b250fc38a2990604c80228b94c80 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/launch_matched_cutoffs.py @@ -0,0 +1,14 @@ +"""Keep evaluation controllers alive for the declared queued comparisons.""" +from pathlib import Path +import datetime,json,os,subprocess +R=Path('/workspace/research');jobs={};processes={};env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1') +for name,control,runtime,label in [('lowfreq_windows','overflow_control','postloss_inference','E113'),('seasonal_history','long_seasonal','seasonal_history_inference','E121'),('seasonal_width','seasonal_dispersion','seasonal_width_inference','E129'),('long_seasonal_replication','weekly_replication_control','long_seasonal_inference','E118'),('log_horizon','overflow_control','postloss_inference','E123')]: + path=R/(name+'_matched_cutoffs.log') + with path.open('a') as log: + command=['python3',str(R/'recovery/watch_matched_cutoffs.py'),'--run',name,'--control',control,'--evaluator',str(R/runtime/'evaluate.py'),'--label',label] + p=subprocess.Popen(command,stdout=log,stderr=subprocess.STDOUT,env=env) + processes[label]=p;jobs[label]=dict(pid=p.pid,parent_pid=os.getpid(),command=command,log=str(path),receipt=str(R/(name+'_matched_cutoffs_receipt.json'))) +q=R/'CURRENT_RESEARCH_STATE.json';state=json.loads(q.read_text());state['diagnostics']['matched_cutoff_controllers']=jobs;t=q.with_suffix('.tmp');t.write_text(json.dumps(state,indent=2));os.replace(t,q) +print(json.dumps(jobs),flush=True) +for label,p in processes.items(): + result=p.wait();print(json.dumps(dict(label=label,returncode=result)),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/matched_report.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/matched_report.py new file mode 100644 index 0000000000000000000000000000000000000000..f7755cfc0300a5a18f3e2db1d6d5aa89cda9f0fa --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/matched_report.py @@ -0,0 +1,16 @@ +"""Record matched validation reports, including all configuration-group metrics.""" +import argparse,datetime,json,math +from pathlib import Path +R=Path('/workspace/research');ap=argparse.ArgumentParser() +for key in ['candidate','control','label','out']:ap.add_argument('--'+key,required=True) +ap.add_argument('--cutoffs',default='0');ap.add_argument('--outcome',required=True);a=ap.parse_args() +folders=['evals','backcast_evals','backcast2_evals','backcast3_evals'];rows=[] +for index in map(int,a.cutoffs.split(',')): + folder=folders[index];x=json.loads((R/folder/a.candidate/'report.json').read_text());y=json.loads((R/folder/a.control/'report.json').read_text()) + assert x['n_failed']==y['n_failed']==0 and x['n_configs']==y['n_configs'] + delta={g:{k:math.sqrt(y['groups'][g][k]['rel_mase_gmean']*y['groups'][g][k]['rel_wql_gmean'])-math.sqrt(v['rel_mase_gmean']*v['rel_wql_gmean']) for k,v in entries.items()} for g,entries in x['groups'].items()} + rows.append(dict(cutoff=folder,candidate_skill=x['skill_score'],control_skill=y['skill_score'],delta=x['skill_score']-y['skill_score'],candidate_checkpoint=x['checkpoint_sha256'],control_checkpoint=y['checkpoint_sha256'],candidate_eval_seconds=x.get('eval_seconds'),candidate_groups=x['groups'],control_groups=y['groups'],group_skill_delta=delta)) +result=dict(label=a.label,utc=datetime.datetime.now(datetime.timezone.utc).isoformat(),candidate=a.candidate,control=a.control,rows=rows,mean_delta=sum(v['delta'] for v in rows)/len(rows),positive_cutoffs=sum(v['delta']>0 for v in rows),outcome=a.outcome) +p=Path(a.out);assert not p.exists(),'Refuse duplicate comparison record';p.write_text(json.dumps(result,indent=2)) +with (R/'direct_v1/EXPERIMENTS.md').open('a') as f:f.write('\n'+a.label+': '+json.dumps(result)+'\n') +print(json.dumps({k:v for k,v in result.items() if k!='rows'})) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/median_error_structure.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/median_error_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..83bb24d13841f0266d0947799c682f47e8641474 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/median_error_structure.py @@ -0,0 +1,30 @@ +"""Describe validation median errors without fitting or proposing corrected forecasts.""" +import argparse,json,sys,time +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +from ts_io import read_prediction_file,read_truth_file +ap=argparse.ArgumentParser() +for n in ['valid','pred','report','out']:ap.add_argument('--'+n,required=True) +a=ap.parse_args();start=time.monotonic();root=Path(a.valid);report=json.loads(Path(a.report).read_text());rows=[] +for cfg in report['configs']: + cid=cfg['config_id'];y,scale,_=read_truth_file(root/'truth/cases'/(cid+'.h5'));_,q=read_prediction_file(Path(a.pred)/'cases'/(cid+'.h5')) + good=np.isfinite(scale)&(scale>0);valid=np.isfinite(y)&good[...,None];safe=np.where(good,scale,1).astype(np.float64) + err=np.where(valid,(q[:,:,4,:].astype(np.float64)-y.astype(np.float64))/safe[...,None],0.) + n=valid.sum(-1);total=int(n.sum());mae=float(np.abs(err).sum()/total) + signed=float(err.sum()/total);absolute_window_mean=float(np.abs(err.sum(-1)).sum()/total) + assert absolute_window_mean<=mae+1e-10 + lead=[] + for positions in np.array_split(np.arange(y.shape[-1]),4): + mask=valid[...,positions];count=int(mask.sum());values=err[...,positions] + lead.append(dict(count=count,mase=float(np.abs(values).sum()/count),signed_scaled_error=float(values.sum()/count))) + rows.append(dict(config_id=cid,term=cfg['term'],domain=cfg['domain'],frequency=cfg['freq'],horizon=cfg['prediction_length'],mase=mae,scorer_mase=cfg['metrics']['mase'],signed_scaled_error=signed,absolute_window_mean_error=absolute_window_mean,window_mean_error_fraction_of_mae=absolute_window_mean/max(mae,1e-30),lead_quarters=lead)) + assert abs(mae-cfg['metrics']['mase'])<1e-6*max(1,mae) +groups={} +for key in ['term','domain','frequency']: + groups[key]={} + for value in sorted({row[key] for row in rows}): + selected=[row for row in rows if row[key]==value] + groups[key][value]=dict(configs=len(selected),mean_window_mean_error_fraction=float(np.mean([row['window_mean_error_fraction_of_mae'] for row in selected])),mean_signed_error_over_mae=float(np.mean([row['signed_scaled_error']/max(row['mase'],1e-30) for row in selected])),mean_lead_quarter_mase_ratio=[float(np.mean([row['lead_quarters'][i]['mase']/max(row['mase'],1e-30) for row in selected])) for i in range(4)]) +result=dict(checkpoint_sha256=report['checkpoint_sha256'],groups=groups,configs=rows,seconds=time.monotonic()-start,optimizer_updates=0,new_inference=False,note='Validation-only descriptive analysis. Absolute per-window mean error is a Jensen lower bound on MAE, not a recoverable correction or attributable causal component. Groups average configurations equally; lead ratios are descriptive, not the benchmark metric. No parameter fitting or forecast modification.') +Path(a.out).write_text(json.dumps(result,indent=2));print(json.dumps({k:v for k,v in result.items() if k!='configs'})) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/pack_composition.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/pack_composition.py new file mode 100644 index 0000000000000000000000000000000000000000..0a023de983f7c0860043b58def56406e3fd27eb9 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/pack_composition.py @@ -0,0 +1,32 @@ +"""Read-only comparison of source/length composition in the two allowed packs.""" +import json,time +from pathlib import Path +import numpy as np +R=Path('/workspace/research');started=time.monotonic();old=R/'packed_sample';new=R/'packed_stratified_full' +a=json.loads((old/'meta.json').read_text());b=json.loads((new/'meta.json').read_text());assert a['dirs']==b['dirs'];names=a['dirs'] +weights=[] +for n in names: + w=min((old/(n+'.bin')).stat().st_size//4,20000000)**.25 + if n.startswith(('era5_','cmip6_')):w*=.35 + if n.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) +weights=np.array(weights)/sum(weights);bins=np.array([16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131073]) +rows=[];aggregate={k:np.zeros(len(bins)-1) for k in ['old','full']} +for n,w in zip(names,weights): + row={'source':n,'conditional_real_source_probability':float(w)} + for k,root in [('old',old),('full',new)]: + lengths=np.diff(np.load(root/(n+'.offsets.npy'),mmap_mode='r')) + hist=np.histogram(lengths,bins=bins)[0]/len(lengths);aggregate[k]+=w*hist + row[k]={'series':len(lengths),'points':int(lengths.sum()),'mean_length':float(lengths.mean()),'median_length':float(np.median(lengths)), + 'fraction_below64':float(np.mean(lengths<64)),'fraction_below256':float(np.mean(lengths<256)), + 'fraction_at_least20480':float(np.mean(lengths>=20480)),'length_bin_probabilities':hist.tolist()} + row['weighted_length_distribution_l1']=float(w*np.abs(np.array(row['old']['length_bin_probabilities'])-row['full']['length_bin_probabilities']).sum()) + row['mixed_frequency_rows_in_full']=b['receipts'][n]['mixed_frequency_rows_in_candidates'];row['full_frequencies']=b['receipts'][n]['kept_frequencies'];rows.append(row) +result=dict(kind='per-source uniform-series sampling composition; no series values or validation labels read', + length_bins=bins.tolist(),conditional_real_length_bin_probabilities={k:v.tolist() for k,v in aggregate.items()}, + source_probabilities_unchanged=True,min_length_both=16,max_crop_length_both=131072, + mixed_frequency_sources=[r['source'] for r in rows if r['mixed_frequency_rows_in_full']],sources=rows, + seconds=time.monotonic()-started,optimizer_updates=0) +(R/'pack_composition_comparison.json').write_text(json.dumps(result,indent=2)) +print(json.dumps({k:v for k,v in result.items() if k!='sources'})) +for row in sorted(rows,key=lambda r:-r['weighted_length_distribution_l1'])[:12]:print(json.dumps({k:v for k,v in row.items() if k not in ['old','full']},separators=(',',':')), 'mean_length',row['old']['mean_length'],row['full']['mean_length']) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/quantile_coverage.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/quantile_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..d7f4958ae772a15c4a580eed59bb9257b065154d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/quantile_coverage.py @@ -0,0 +1,59 @@ +"""Validation-only quantile coverage, with separate strict/inclusive coverage at atoms.""" +import argparse +import json +import sys +import time +from pathlib import Path + +import numpy as np + +sys.path.insert(0,'/workspace/evaluation') +from ts_io import read_prediction_file, read_truth_file + +parser = argparse.ArgumentParser() +parser.add_argument('--valid',required=True) +parser.add_argument('--pred',required=True) +parser.add_argument('--report',required=True) +parser.add_argument('--out',required=True) +args = parser.parse_args() +started = time.monotonic() +root = Path(args.valid) +index = json.loads((root/'input/index.json').read_text()) +report = json.loads(Path(args.report).read_text()) +levels = np.arange(1,10)/10 +rows = [] +for cfg in index['configs']: + relative = Path('cases')/(cfg['config_id']+'.h5') + y,scale,_ = read_truth_file(root/'truth'/relative) + _,q = read_prediction_file(Path(args.pred)/relative) + valid = np.isfinite(y) + assert q.shape==(*y.shape[:2],9,y.shape[-1]) and np.isfinite(q).all() + count = int(valid.sum()) + assert count>0 + strict = ((y[:,:,None,:] anneal_from_step + assert 0 < anneal_final_lr <= anneal_from_lr + progress=max(0.,min(1.,(step-anneal_from_step)/(steps-anneal_from_step))) + return anneal_final_lr+.5*(anneal_from_lr-anneal_final_lr)*(1+math.cos(math.pi*progress)) + warm_step=step-reset_at if reset_at>=0 and step>reset_at else step + return peak*min(1,warm_step/400)*(.2+.4*(1+math.cos(math.pi*step/steps))) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/seasonal_history_support.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/seasonal_history_support.py new file mode 100644 index 0000000000000000000000000000000000000000..84314b30b22a4a761447fc5ee1cffb9301e725b9 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/seasonal_history_support.py @@ -0,0 +1,23 @@ +"""Context-metadata diagnostic of potential 8-cycle support, with no targets read.""" +import importlib.util,json,time +from pathlib import Path +import h5py,numpy as np +R=Path('/workspace/research');started=time.monotonic() +spec=importlib.util.spec_from_file_location('support_model',R/'long_seasonal/model.py');m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m) +root=Path('/workspace/data/valid/input');index=json.loads((root/'index.json').read_text());rows=[] +for cfg in index['configs']: + with h5py.File(root/'cases'/(cfg['config_id']+'.h5'),'r') as f:lengths=np.asarray(f['context_length']) + h=cfg['prediction_length'];periods=m.periods_for_freq(cfg['freq']);row={k:cfg[k] for k in ['config_id','freq','term','domain']};row['periods']=periods;row['n_instances']=len(lengths) + for cap in [4096,16384]: + support=[];cycles=[] + for p in periods: + count=np.clip(1+(np.minimum(lengths,cap)[:,None]-p+np.arange(h)[None,:]%p)//p,0,16) + support.append(float(np.mean((count>=8)&(p>=2))));cycles.append(float(np.mean(np.where(p>=2,count,0)))) + row[str(cap)]={'phase_support_fraction':support,'mean_available_cycles':cycles} + row['support_gain_sum']=sum(row['16384']['phase_support_fraction'])-sum(row['4096']['phase_support_fraction']);rows.append(row) +changed=[r for r in rows if r['support_gain_sum']>0] +result=dict(kind='optimistic potential support before missing-value masks; not measured forecast improvement',input_metadata_only=True,validation_targets_read=False,optimizer_updates=0,configs=rows, + changed_configurations=len(changed),changed_domains=sorted(set(r['domain'] for r in changed)),seconds=time.monotonic()-started) +(R/'seasonal_history_support.json').write_text(json.dumps(result,indent=2)) +print(json.dumps({k:v for k,v in result.items() if k!='configs'})) +for r in sorted(changed,key=lambda x:x['support_gain_sum'],reverse=True)[:20]:print(json.dumps(r)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/snapshot.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/snapshot.py new file mode 100644 index 0000000000000000000000000000000000000000..b2ac1a1421c086707a28f55843eb948471ec62e3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/snapshot.py @@ -0,0 +1,99 @@ +"""Write a compact authoritative research recovery index without touching training state.""" +import datetime +import json +import os +from pathlib import Path + +R=Path('/workspace/research');p=R/'CURRENT_RESEARCH_STATE.json' +s=json.loads(p.read_text()) +s['snapshot_utc']=datetime.datetime.now(datetime.timezone.utc).isoformat() +receipt=json.loads((R/'recovery3_launch_receipt.json').read_text()) +s['runs']={} +for name,job in receipt['jobs'].items(): + run=R/'runs'/name + log=Path(job['log']) + records=[] + for line in log.read_text().splitlines(): + try: + record=json.loads(line) + if 'step' in record or 'completed_step' in record:records.append(record) + except json.JSONDecodeError:pass + s['runs'][name]={'config':json.loads((run/'config.json').read_text()) if (run/'config.json').exists() else None, + 'last_phase_record':records[-1] if records else None, + 'phase_log':str(log),'supervisor_receipt':str(R/'recovery3_launch_receipt.json'), + 'latest_saved_ema':str(max(run.glob('ema*.pt'))) if list(run.glob('ema*.pt')) else None, + 'complete_recovery_checkpoint':str(run/'recovery.pt') if (run/'recovery.pt').exists() else None, + 'pid_at_snapshot':job['pid'],'returncode':job.get('returncode'), + 'note':'Check actual live process and checkpoint state before resuming; this is only a snapshot.'} +s['queues']={name:{'status':q['status'],'dependency':q['dependency'],'command':q['command'], + 'required_checkpoints':q['required_checkpoints']} + for name,q in receipt['queues'].items()} +s.pop('prepared_not_launched',None) +s['deferred_unqueued']={'E72':'temporal_mixup, prepared and checked but not queued','ideas':'RESEARCH_IDEAS.md, no jobs attached'} +s['completed_since_previous_recovery']={ + 'E67_control12000':{'skill':.37724286394256845,'training_loop_seconds':2794.8358458959847}, + 'E67_paired12000':{'skill':.377427077277383,'training_loop_seconds':2794.867385860998}, + 'E63_expanded146M':'Stopped8501, complete recovery retained; allocation moved to E73; inconclusive data scaling', + 'E61_slowAR':'Complete12000; E76 used6000 correction, final transfer rejected', + 'E65_recent_normalization':'Complete12000; E81 equal ensemble rejected', + 'E58_small_control':'Complete32000', + 'E58_wide146M':'Complete32000; no gain over37Mcontrol; do not resume', + 'E71_patch8':'Complete12000; selected6000 used in E87/E96/E102 ensembles', + 'E69_volatility':'Complete12000; final below matched control; no transfer', + 'E89_patch8_control':'Complete12000; final0.380847096,loop2729.052105s; selected starting E71parent remains stronger', + 'E89_fullpatch4':'Complete12000,main0.381640078; E96 used6000, E103final cached alternative mixed; loop5066.016522s', + 'E93_split_patch':'Complete12000,main0.381711986; selected final is E102 published thirdmember; loop3153.565149s', + 'E92_robust_normalization':'Complete12000,final0.377099312 belowcontrol; rejected;E97started', + 'E90_metric_scale':'Complete12000; final0.377373344 ties/slightly trailsE80; no selection; loop2702.166704s', + 'E84_coarse':'Complete12000; daily gain but weekly regression; not selected', + 'E88_late_patch8_slowAR':'Complete12000; small9k gain lost atfinal; rejected', + 'E80_overflow':'Complete12000; finaltiesoriginal; selected3k compositeE91rejected', + 'E78_multiscaleAR':'Complete12000; no gain over single slowAR', + 'E86_protected_graft':'Complete8000; below own initialization; no publication', + 'E75_postloss':'Stopped3653 deliberately; immutable snapshot retained; E98 separately declared completion active in another output, original stopfile remains', + 'E73_independent_graft':'Stopped8683 after negative8000; replaced by E86; stopfile remains', + 'E95_stratified_corpus':'Complete12000,final0.377983250,earliermixed; E105collision destroyed only1000weights and optimizer recovery;2k..12k preserved; do not resume', + 'E97_weekly_synth':'Complete12000,final0.380439539; E112final weekly correction now published; loop2600.472750s', + 'E105_stratified_volume':'Complete12000,final0.377529200,earlier0.336713522/0.359535697/0.390349158 mixed; corrected continuationloop2013.982814s plus original incident phase', + 'E106_spectral_synth':'Complete12000,final0.377641399,earlier0.337647555/0.361626447/0.385497870, average matched gap negligible; loop2206.272278s; E114fixed6000transfers in selection', + 'E98_postloss_completion':'Complete12000,final0.376034254 below3000 andcontrol; rejected,loop1995.386513s', + 'E99_early_cooldown':'Complete36000,final0.363306598 trails original36k0.364859034; rejected,loop1603.635706s', + 'E77_pairedslowAR':'Complete12000;6000 strongest main/earlier comparison'} +s['external_receipts']=[str(R/'postloss_recovery3_receipt.json'),str(R/'random_capacity_512_queue.json'),str(R/'random_capacity_1024_queue.json'),str(R/'multiscale_ar_queue.json'),str(R/'overflow_control_queue.json'),str(R/'coarse_aggregate_queue.json'),str(R/'patch8_long_memory_queue.json'),str(R/'wide_graft_frozen_queue.json'),str(R/'patch4_candidate_queue.json'),str(R/'patch4_control_queue.json'),str(R/'metric_scale_queue.json'),str(R/'robust_normalization_queue.json'),str(R/'split_patch_queue.json'),str(R/'random_capacity_1024_halflr_queue.json'),str(R/'stratified_corpus_queue.json'),str(R/'weekly_synth_queue.json'),str(R/'postloss_completion_queue.json'),str(R/'random_capacity_512_anneal_queue.json'),str(R/'distill_ensemble_queue.json'),str(R/'stratified_volume_queue.json'),str(R/'spectral_synth_queue.json'),str(R/'long_seasonal_queue.json'),str(R/'random_capacity_full_queue.json'),str(R/'weekly_replication_control_queue.json'),str(R/'weekly_replication_candidate_queue.json'),str(R/'lowfreq_windows_queue.json'),str(R/'phase_joint_queue.json'),str(R/'long_seasonal_replication_queue.json'),str(R/'seasonal_dispersion_queue.json'),str(R/'seasonal_history_queue.json'),str(R/'random_capacity_original_ar_queue.json'),str(R/'log_horizon_queue.json'),str(R/'compiled_teacher_trial_queue.json'),str(R/'seasonal_width_queue.json'),str(R/'random_capacity_long_seasonal_queue.json'),str(R/'visibility_curriculum_queue.json'),str(R/'direct_trend_head_queue.json'),str(R/'random_capacity_deep_queue.json'),str(R/'ensemble_gate_queue.json')] +queue_pids={'random_capacity_512_queue.json':965,'random_capacity_1024_queue.json':967, + 'multiscale_ar_queue.json':1678,'overflow_control_queue.json':1676, + 'coarse_aggregate_queue.json':3086,'patch8_long_memory_queue.json':3739, + 'wide_graft_frozen_queue.json':3931,'patch4_candidate_queue.json':4078, + 'patch4_control_queue.json':4080} +s['external_jobs']={} +for receipt_name in s['external_receipts']: + receipt_path=Path(receipt_name) + if not receipt_path.exists():continue + item=json.loads(receipt_path.read_text());command=item.get('command',[]) + if '--out' not in command:continue + run=Path(command[command.index('--out')+1]);log=Path(item.get('log',str(receipt_path).replace('_queue.json','_train.log'))) + last=None + if log.exists(): + for line in log.read_text().splitlines(): + try: + record=json.loads(line) + if isinstance(record,dict) and ('step' in record or 'completed_step' in record):last=record + except json.JSONDecodeError:pass + queue_pid=item.get('launcher_pid',queue_pids.get(receipt_path.name)) + children_file=Path(f'/proc/{queue_pid}/task/{queue_pid}/children') if queue_pid else None + children=list(map(int,children_file.read_text().split())) if children_file and children_file.exists() else [] + checkpoints=list(run.glob('ema*.pt')) + s['external_jobs'][run.name]={'receipt':str(receipt_path),'status':item.get('status'), + 'queue_pid_at_snapshot':queue_pid,'child_pids_at_snapshot':children, + 'last_phase_record':last,'log':str(log), + 'latest_saved_ema':str(max(checkpoints)) if checkpoints else None, + 'complete_recovery_checkpoint':str(run/'recovery.pt') if (run/'recovery.pt').exists() else None, + 'command':command,'note':'PIDs are only a snapshot; check actual processes and serialized state before recovery.'} +s['compiler_environment']={'OPENBLAS_NUM_THREADS':'1','OMP_NUM_THREADS':'1','TORCHINDUCTOR_COMPILE_THREADS':'2','MAX_JOBS':'2','PYTHONPATH':str(R/'compiler_support'),'TRITON_CACHE_MANAGER':'sibling_cache:SiblingFileCacheManager','TRITON_CACHE_DIR':'/tmp/timeseries-triton-cache','TORCHINDUCTOR_CACHE_DIR':'/tmp/timeseries-inductor-cache'} +for job in s['external_jobs'].values(): + job['environment']=s['compiler_environment'] if '--compile-loss' in job['command'] else {'OPENBLAS_NUM_THREADS':'1','OMP_NUM_THREADS':'1'} +s['compiler_cache_backup']=str(R/'compiler_cache_backup') +for stale in ['pending','pending_actions','active_experiments','next_experiments','prepared_experiments']: + s.pop(stale,None) +tmp=p.with_suffix('.tmp');tmp.write_text(json.dumps(s,indent=2));os.replace(tmp,p) +print(s['snapshot_utc']) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/synthetic_window_audit.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/synthetic_window_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..5a6455bbd9926f9d342ee1a24ca825328a9e7e1f --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/synthetic_window_audit.py @@ -0,0 +1,63 @@ +"""Compare actual allowed/synthetic training-window dynamics without validation data.""" +import datetime +import json +from pathlib import Path +import sys +import time +import types +import numpy as np + +R=Path('/workspace/research') +sys.path.insert(0,str(R/'overflow_control')) +source=(R/'overflow_control/data.py').read_text() +needle='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)' +assert source.count(needle)==1 +instrumented=source.replace(needle,needle+';self.audit_synthetic=np.zeros(batch,bool)') +needle='if r.random()=16 and len(target)>=4: + k=min(16,n//4,len(target)) + # Descriptive finite-observation means, not a proposed inference feature. + scale=max(float(np.std(values)),float(np.mean(np.abs(values)))*1e-4,1e-4) + past=(float(np.mean(values[-k:]))-float(np.mean(values[-2*k:-k])))/scale + future=(float(np.mean(target[:k].astype(np.float64)))-float(np.mean(values[-k:])))/scale + item.update(past_change=float(np.clip(past,-20,20)),future_change=float(np.clip(future,-20,20))) + groups.setdefault(frequency+'_'+kind,[]).append(item);counts+=1 +summary={} +for name,rows in groups.items(): + c=np.array([x['context'] for x in rows]);h=np.array([x['target'] for x in rows]) + valid=[x for x in rows if x['past_change'] is not None] + past=np.array([x['past_change'] for x in valid]);future=np.array([x['future_change'] for x in valid]) + summary[name]=dict(rows=len(rows),median_finite_context=float(np.median(c)), + context_at_most128=float(np.mean(c<=128)),context_above512=float(np.mean(c>512)), + median_finite_target=float(np.median(h)),dynamic_rows=len(valid), + median_abs_recent_change=float(np.median(np.abs(past))), + median_abs_future_change=float(np.median(np.abs(future))), + recent_future_change_correlation=float(np.corrcoef(past,future)[0,1])) +result=dict(seed=seed,rows=counts,batches=160,groups=summary,seconds=time.monotonic()-started, + generated_utc=datetime.datetime.now(datetime.timezone.utc).isoformat(), + instrumentation_first640_rows_and_rng_bitwise=True,optimizer_updates=0, + validation_data_read=False,decision='Descriptive audit only. E113 remains unchanged; no new generator selected.') +(R/'synthetic_window_audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/train.py new file mode 100644 index 0000000000000000000000000000000000000000..065dcacb628103ba06aed5cdf1c9868860599ae0 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/train.py @@ -0,0 +1,255 @@ +"""Resumable continuation of our existing permitted-corpus experiments.""" +import argparse,copy,fcntl,inspect,json,math,os,sys,time +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import numpy as np +import torch + +ap=argparse.ArgumentParser() +ap.add_argument('--code-dir',required=True);ap.add_argument('--packed',required=True) +ap.add_argument('--source-weights-from');ap.add_argument('--out',required=True) +ap.add_argument('--initialize-from',required=True);ap.add_argument('--initialize-ema') +ap.add_argument('--start-step',type=int,default=0);ap.add_argument('--resume') +ap.add_argument('--steps',type=int,required=True);ap.add_argument('--batch',type=int,required=True) +ap.add_argument('--lr',type=float,required=True);ap.add_argument('--seed',type=int,required=True) +ap.add_argument('--context',type=int);ap.add_argument('--sample-context',type=int,default=4096) +ap.add_argument('--save-every',type=int,default=1000);ap.add_argument('--stop-file') +ap.add_argument('--recovery-every',type=int,default=250) +ap.add_argument('--halt-after',type=int) +ap.add_argument('--loss-mode',choices=['individual','paired']) +ap.add_argument('--compile-loss',action='store_true') +ap.add_argument('--reset-at',type=int,default=-1);ap.add_argument('--reset-seed',type=int,default=179) +ap.add_argument('--anneal-from-step',type=int);ap.add_argument('--anneal-from-lr',type=float) +ap.add_argument('--anneal-final-lr',type=float) +ap.add_argument('--teacher-package');ap.add_argument('--teacher-coefficient',type=float) +ap.add_argument('--compile-teacher',action='store_true') +ap.add_argument('--visibility-curriculum',action='store_true') +ap.add_argument('--gate-package') +a=ap.parse_args() +# Hold a process-lifetime lock before loading a model or touching GPU state. +_run_out=Path(a.out);_run_out.mkdir(parents=True,exist_ok=True) +_run_lock=open(_run_out/'.training.lock','a') +try:fcntl.flock(_run_lock,fcntl.LOCK_EX|fcntl.LOCK_NB) +except BlockingIOError:raise SystemExit('Another trainer already owns this output directory: '+str(_run_out)) +if not a.resume: + _saved=list(_run_out.glob('ema*.pt'))+list(_run_out.glob('step*.pt')) + if (_run_out/'recovery.pt').exists():_saved.append(_run_out/'recovery.pt') + if _saved: + raise SystemExit('Refusing fresh training into an output with saved checkpoints; use a new directory or explicit --resume: '+str(_run_out)) +sys.path.insert(0,a.code_dir) +from model import DirectForecaster,loss_fn +from data import Sampler +from schedules import learning_rate +torch.set_num_threads(2);torch.manual_seed(a.seed);torch.backends.cuda.matmul.allow_tf32=True +out=Path(a.out);out.mkdir(parents=True,exist_ok=True);a.trainable_scope='all' +if Path(a.code_dir).name in ('long_memory_synth','paired_long_memory','multiscale_ar','random_capacity','patch8_long_memory','distill_ensemble','random_capacity_long_seasonal','visibility_curriculum','random_capacity_deep'):a.synthetic_ar_time_constants=[1,10000] +if Path(a.code_dir).name in ('full_paired','patch8','temporal_mixup','postloss','paired_long_memory','multiscale_ar','random_capacity','overflow_control','coarse_aggregate','patch8_long_memory','patch4','metric_scale','robust_normalization','split_patch','weekly_synth','distill_ensemble'):a.requested_horizon_seed=a.seed+300003 +if Path(a.code_dir).name=='multiscale_ar': + a.synthetic_ar_components=4;a.multiscale_ar_seed=a.seed+700003 +if Path(a.code_dir).name=='volatility_synth':a.stochastic_volatility_seed=a.seed+500003 +if Path(a.code_dir).name=='coarse_aggregate': + a.coarse_aggregation_seed=a.seed+900003;a.coarse_aggregation_probability=.2;a.coarse_aggregation_frequencies=['D','W'] +if Path(a.code_dir).name=='temporal_mixup':a.temporal_mixup_seed=a.seed+600003 +if Path(a.code_dir).name=='postloss': + a.fixed_postprocessing_loss=True;a.normalization_overflow_fallback=True +if Path(a.code_dir).name in ('overflow_control','metric_scale','random_capacity','weekly_synth','distill_ensemble'):a.normalization_overflow_fallback=True +if Path(a.code_dir).name=='weekly_synth': + a.weekly_synthetic_seed=a.seed+1000003;a.weekly_replacement_probability=1/11 +if Path(a.code_dir).name=='spectral_synth': + a.spectral_synthetic_seed=a.seed+1100003;a.spectral_replacement_probability=.5 + a.spectral_length_scale=[1,10000];a.spectral_families=['Matern0.5','Matern1.5','Matern2.5','RBF'] + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True +if Path(a.code_dir).name in ('long_seasonal','phase_joint','seasonal_dispersion','seasonal_history','seasonal_width','direct_trend_head','random_capacity_long_seasonal','visibility_curriculum','random_capacity_deep','ensemble_gate'): + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True +if Path(a.code_dir).name=='random_capacity_original_ar': + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True + a.synthetic_ar_coefficient_law='uniform(0.2,0.995), original generator; unchanged AR branch probability and asymptotic variance scaling' +if Path(a.code_dir).name=='log_horizon': + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True + a.requested_horizon_law='half full; half geometric quantile remap of the original uniform integer endpoint draw from min(16,max(1,H//4)) to H, then patch16 rounding; identical RNG consumption' +if Path(a.code_dir).name=='seasonal_history': + a.learned_seasonal_history_context=16384;a.recent_encoder_and_rule_context=4096 + a.history_extension_rule='extend originally full4096 real contexts before the same cutoff, preserving original recent contexts, targets, aggregation, sampler RNG and horizon RNG; synthetic extra prefix missing' +if Path(a.code_dir).name=='lowfreq_windows': + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True + a.lowfreq_window_seed=a.seed+1200003;a.lowfreq_window_probability=.5 + a.lowfreq_window_rule='period2=1,period1<=52;finite-target endpoint;log-uniform horizon4..min(H,max(8,2p),span-8) with available-length fallback;context cap min(C,max(64,32p));at least4finite history' +if Path(a.code_dir).name=='metric_scale':a.loss_seasonality='lag1 for exact daily[7,365] and weekly[52,1] period pairs; unchanged otherwise' +if Path(a.code_dir).name=='robust_normalization':a.normalization_kind='finite median plus/minus6 mean absolute deviations winsorized mean/RMS, float64; original normalized history clipped30' +if Path(a.code_dir).name=='wide_graft_frozen':a.trainable_scope='new feature stream and cross-stream blocks; inherited parameter blocks frozen' +if a.visibility_curriculum: + assert Path(a.code_dir).name=='visibility_curriculum' and not a.teacher_package and not a.gate_package + from visibility import visible_batch + a.visibility_curriculum_rule='steps1..16000:lastC/4,firstmax(16,H/4);16001..32000:lastC/2,firstmax(16,H/2);32001..96000:unchanged; sample/prefetch full original windows and crop only current loss arrays' +ck=torch.load(a.resume or a.initialize_from,map_location='cpu',weights_only=False) +# Keep immutable branch ancestry across a later restart from this run's own recovery. +lineage_parents=list(ck.get('parent_checkpoints',[])) +if a.initialize_ema:lineage_parents.append(a.initialize_ema) +if a.resume and Path(a.resume).parent.resolve()!=out.resolve():lineage_parents.append(a.resume) +previous_args=ck.get('args',{}) +previous_resume=previous_args.get('resume') +if previous_resume and Path(previous_resume).parent.resolve()!=Path(previous_args.get('out',a.out)).resolve(): + lineage_parents.append(previous_resume) +lineage_parents=list(dict.fromkeys(lineage_parents)) +config=dict(ck['config']) +if a.context:config['max_context']=a.context +model=DirectForecaster(**config).cuda();model.load_state_dict(ck['model']) +teacher=None;teacher_predict=None;experts=None +if Path(a.code_dir).name=='distill_ensemble': + assert a.teacher_package and a.teacher_coefficient is not None +if a.teacher_package: + assert Path(a.code_dir).name=='distill_ensemble' + from teacher import OwnEnsembleTeacher + with torch.random.fork_rng(devices=[torch.cuda.current_device()]): + teacher=OwnEnsembleTeacher(a.teacher_package) + if ck.get('args',{}).get('teacher_descriptor_sha256'): + assert ck['args']['teacher_descriptor_sha256']==teacher.descriptor_sha256 + assert ck['args']['teacher_coefficient']==a.teacher_coefficient + a.teacher_descriptor_sha256=teacher.descriptor_sha256 + a.teacher_checkpoint_sha256=teacher.member_hashes + a.teacher_target_kind='equal average of own frozen E96 raw normalized sign-paired neural quantiles, before postprocessing' + teacher_predict=teacher + if a.compile_teacher: + torch._dynamo.config.recompile_limit=64 + teacher_predict=torch.compile(teacher.__call__,fullgraph=True,dynamic=False) +else: + assert not a.compile_teacher, '--compile-teacher requires a declared own-model teacher' + +if Path(a.code_dir).name=='ensemble_gate':assert a.gate_package and a.loss_mode=='paired' +if a.gate_package: + assert Path(a.code_dir).name=='ensemble_gate' and not a.teacher_package and not a.compile_loss + from experts import FrozenExperts + from model import FEATURE_NAMES + torch.backends.cuda.matmul.allow_tf32=False + with torch.random.fork_rng(devices=[torch.cuda.current_device()]): + experts=FrozenExperts(a.gate_package) + if ck.get('args',{}).get('fixed_expert_descriptor_sha256'): + assert ck['args']['fixed_expert_descriptor_sha256']==experts.descriptor_sha256 + assert ck['args']['fixed_expert_checkpoint_sha256']==experts.member_hashes + a.fixed_expert_descriptor_sha256=experts.descriptor_sha256 + a.fixed_expert_checkpoint_sha256=experts.member_hashes + a.expert_forecast_kind='four own frozen E130 raw-scale final forecasts, including exact packaged per-member transformations' + a.gate_weight_rule='0.125+0.5*softmax; same positive per-lead weight across all quantiles' + a.gate_features=FEATURE_NAMES + a.trainable_scope='6340 gate parameters only; four experts frozen and excluded from optimizer and EMA' + a.fixed_postprocessing_loss=True + a.gate_precision='FP32 gate, BF16 frozen experts, TF32 disabled' + assert sum(p.numel() for p in model.parameters())==6340 + +protector=None +if Path(a.code_dir).name=='wide_graft_frozen': + from frozen import FreezeInherited + protector=FreezeInherited(model) + a.protected_parameters=protector.inherited_numel +if a.compile_loss: + torch._dynamo.config.recompile_limit=64 + objective=torch.compile(loss_fn,fullgraph=True,dynamic=False) +else:objective=loss_fn +multipliers=ck.get('lr_multipliers',{}) +def optimizer(): + groups=[] + for mult in sorted(set(multipliers.values())|{1.}): + params=[p for n,p in model.named_parameters() if multipliers.get(n,1.)==mult] + if params:groups.append({'params':params,'lr':a.lr*mult,'lr_multiplier':mult,'weight_decay':.05/mult}) + return torch.optim.AdamW(groups,betas=(.9,.95),fused=True) +opt=optimizer() +if a.resume: + start_step=ck['step'];opt.load_state_dict(ck['optimizer']) + ema={k:v.cuda() for k,v in ck['ema_state'].items()} +else: + start_step=a.start_step + ema_ck=torch.load(a.initialize_ema,map_location='cpu',weights_only=False) if a.initialize_ema else ck + ema={k:v.cuda().clone() for k,v in ema_ck['model'].items()} +del ck +def make_sampler(seed): + kwargs={'seed':seed} + if 'source_weights_from' in inspect.signature(Sampler).parameters:kwargs['source_weights_from']=a.source_weights_from + return Sampler(a.packed,**kwargs),np.random.default_rng(seed) +stream_seed=a.reset_seed if a.reset_at>=0 and start_step>=a.reset_at else a.seed +sampler,rng=make_sampler(stream_seed) +def next_batch(): + c=int(rng.choice([512,1024,2048,a.sample_context],p=[.1,.15,.35,.4])) + h=int(rng.choice([32,128,512,1024],p=[.1,.2,.2,.5])) + x,y,p=sampler.sample(a.batch,c,h) + return x[:,-model.max_context:].copy(),y,p +pool=ThreadPoolExecutor(1) +if a.resume: + recovery=torch.load(a.resume,map_location='cpu',weights_only=False) + rng.bit_generator.state=recovery['batch_rng_state'];sampler.rng.bit_generator.state=recovery['sampler_rng_state'] + for name,state in recovery.get('sampler_rng_states',{}).items():getattr(sampler,name).bit_generator.state=state + torch.set_rng_state(recovery['torch_rng_state']);torch.cuda.set_rng_state_all(recovery['cuda_rng_state']) + pending=recovery['prefetched_batch'];del recovery + future=pool.submit(lambda:pending) +else:future=pool.submit(next_batch) +parameters=sum(p.numel() for p in model.parameters()) +(out/'config.json').write_text(json.dumps({**vars(a),'model':model.config,'parameters':parameters},indent=2)) +print(json.dumps({'parameters':parameters,'starting_step':start_step,'stream_seed':stream_seed,'restored_complete_training_state':bool(a.resume)}),flush=True) +started=time.monotonic();losses=[] +def atomic_save(obj,path): + torch.save(obj,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) +def save(step,include_selection_weights=True): + global future + pending_batch=future.result() + common={'config':model.config,'step':step,'args':vars(a),'lr_multipliers':multipliers, + 'parent_checkpoints':list(dict.fromkeys(lineage_parents+(teacher.checkpoints if teacher else [])+(experts.checkpoints if experts else [])))} + if include_selection_weights: + for prefix,state in [('step',model.state_dict()),('ema',ema)]: + atomic_save({**common,'model':state,'ema':prefix=='ema'},out/f'{prefix}{step:06d}.pt') + atomic_save({**common,'model':model.state_dict(),'optimizer':opt.state_dict(),'ema_state':ema, + 'prefetched_batch':pending_batch,'batch_rng_state':copy.deepcopy(rng.bit_generator.state), + 'sampler_rng_state':copy.deepcopy(sampler.rng.bit_generator.state), + 'sampler_rng_states':{name:copy.deepcopy(value.bit_generator.state) for name,value in vars(sampler).items() if isinstance(value,np.random.Generator)}, + 'torch_rng_state':torch.get_rng_state(),'cuda_rng_state':torch.cuda.get_rng_state_all()},out/'recovery.pt') + future=pool.submit(lambda:pending_batch) +for step in range(start_step+1,a.steps+1): + if a.reset_at>=0 and step==a.reset_at+1 and start_step=a.halt_after) + selection_checkpoint=step%a.save_every==0 or step==a.steps or stop + # Persist a complete state before a fresh/resumed job warms its remaining compiled shapes. + if selection_checkpoint or step%a.recovery_every==0 or step==start_step+1: + save(step,include_selection_weights=selection_checkpoint) + if stop:break +pool.shutdown() +print(json.dumps({'completed_step':step,'training_process_loop_seconds':time.monotonic()-started}),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/watch_matched_cutoffs.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/watch_matched_cutoffs.py new file mode 100644 index 0000000000000000000000000000000000000000..3bd2f95022f87dbe1c349575c0ec77662a2d4d6e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member3/training/recovery/watch_matched_cutoffs.py @@ -0,0 +1,34 @@ +"""Complete declared primary/durability comparisons; never select a model automatically.""" +import argparse,datetime,json,os,subprocess,time +from pathlib import Path +R=Path('/workspace/research');ap=argparse.ArgumentParser() +for key in ['run','control','evaluator','label']:ap.add_argument('--'+key,required=True) +ap.add_argument('--control-evaluator');ap.add_argument('--steps',default='6000,12000');a=ap.parse_args();start=time.monotonic() +receipt=R/(a.run+'_matched_cutoffs_receipt.json') +state=dict(pid=os.getpid(),status='running',run=a.run,control=a.control,steps=[],started_utc=datetime.datetime.now(datetime.timezone.utc).isoformat()) +def save(): + state['seconds']=time.monotonic()-start;tmp=receipt.with_suffix('.tmp');tmp.write_text(json.dumps(state,indent=2));os.replace(tmp,receipt) +def call(label,command): + state['status']=label;save();t=time.monotonic();result=subprocess.run(command);state['steps'].append(dict(label=label,returncode=result.returncode,seconds=time.monotonic()-t));save() + if result.returncode:state['status']='failed';save();raise SystemExit(result.returncode) +for step in map(int,a.steps.split(',')): + name=a.run+'_ema'+str(step);report=R/'evals'/name/'report.json';state['status']='waiting for main'+str(step);save() + while not report.exists(): + queue=R/(a.run+'_queue.json') + if queue.exists() and json.loads(queue.read_text()).get('status')=='failed':state['status']='training failed';save();raise SystemExit(1) + time.sleep(3) + time.sleep(1) + call('earlier cutoffs'+str(step),['python3',str(R/'evaluate_cutoffs.py'),'--name',name,'--weights',str(R/'runs'/a.run/f'ema{step:06d}.pt'),'--evaluator',a.evaluator,'--cutoffs','1,2,3']) + control_name=a.control+'_ema'+str(step) + if any(not (R/folder/control_name/'report.json').exists() for folder in ['evals','backcast_evals','backcast2_evals','backcast3_evals']): + assert a.control_evaluator,'Missing matched control reports; pass --control-evaluator for their declared evaluation' + call('control cutoffs'+str(step),['python3',str(R/'evaluate_cutoffs.py'),'--name',control_name,'--weights',str(R/'runs'/a.control/f'ema{step:06d}.pt'),'--evaluator',a.control_evaluator]) + out=R/(a.run+str(step//1000)+'k_four_cutoff_comparison.json') + if out.exists(): + cached=json.loads(out.read_text());assert cached['candidate']==name and cached['control']==a.control+'_ema'+str(step) and len(cached['rows'])==4 + for row,folder in zip(cached['rows'],['evals','backcast_evals','backcast2_evals','backcast3_evals']): + assert row['candidate_checkpoint']==json.loads((R/folder/name/'report.json').read_text())['checkpoint_sha256'] + assert row['control_checkpoint']==json.loads((R/folder/(a.control+'_ema'+str(step))/'report.json').read_text())['checkpoint_sha256'] + state['steps'].append(dict(label='reused verified matched comparison'+str(step),returncode=0,seconds=0));save();continue + call('matched comparison'+str(step),['python3',str(R/'recovery/matched_report.py'),'--candidate',name,'--control',a.control+'_ema'+str(step),'--label',a.label+' '+str(step)+' four-cutoff comparison','--cutoffs','0,1,2,3','--out',str(out),'--outcome',f'Declared comparison checkpoints {a.steps}. No transfer formula or automatic publication is selected by this controller.']) +state['status']='complete; research review required';save();print(json.dumps(state),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member4/training/recovery/check_compiled_restart.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member4/training/recovery/check_compiled_restart.py new file mode 100644 index 0000000000000000000000000000000000000000..ccf17541c33dd5a4151f23b78dbb2e020de205e2 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member4/training/recovery/check_compiled_restart.py @@ -0,0 +1,66 @@ +"""Separate ordinary compiled-run repeatability from a serialized restart effect.""" +import datetime,fcntl,hashlib,json,os,subprocess,time +from pathlib import Path +import numpy as np +import torch + +R=Path('/workspace/research');root=R/'recovery/compiled_restart_fixture';root.mkdir(exist_ok=False) +started=time.monotonic();lock=open(R/'.evaluation.lock','a');tick=time.monotonic() +fcntl.flock(lock,fcntl.LOCK_EX);wait=time.monotonic()-tick +env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1', + TORCHINDUCTOR_COMPILE_THREADS='2',MAX_JOBS='2',PYTHONPATH=str(R/'compiler_support'), + TRITON_CACHE_MANAGER='sibling_cache:SiblingFileCacheManager', + TRITON_CACHE_DIR='/tmp/timeseries-triton-cache',TORCHINDUCTOR_CACHE_DIR='/tmp/timeseries-inductor-cache') +initial=R/'runs/random_capacity_1024/ema096000.pt' +with initial.open('rb') as f:initial_hash=hashlib.file_digest(f,'sha256').hexdigest() +assert initial_hash=='d7cfcd72c3cb84aa69e447b76c4c3ab98c21b7c600a463f0b805f4b4300baf33' +commands=[] +def run(name,extra=(),suffix=''): + out=root/name + command=['python3',str(R/'recovery/train.py'),'--code-dir',str(R/'random_capacity'), + '--packed',str(R/'packed_sample'),'--source-weights-from',str(R/'packed_sample'), + '--out',str(out),'--initialize-from',str(initial),'--steps','6','--batch','48', + '--lr','.001','--seed','953','--loss-mode','paired','--compile-loss', + '--save-every','1000000',*extra] + tick=time.monotonic() + with (root/(name+suffix+'.log')).open('w') as f:code=subprocess.run(command,stdout=f,stderr=subprocess.STDOUT,env=env).returncode + commands.append(dict(name=name+suffix,command=command,returncode=code,seconds=time.monotonic()-tick)) + assert code==0,(name,code) + print(json.dumps(commands[-1]),flush=True) + +run('repeat_a');run('repeat_b');run('interrupted',['--halt-after','3']) +run('interrupted',['--resume',str(root/'interrupted/recovery.pt')],suffix='_resumed') +def compare(left,right): + a=torch.load(root/left/'recovery.pt',map_location='cpu',weights_only=False,mmap=True) + b=torch.load(root/right/'recovery.pt',map_location='cpu',weights_only=False,mmap=True) + groups={} + def descend(x,y,stats): + if isinstance(x,torch.Tensor): + assert isinstance(y,torch.Tensor) and x.shape==y.shape and x.dtype==y.dtype + stats['tensor_count']+=1;stats['tensor_elements']+=x.numel() + same=torch.equal(x,y);stats['different_tensors']+=int(not same) + if x.is_floating_point() and not same: + assert torch.isfinite(x).all() and torch.isfinite(y).all() + d=(x-y).double();stats['maximum_abs_difference']=max(stats['maximum_abs_difference'],float(d.abs().max())) + stats['sum_squared_difference']+=float(d.square().sum());stats['sum_squared_reference']+=float(x.double().square().sum()) + return same + if isinstance(x,np.ndarray):return np.array_equal(x,y,equal_nan=True) + if isinstance(x,dict):return set(x)==set(y) and all([descend(x[k],y[k],stats) for k in x]) + if isinstance(x,(tuple,list)):return len(x)==len(y) and all([descend(v,w,stats) for v,w in zip(x,y)]) + return x==y + for key in ['model','ema_state','optimizer','batch_rng_state','sampler_rng_state','sampler_rng_states','torch_rng_state','cuda_rng_state','prefetched_batch','parent_checkpoints']: + stats=dict(tensor_count=0,tensor_elements=0,different_tensors=0,maximum_abs_difference=0.,sum_squared_difference=0.,sum_squared_reference=0.) + stats['bitwise_equal']=bool(descend(a[key],b[key],stats));groups[key]=stats + assert a['step']==b['step']==6 + return groups +comparisons={'uninterrupted_repeat':compare('repeat_a','repeat_b'), + 'uninterrupted_vs_restart':compare('repeat_a','interrupted')} +for row in comparisons.values(): + for key in ['batch_rng_state','sampler_rng_state','sampler_rng_states','torch_rng_state','cuda_rng_state','prefetched_batch','parent_checkpoints']: + assert row[key]['bitwise_equal'],key +result=dict(utc=datetime.datetime.now(datetime.timezone.utc).isoformat(),initial_checkpoint_sha256=initial_hash, + fixture_seed=953,model_parameters=146477344,batch=48,optimizer_updates=18,steps_per_trajectory=6, + commands=commands,comparisons=comparisons,lock_wait_seconds=wait,seconds=time.monotonic()-started, + validation_data_read=False,fixture_weights_are_not_research_candidates=True, + note='Own mature scratch checkpoint and allowed training windows only. Two independent uninterrupted runs distinguish ordinary compiled numerical variation from an interrupted3+resumed3 trajectory. This is an engineering diagnostic, not a training recipe or model selection.') +(R/'compiled_restart_checks.json').write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member4/training/recovery/reclaim_completed_cache.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member4/training/recovery/reclaim_completed_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..3961c2a56a78474daf33305e890eec17d2ece2da --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member4/training/recovery/reclaim_completed_cache.py @@ -0,0 +1,16 @@ +"""Release dispensable raw-checkpoint page cache without changing any files.""" +import datetime,json,os,time +from pathlib import Path +R=Path('/workspace/research');start=time.monotonic();mem=Path('/sys/fs/cgroup/memory.current') +before=int(mem.read_text());files=[] +for name in ['random_capacity_512','long_seasonal','seasonal_dispersion','phase_joint','weekly_replication_control','weekly_replication_candidate']: + run=R/'runs'/name + # All are completed runs; EMA and full recovery checkpoints are untouched. + q=R/(name+'_queue.json');assert json.loads(q.read_text())['status']=='complete' + for p in sorted(run.glob('step*.pt')): + fd=os.open(p,os.O_RDONLY) + try:os.posix_fadvise(fd,0,0,os.POSIX_FADV_DONTNEED) + finally:os.close(fd) + files.append(dict(path=str(p),bytes=p.stat().st_size)) +result=dict(utc=datetime.datetime.now(datetime.timezone.utc).isoformat(),files=len(files),advised_bytes=sum(x['bytes'] for x in files),before_bytes=before,after_bytes=int(mem.read_text()),seconds=time.monotonic()-start,files_changed_or_deleted=0,notes='Read-only cache hints on completed raw checkpoints only; no EMA, recovery, corpus or active training state modified.') +(R/'completed_checkpoint_cache_receipt.json').write_text(json.dumps(result,indent=2));print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member4/training/recovery/relaunch_20261022b.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member4/training/recovery/relaunch_20261022b.py new file mode 100644 index 0000000000000000000000000000000000000000..d16fc19cbbb86dba2ff53b445e368b8bbd2ca218 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member4/training/recovery/relaunch_20261022b.py @@ -0,0 +1,105 @@ +"""Resume interrupted research jobs and preserve phase-specific recovery receipts.""" +import datetime +import json +import os +from pathlib import Path +import shutil +import subprocess +import time + +R = Path('/workspace/research') +TAG = 'recovery2' +env = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1') +receipt = {'recovery_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(), + 'remaining_research_seconds_at_operator_recovery': 152594, + 'jobs': {}, 'queues': {}} +children = {} + +def launch(name, command, phase=TAG): + log = R / f'{name}_{phase}.log' + assert not log.exists(), log + with log.open('w') as f: + child = subprocess.Popen(command, stdout=f, stderr=subprocess.STDOUT, env=env) + children[name] = child + return {'pid': child.pid, 'command': command, 'log': str(log), 'started_monotonic': time.monotonic()} + +def persist(): + path = R / f'{TAG}_launch_receipt.json' + tmp = path.with_suffix('.tmp') + tmp.write_text(json.dumps(receipt, indent=2)); os.replace(tmp, path) + +for name in ['wide_capacity_146m_recovery', 'wide_capacity_control_recovery', + 'long_memory_synth_recovery', 'recent_normalization_recovery', 'wide_graft', 'patch8']: + run = R / 'runs' / name + cfg = json.loads((run / 'config.json').read_text()) + shutil.copy2(run / 'config.json', run / f'config_before_{TAG}.json') + command = ['python3', str(R / 'recovery/train.py')] + for key in ['code_dir', 'packed', 'source_weights_from', 'out', 'initialize_from', + 'initialize_ema', 'start_step', 'steps', 'batch', 'lr', 'seed', 'context', + 'sample_context', 'save_every', 'stop_file', 'reset_at', 'reset_seed', 'loss_mode']: + if cfg.get(key) is not None: + command += ['--' + key.replace('_', '-'), str(cfg[key])] + if (run / 'recovery.pt').exists(): + command += ['--resume', str(run / 'recovery.pt')] + mode = 'complete optimizer/EMA/RNG/prefetched-batch resume' + else: + mode = 'restart saved own initialization; no complete checkpoint existed' + if cfg.get('compile_loss'): + command += ['--compile-loss'] + command = ['env', 'TORCHINDUCTOR_COMPILE_THREADS=2', 'MAX_JOBS=2', + 'PYTHONPATH=/workspace/research/compiler_support', + 'TRITON_CACHE_MANAGER=sibling_cache:SiblingFileCacheManager', + 'TRITON_CACHE_DIR=/tmp/timeseries-triton-cache', + 'TORCHINDUCTOR_CACHE_DIR=/tmp/timeseries-inductor-cache'] + command + assert not Path(cfg['stop_file']).exists(), cfg['stop_file'] + receipt['jobs'][name] = dict(launch(name, command), mode=mode) + persist() + +watch_specs = { + 'wide_capacity_146m_recovery': ('wide_capacity_inference', '24000,32000'), + 'wide_capacity_control_recovery': ('wide_capacity_inference', '24000,32000'), + 'long_memory_synth_recovery': ('partial_targets_inference', '12000'), + 'recent_normalization_recovery': ('recent_normalization_inference', '12000'), + 'wide_graft': ('wide_graft_inference', '4000,8000,12000,16000,24000,32000'), + 'patch8': ('full_paired_inference', '1000,3000,6000,12000'), + 'volatility_synth': ('partial_targets_inference', '3000,6000,12000'), + 'postloss': ('full_paired_inference', '1000,3000,6000,12000'), + 'paired_long_memory': ('full_paired_inference', '1000,3000,6000,12000'), +} +for name, (runtime, steps) in watch_specs.items(): + command = ['python3', str(R / 'watch_evaluate.py'), '--run', str(R / 'runs' / name), + '--evaluator', str(R / runtime / 'evaluate.py'), '--name', name, '--steps', steps] + launch(name + '_watch', command) + +queue_specs = {'volatility_synth': 'long_memory_synth_recovery', + 'postloss': 'recent_normalization_recovery', + 'paired_long_memory': 'wide_capacity_control_recovery'} +for name, dependency in queue_specs.items(): + old = json.loads((R / (name + '_queue.json')).read_text()) + shutil.copy2(R / (name + '_queue.json'), R / (name + '_queue_before_' + TAG + '.json')) + receipt['queues'][name] = dict(old, dependency=dependency, status='waiting', + wait_pids=[children[dependency].pid]) +persist() + +while True: + for name, job in receipt['jobs'].items(): + if 'returncode' not in job and children[name].poll() is not None: + job.update(returncode=children[name].returncode, + phase_seconds=time.monotonic() - job['started_monotonic']) + persist() + for name, queue in receipt['queues'].items(): + if queue['status'] == 'waiting' and children[queue['dependency']].poll() is not None: + if children[queue['dependency']].returncode != 0 or not all(Path(p).exists() for p in queue['required_checkpoints']): + queue['status'] = 'blocked_by_incomplete_dependency' + else: + receipt['jobs'][name] = launch(name, queue['command']) + queue.update(status='running', pid=children[name].pid, + started_utc=datetime.datetime.now(datetime.timezone.utc).isoformat()) + with (R / 'direct_v1/EXPERIMENTS.md').open('a') as f: + f.write(f'\n{name} started {queue["started_utc"]} after {queue["dependency"]} completed. Original predeclared settings and seed retained.\n') + (R / (name + '_queue.json')).write_text(json.dumps(queue, indent=2)) + persist() + if all(p.poll() is not None for n,p in children.items() if not n.endswith('_watch')) and all(q['status'] != 'waiting' for q in receipt['queues'].values()): + break + time.sleep(5) +persist() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member4/training/recovery/schedules.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member4/training/recovery/schedules.py new file mode 100644 index 0000000000000000000000000000000000000000..4c8378f374144b802d2cd5a98afd71efc1ba0a4c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member4/training/recovery/schedules.py @@ -0,0 +1,13 @@ +"""Explicit training-only learning-rate schedules; default arithmetic unchanged.""" +import math + + +def learning_rate(step, steps, peak, reset_at=-1, anneal_from_step=None, + anneal_from_lr=None, anneal_final_lr=None): + if anneal_from_step is not None: + assert steps > anneal_from_step + assert 0 < anneal_final_lr <= anneal_from_lr + progress=max(0.,min(1.,(step-anneal_from_step)/(steps-anneal_from_step))) + return anneal_final_lr+.5*(anneal_from_lr-anneal_final_lr)*(1+math.cos(math.pi*progress)) + warm_step=step-reset_at if reset_at>=0 and step>reset_at else step + return peak*min(1,warm_step/400)*(.2+.4*(1+math.cos(math.pi*step/steps))) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member4/training/recovery/seasonal_history_support.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member4/training/recovery/seasonal_history_support.py new file mode 100644 index 0000000000000000000000000000000000000000..84314b30b22a4a761447fc5ee1cffb9301e725b9 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member4/training/recovery/seasonal_history_support.py @@ -0,0 +1,23 @@ +"""Context-metadata diagnostic of potential 8-cycle support, with no targets read.""" +import importlib.util,json,time +from pathlib import Path +import h5py,numpy as np +R=Path('/workspace/research');started=time.monotonic() +spec=importlib.util.spec_from_file_location('support_model',R/'long_seasonal/model.py');m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m) +root=Path('/workspace/data/valid/input');index=json.loads((root/'index.json').read_text());rows=[] +for cfg in index['configs']: + with h5py.File(root/'cases'/(cfg['config_id']+'.h5'),'r') as f:lengths=np.asarray(f['context_length']) + h=cfg['prediction_length'];periods=m.periods_for_freq(cfg['freq']);row={k:cfg[k] for k in ['config_id','freq','term','domain']};row['periods']=periods;row['n_instances']=len(lengths) + for cap in [4096,16384]: + support=[];cycles=[] + for p in periods: + count=np.clip(1+(np.minimum(lengths,cap)[:,None]-p+np.arange(h)[None,:]%p)//p,0,16) + support.append(float(np.mean((count>=8)&(p>=2))));cycles.append(float(np.mean(np.where(p>=2,count,0)))) + row[str(cap)]={'phase_support_fraction':support,'mean_available_cycles':cycles} + row['support_gain_sum']=sum(row['16384']['phase_support_fraction'])-sum(row['4096']['phase_support_fraction']);rows.append(row) +changed=[r for r in rows if r['support_gain_sum']>0] +result=dict(kind='optimistic potential support before missing-value masks; not measured forecast improvement',input_metadata_only=True,validation_targets_read=False,optimizer_updates=0,configs=rows, + changed_configurations=len(changed),changed_domains=sorted(set(r['domain'] for r in changed)),seconds=time.monotonic()-started) +(R/'seasonal_history_support.json').write_text(json.dumps(result,indent=2)) +print(json.dumps({k:v for k,v in result.items() if k!='configs'})) +for r in sorted(changed,key=lambda x:x['support_gain_sum'],reverse=True)[:20]:print(json.dumps(r)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/model_manifest.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/model_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..ddcad3d7177eb8c5264f18780c1c7e67318e4947 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/model_manifest.json @@ -0,0 +1,391 @@ +{ + "name": "fresh-seasonal-48k", + "contract": "timeseries-forecast/v1", + "parameters": 146575680, + "pretrained_assets": [], + "sources_used": [ + "gifteval_pretrain/BEIJING_SUBWAY_30MIN", + "gifteval_pretrain/HZMETRO", + "gifteval_pretrain/LOS_LOOP", + "gifteval_pretrain/PEMS03", + "gifteval_pretrain/PEMS04", + "gifteval_pretrain/PEMS07", + "gifteval_pretrain/PEMS08", + "gifteval_pretrain/PEMS_BAY", + "gifteval_pretrain/Q-TRAFFIC", + "gifteval_pretrain/SHMETRO", + "gifteval_pretrain/alibaba_cluster_trace_2018", + "gifteval_pretrain/australian_electricity_demand", + "gifteval_pretrain/azure_vm_traces_2017", + "gifteval_pretrain/bdg-2_bear", + "gifteval_pretrain/bdg-2_fox", + "gifteval_pretrain/bdg-2_panther", + "gifteval_pretrain/bdg-2_rat", + "gifteval_pretrain/bitcoin_with_missing", + "gifteval_pretrain/borealis", + "gifteval_pretrain/borg_cluster_data_2011", + "gifteval_pretrain/buildings_900k", + "gifteval_pretrain/bull", + "gifteval_pretrain/cdc_fluview_ilinet", + "gifteval_pretrain/cdc_fluview_who_nrevss", + "gifteval_pretrain/china_air_quality", + "gifteval_pretrain/cif_2016_12", + "gifteval_pretrain/cif_2016_6", + "gifteval_pretrain/cmip6_2000", + "gifteval_pretrain/cmip6_2005", + "gifteval_pretrain/cmip6_2010", + "gifteval_pretrain/cockatoo", + "gifteval_pretrain/covid19_energy", + "gifteval_pretrain/covid_mobility", + "gifteval_pretrain/elecdemand", + "gifteval_pretrain/elf", + "gifteval_pretrain/era5_2010", + "gifteval_pretrain/era5_2011", + "gifteval_pretrain/era5_2012", + "gifteval_pretrain/era5_2013", + "gifteval_pretrain/era5_2014", + "gifteval_pretrain/era5_2015", + "gifteval_pretrain/era5_2016", + "gifteval_pretrain/era5_2017", + "gifteval_pretrain/era5_2018", + "gifteval_pretrain/extended_web_traffic_with_missing", + "gifteval_pretrain/favorita_sales", + "gifteval_pretrain/favorita_transactions", + "gifteval_pretrain/gfc12_load", + "gifteval_pretrain/gfc14_load", + "gifteval_pretrain/gfc17_load", + "gifteval_pretrain/godaddy", + "gifteval_pretrain/hog", + "gifteval_pretrain/ideal", + "gifteval_pretrain/kaggle_web_traffic_weekly", + "gifteval_pretrain/kdd2022", + "gifteval_pretrain/largest_2017", + "gifteval_pretrain/largest_2018", + "gifteval_pretrain/largest_2019", + "gifteval_pretrain/largest_2020", + "gifteval_pretrain/largest_2021", + "gifteval_pretrain/lcl", + "gifteval_pretrain/london_smart_meters_with_missing", + "gifteval_pretrain/m1_monthly", + "gifteval_pretrain/m1_quarterly", + "gifteval_pretrain/m1_yearly", + "gifteval_pretrain/m5", + "gifteval_pretrain/monash_m3_monthly", + "gifteval_pretrain/monash_m3_other", + "gifteval_pretrain/monash_m3_quarterly", + "gifteval_pretrain/nn5_daily_with_missing", + "gifteval_pretrain/nn5_weekly", + "gifteval_pretrain/oikolab_weather", + "gifteval_pretrain/pdb", + "gifteval_pretrain/project_tycho", + "gifteval_pretrain/residential_load_power", + "gifteval_pretrain/residential_pv_power", + "gifteval_pretrain/rideshare_with_missing", + "gifteval_pretrain/sceaux", + "gifteval_pretrain/smart", + "gifteval_pretrain/solar_power", + "gifteval_pretrain/spain", + "gifteval_pretrain/subseasonal", + "gifteval_pretrain/subseasonal_precip", + "gifteval_pretrain/sunspot_with_missing", + "gifteval_pretrain/taxi_30min", + "gifteval_pretrain/tourism_quarterly", + "gifteval_pretrain/tourism_yearly", + "gifteval_pretrain/traffic_hourly", + "gifteval_pretrain/traffic_weekly", + "gifteval_pretrain/uber_tlc_daily", + "gifteval_pretrain/uber_tlc_hourly", + "gifteval_pretrain/vehicle_trips_with_missing", + "gifteval_pretrain/wiki-rolling_nips", + "gifteval_pretrain/wind_farms_with_missing", + "gifteval_pretrain/wind_power", + "synthetic:both original and sign-reflected orientations of each sampled allowed or locally generated window; paired quantile loss, seed 307", + "synthetic:own Fourier/trend/intermittent generator with AR time constant log-uniform from 1 to 10000 steps and zero initial state; seed 307", + "synthetic:own direct_v1 Fourier seasons, damped trends, AR noise, changepoints and intermittent demand; seeds 307", + "synthetic:own random requested-horizon prefixes, half of rows retain the full horizon and half use a patch-rounded prefix between one-quarter and the full horizon; independent seed 300310" + ], + "weights_sha256": "4b309f0721378f97db815dd511b8b54711348270c48e9eae0103dba506f66708", + "config": { + "d": 1024, + "heads": 16, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true + }, + "training_lineage": [ + { + "checkpoint": "runs/random_capacity_long_seasonal/ema048000.pt", + "sha256": "4b309f0721378f97db815dd511b8b54711348270c48e9eae0103dba506f66708", + "step": 48000, + "seed": 307, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 48, + "lr": 0.0002, + "steps": 96000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": true, + "synthetic_ar_time_constants": [ + 1, + 10000 + ], + "requested_horizon_seed": 300310, + "normalization_overflow_fallback": true, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null, + "teacher_coefficient": null, + "compile_teacher": false, + "visibility_curriculum": false + }, + "model_config": { + "d": 1024, + "heads": 16, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true + }, + "parents": [ + "random_capacity_long_seasonal_initial.pt", + "random_capacity_1024_initial.pt" + ] + }, + { + "checkpoint": "random_capacity_long_seasonal_initial.pt", + "sha256": "f7e35a6341ffc6c1ce53cfd8934256dde937171f5002f1fc34b1fd169f1a15d6", + "step": 0, + "seed": 307, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 1024, + "heads": 16, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true + }, + "conversion": { + "method": "zero-initialize E107 seasonal query/head on own untrained E79random146M backbone", + "parent_sha256": "c9693619ca6277c26fef3b2bde37ff6796bec97b3af9f94588bbc5ddd329ec90", + "fixture_seed": 677, + "initial_function_bitwise_equal": true, + "optimizer_updates": 0 + }, + "parents": [ + "random_capacity_1024_initial.pt" + ] + }, + { + "checkpoint": "random_capacity_1024_initial.pt", + "sha256": "c9693619ca6277c26fef3b2bde37ff6796bec97b3af9f94588bbc5ddd329ec90", + "step": 0, + "seed": 307, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 1024, + "heads": 16, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "initialization": "random initialization in this workspace" + } + ], + "symmetric_averaging": true, + "seasonal_gate": { + "variance_ratio_threshold": 0.25, + "maximum_weight": 0.98, + "cycles_averaged": 4, + "template_mode": "aligned", + "amplitude_ratio_clip": [ + 0.5, + 2.0 + ], + "latest_cycle_minimum_coverage": 0.75, + "variance_noise_correction": "mean squared seasonal differences / 2" + }, + "continuity": { + "decay_steps": 24, + "variance_ratio_threshold": 0.5, + "maximum_weight": 0.95, + "lookback": 512, + "slope_median_differences": 8 + }, + "notes": "All training lineage originates from random initialization here, using only the declared corpus and locally generated series. Validation was used only for selection and diagnostics. Context transformations are fixed formulas; there is no inference-time fitting or parameter adaptation.", + "runtime_code_sha256": { + "infer.sh": "5fe66b4fe9a4787285d830cfd96975701e97286a75ba7c3687bd8891475edf68", + "continuity.py": "dbb08d2229ad80ad00f638b0b9f2f6ca13c663e0fd6730058e5fee8ff54545d5", + "predict.py": "9bde896945a2cd8f892e7eeb6328ed2dfda09293532f3a4a64d929c9943614ef", + "seasonal.py": "b946e63048196ab5ea8b249137d48c80d8510943caccd0f180e4fb86d9b24b37", + "ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "zero_mass.py": "f079d509009bcda409b80eb64467c869b838cfbab11b2bd4c660c2875b6642fe", + "model.py": "3eaa4aed0a1c62b80d94be6c3084b10a594e9fce17444eac17ca3f1b0b5c549e" + }, + "normalization_overflow_fallback": { + "trigger": "nonfinite float32 context mean or scale", + "arithmetic": "float64 context statistics on affected rows; original arithmetic on ordinary rows", + "inference_fitting": false + }, + "final_training_stage": { + "trainable_scope": "all parameters", + "sign_loss": "paired", + "learning_rate_multipliers": {} + }, + "trend_summary": { + "fixed_averaging_width": 128, + "matches_all_pretraining_context_widths": true, + "independent_of_batch_padding": true + }, + "zero_mass_projection": { + "threshold_in_context_standard_deviations": 0.4, + "nonnegative_context_required": true, + "minimum_exact_zeros": 4, + "minimum_zero_fraction": 0.1, + "context_cap": 4096 + }, + "recency_features": { + "query_projection_parameters": 65536, + "latest_vs_four_cycle_level": true, + "amplitude_ratio_clip": [ + 0.5, + 2.0 + ], + "minimum_observed_cycles": 3 + }, + "long_seasonal_features": { + "cycles": [ + 4, + 16 + ], + "each_cycle_centered": true, + "minimum_total_cycles": 8, + "minimum_recent_cycles": 2, + "query_features": [ + "centered16-minus4 phase mean", + "observed16-cycle fraction" + ], + "median_shift": "sum of two learned tanh gates times template differences", + "same_shift_all_quantiles": true, + "maximum_context": 4096, + "parameters_fixed_at_inference": true + }, + "confidence_features": { + "query_projection_parameters": 6144, + "backbone_frozen_during_projection_training": false, + "training_objective": "weighted quantile and median loss after averaging both sign orientations", + "statistics": [ + "mean absolute difference", + "root mean square difference" + ], + "lags": "one and the two frequency-derived periods", + "lookback": "512 for lag one; eight cycles for seasonal lags", + "minimum_valid_pairs": 8, + "insufficient_pair_defaults": [ + 1, + 1.4142135623730951 + ], + "statistic_clip": 10, + "transform": "log1p", + "stage_scope": "Projection trained jointly from random initialization; all training stages are recorded in training_lineage.training_settings." + }, + "partial_target_training": { + "available_horizon": "last finite training-label position rounded up to the patch boundary", + "decoder_future_key_mask": true, + "per_row_horizon_metadata": true, + "inference_uses_requested_horizon_only": true + }, + "training_provenance_code_sha256": { + "long_seasonal/check.py": "e55fe780892204889e210d1591ae3f0b964d72ec1916b9b5e768b938aba28fc1", + "long_seasonal/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "long_seasonal/launch.py": "68c56b8abde125eb8de866807f8deb946c30e4c52866bc0cafcab82198b58def", + "long_seasonal/long_features.py": "270d84ff1208085f65856e8c489998e6248af5c5ea1c3c47b5161f7d6b621b13", + "long_seasonal/model.py": "3eaa4aed0a1c62b80d94be6c3084b10a594e9fce17444eac17ca3f1b0b5c549e", + "long_seasonal/transfer.py": "301df5a793988edbe50b3384c5777d8679161142943578bc7723a552ed4f3d04", + "random_capacity/check.py": "c5090883cc4e983a41041a319a5260f4d1d5c88bb3133b0651ea5e077845fb8d", + "random_capacity/check_anneal_schedule.py": "e7a431afbd93b3a542786781a4065d5802743965dadc42759cb1d3d50c3adbd5", + "random_capacity/data.py": "d84032a33937a465acfc9e1b97004ca8d9db221509bb2710e74500703ade4344", + "random_capacity/initialize.py": "2a3326d8f2340e9f3fb9ccdea4a69c94c25f9cb969b883ec5e89bb7a53e1e317", + "random_capacity/launch_anneal.py": "3e3b8784781519f77fffac9f683eea847d14df92bf829c2022e520a6074fbb25", + "random_capacity/launch_legacy.py": "d9bd7980146ccb62c292907aa50713e37d0be2dfeac829cf075c140747e9041a", + "random_capacity/launch_lower_rate.py": "44ce2d26ce1adc76023893e82734c2634c840541e7f88f9cef5b51e503a1ef97", + "random_capacity/model.py": "44eeb23c037e91b8f67e432615ce46540a7ac4242919785f9c4218de23121499", + "random_capacity/queue_recovery3.py": "72b59dff33a62ccb584cece127fb3e0d1631a893ab3d5ffb791a3398f9d902f2", + "random_capacity/restart_corrected.py": "1f020aa304f1ce92d452ed884d0dbe5a0607f2d2c2fb6537f9e0bcf42412fde9", + "random_capacity_long_seasonal/check.py": "4d96430799d842212d85af5e4253ad1bd74845685ba00837d44d7d1b95628ba8", + "random_capacity_long_seasonal/data.py": "d84032a33937a465acfc9e1b97004ca8d9db221509bb2710e74500703ade4344", + "random_capacity_long_seasonal/launch.py": "4c3499ca6be7ac43db5648f92466a0829b79c665f67704613c7447cf6d2e2a2f", + "random_capacity_long_seasonal/model.py": "3eaa4aed0a1c62b80d94be6c3084b10a594e9fce17444eac17ca3f1b0b5c549e", + "recovery/accumulation.py": "a0b29cd6fb097ded4333a9d4de9078b3da67090e6c719feb1006f187c632515b", + "recovery/brief.py": "a2b4187f051c99b94116cf13259b5044940e2317938a8f96ae3f4babec820f69", + "recovery/brief_before_E145.py": "dcb51a5397796bb0d67bfb57ced852bc577f493c97f54bc9a2b4a655ae1db6e9", + "recovery/capacity_curves.py": "9901b6714595b7c65b333bed63a3cfc0ff3dea5a5310790cf127fedce89dbb13", + "recovery/check_accumulation_cpu.py": "3448478f534e3625758077dd54504d0bda241e00d22945caa7e26c62b3a002a4", + "recovery/check_accumulation_gpu.py": "0c932eb8698adc5bfee4cf0a280e399c1403a92912c33870a7dfad13ea7d1447", + "recovery/check_accumulation_recovery.py": "ed3267d5e1f291c77f9d20dae132d432fe7b9cb42a2afc3f02381bf03a7163f4", + "recovery/check_compiled_restart.py": "0b16cb7503f23ee3735b096900c6e377bc3c444df94636696a6de1551617ea20", + "recovery/distillation_error_dependence.py": "882a09dc140fd586679e408cf1d3dffad6d748d12bef7926e0d7a95cebc6eabd", + "recovery/exposure_audit.py": "54c194a626b8876ece84686b39b22360155c9fada7248a393ca9b7d6ee38002b", + "recovery/launch_matched_cutoffs.py": "7d5b9b569df284c143bb4fe50033ed6be21ff1b54cb4405723b2ebcdefe6e562", + "recovery/matched_report.py": "f78ad10f984a6a6fcf3160eacf17b8b26dbc32e8f1b94fecea924cd314df4520", + "recovery/median_error_structure.py": "f6e126496eba2e0aa1fce1efeac7e926f0fbc28005ab81c0f1c9cf73ecd93782", + "recovery/pack_composition.py": "66c198e44b55fc4dce50dec505a0127eb9d97390e04d0f97c271ace11ad0f49f", + "recovery/pack_exposure.py": "c3e6f8d70de1d6e09389e206a0d0ef6fda0dc15466028a8453ca0ca6efbfcde5", + "recovery/quantile_coverage.py": "7a4057d1aa38c5e7de0ca601db0003a8fd3a9a2e6123b2fdb81fa8aedbc34787", + "recovery/queued_train_before_recovery4.py": "45dc3f68ebfee8d78cff60fc57fc5a9575ae0852115924a0f897cc895caad3cc", + "recovery/reclaim_completed_cache.py": "d0a23e5a73b362f03a3be0d9fcc8dd5292d17da0489484a9c52af84bd05d9638", + "recovery/record_learning_diagnostic.py": "8307e94997105f7dbcc6c77fd43e44a9bfefdebb9facb4c8d66c37b160e20cce", + "recovery/refresh_journal.py": "6ccbbbf7494f3b310f2e4d47e572487b62494ae52ef6598de93ce8ae28c8a7a5", + "recovery/relaunch_20261022b.py": "f90ddd77928a793c8e151ba74cfa9cc84c8aefad0c0d943a833c74bc07b79313", + "recovery/relaunch_20261023.py": "a4c40c5674b0d05cfe9bb1fffe907f02dec16c53cbddb8b86efbba1b96649097", + "recovery/relaunch_storage_20261023.py": "28d43c9fc625667a8132baf16e7f17103649ea32efa1d2bc85756e32f629b843", + "recovery/schedules.py": "7748fd6b2bbbe64037472faf7e6583d03cf339138d2f3c07b1bac9e65bf2d4f5", + "recovery/seasonal_history_support.py": "fe2da1a695715c3add9472f0bfebc946783b179b1a8415f85565a937885f7076", + "recovery/snapshot.py": "46a0e3f178ce8c0d7c0eb2a45cc9833cbe8a69549b1d528263a3ec180978be7e", + "recovery/synthetic_window_audit.py": "912e38fd094f35fb528a77388d8076600207b369bb3b2c2133a24c3c485019a1", + "recovery/train.py": "7c452f609bb48e254c09ae9932f09fc836b51e004d322445fadd272063341a8b", + "recovery/watch_matched_cutoffs.py": "177dbe6d8b5186dd3ce1c4b261a55cd5cfb44f6ed2922ef64b489deb2117fa6b" + } +} diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/long_seasonal/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/long_seasonal/check.py new file mode 100644 index 0000000000000000000000000000000000000000..beba62576fae73576eef907b81c674e96622670d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/long_seasonal/check.py @@ -0,0 +1,145 @@ +"""Check exact initialization, fixed feature arithmetic and allowed-data gradients.""" +import argparse +import hashlib +import importlib.util +import json +import sys +import time +from pathlib import Path + +import numpy as np +import torch + +R = Path('/workspace/research') +sys.path.insert(0, str(R / 'long_seasonal')) +from model import DirectForecaster, centered_seasonal_difference, loss_fn +from data import Sampler + +ap = argparse.ArgumentParser() +ap.add_argument('--gpu', action='store_true') +a = ap.parse_args() +torch.set_num_threads(2) +torch.manual_seed(503) +started = time.monotonic() +spec = importlib.util.spec_from_file_location('long_control_model', R / 'overflow_control/model.py') +control_code = importlib.util.module_from_spec(spec) +spec.loader.exec_module(control_code) +parent_path = R / 'horizon_delta12k.pt' +parent = torch.load(parent_path, map_location='cpu', weights_only=False) +config = dict(parent['config'], long_seasonal_features=True) +candidate = DirectForecaster(**config) +missing, unexpected = candidate.load_state_dict(parent['model'], strict=False) +assert set(missing) == {'long_query.weight', 'long_head.weight', 'long_head.bias'} +assert not unexpected +assert all(torch.count_nonzero(candidate.state_dict()[key]) == 0 for key in missing) +control = control_code.DirectForecaster(**parent['config']) +control.load_state_dict(parent['model']) +assert all(torch.equal(value, candidate.state_dict()[key]) for key, value in parent['model'].items()) + +if a.gpu: + import fcntl + lock = open(R / '.evaluation.lock', 'a') + fcntl.flock(lock, fcntl.LOCK_EX) + device = 'cuda' + torch.backends.cuda.matmul.allow_tf32 = False + candidate = candidate.cuda() + control = control.cuda() + rng = np.random.default_rng(509) + x = torch.tensor(rng.normal(size=(8, 512)).astype(np.float32), device=device) + x[0, :23] = float('nan') + x[1] = 0 + p = torch.tensor([[24,168],[7,365],[12,1],[52,1],[4,1],[1,1],[96,672],[2,14]], device=device) + with torch.inference_mode(), torch.autocast('cuda', dtype=torch.bfloat16): + expected = control(x, p, 128) + actual = candidate(x, p, 128) + assert all(torch.equal(v, w) for v, w in zip(expected, actual)) + del control, expected, actual, x, p + torch.cuda.empty_cache() + torch.cuda.reset_peak_memory_stats() + sampler = Sampler(R / 'packed_sample', seed=509, source_weights_from=R / 'packed_sample') + arrays = sampler.sample(64, 4096, 1024) + tensors = [torch.from_numpy(v).cuda() for v in arrays] + placeholders = [torch.zeros_like(v) for v in candidate.parameters() for _ in range(3)] + with torch.autocast('cuda', dtype=torch.bfloat16): + loss = loss_fn(candidate, *tensors, paired=True) + loss.backward() + assert torch.isfinite(loss) + assert all(v.grad is None or torch.isfinite(v.grad).all() for v in candidate.parameters()) + gradients = {key: float(dict(candidate.named_parameters())[key].grad.norm()) for key in missing} + assert gradients['long_head.weight'] > 0 and gradients['long_query.weight'] > 0 + result = dict(seed=509, gpu_initial_function_bitwise_equal=True, + max_shape=[64,4096,1024], loss=float(loss.detach()), added_gradient_norms=gradients, + reserved_mib=torch.cuda.max_memory_reserved()/2**20, + allocated_mib=torch.cuda.max_memory_allocated()/2**20, + includes_ema_and_adam_placeholders=True, seconds=time.monotonic()-started, + optimizer_updates=0, validation_data_read=False) + (R / 'long_seasonal_gpu_checks.json').write_text(json.dumps(result, indent=2)) + print(json.dumps(result)) + raise SystemExit() + +rng = np.random.default_rng(503) +z = rng.normal(size=(4, 96)).astype(np.float32) +valid = rng.random(z.shape) > .12 +z[~valid] = 0 +periods = np.array([[4,7],[2,3],[12,1],[24,168]], dtype=np.int64) +delta, extra = centered_seasonal_difference(torch.from_numpy(z), torch.from_numpy(valid), + torch.from_numpy(periods), 23) +expected = np.zeros((4,23,2), np.float32) +support = np.zeros_like(expected) +for row in range(4): + for j in range(2): + period = int(periods[row,j]) + for t in range(23): + observations, recent = [], [] + for cycle in range(16): + end = max(0, 96-cycle*period) + start = max(0, 96-(cycle+1)*period) + index = 96-period+t%period-cycle*period + if index < 0 or not valid[row,index]: + continue + mean = z[row,start:end][valid[row,start:end]].mean(dtype=np.float64) + value = float(z[row,index])-mean + observations.append(value) + if cycle < 4: + recent.append(value) + if period>=2 and len(observations)>=8 and len(recent)>=2: + expected[row,t,j] = np.mean(observations)-np.mean(recent) + support[row,t,j] = len(observations)/16 +assert np.max(np.abs(delta.numpy()-expected)) < 1e-6 +assert np.array_equal(extra.numpy()[:,:,[1,3]], support) +# Adding a different constant to each complete cycle leaves centered templates unchanged. +z0 = torch.tensor(rng.normal(size=(1,64)).astype(np.float32)) +offsets = torch.tensor(rng.normal(size=(1,16,1)).astype(np.float32)) +z1 = (z0.view(1,16,4)+offsets).view(1,64) +p = torch.tensor([[4,4]]) +ones = torch.ones_like(z0,dtype=torch.bool) +v0 = centered_seasonal_difference(z0,ones,p,16)[0] +v1 = centered_seasonal_difference(z1,ones,p,16)[0] +assert torch.max(torch.abs(v0-v1)) < 1e-6 +for c,h in [(32,6),(96,23),(512,128)]: + ctx = torch.tensor(rng.normal(size=(4,c)).astype(np.float32)) + ctx[0,:c//3] = float('nan') + ctx[1] = 0 + ctx[2] = float('nan') + with torch.inference_mode(): + expected = control(ctx,torch.from_numpy(periods),h) + actual = candidate(ctx,torch.from_numpy(periods),h) + assert all(torch.equal(v,w) for v,w in zip(expected,actual)) +assert (R/'long_seasonal/data.py').read_bytes()==(R/'overflow_control/data.py').read_bytes() +out = R / 'long_seasonal_initial.pt' +assert not out.exists(), 'Do not overwrite an existing declared initial checkpoint' +checkpoint = dict(model=candidate.state_dict(), config=config, step=0, + args=dict(packed=str(R/'packed_sample'), seed=503), + parent_checkpoints=[str(parent_path)], + conversion=dict(method='zero-initialized sixteen-cycle centered seasonal query/head additions', + parent_sha256=hashlib.sha256(parent_path.read_bytes()).hexdigest(), + initial_function_bitwise_equal=True)) +torch.save(checkpoint,out) +result = dict(seed=503, independent_feature_arithmetic=True, centered_cycle_offset_invariance=True, + initial_function_bitwise_equal=True, inherited_weights_bitwise_equal=True, + sampler_byte_identical=True, added_parameters=sum(candidate.state_dict()[k].numel() for k in missing), + total_parameters=sum(v.numel() for v in candidate.parameters()), + checkpoint_sha256=hashlib.sha256(out.read_bytes()).hexdigest(), + seconds=time.monotonic()-started, optimizer_updates=0, validation_data_read=False) +(R/'long_seasonal_checks.json').write_text(json.dumps(result,indent=2)) +print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/long_seasonal/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/long_seasonal/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/long_seasonal/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/long_seasonal/launch.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/long_seasonal/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..d7fd732aae9def625f17a4d15dd2dbe3f4cd9317 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/long_seasonal/launch.py @@ -0,0 +1,31 @@ +"""Queue the audited learned sixteen-cycle summary after nested-volume training.""" +def main(): + import json + import os + import subprocess + from pathlib import Path + R=Path('/workspace/research') + checks=json.loads((R/'long_seasonal_checks.json').read_text()) + assert checks['initial_function_bitwise_equal'] and checks['inherited_weights_bitwise_equal'] + assert checks['independent_feature_arithmetic'] and checks['sampler_byte_identical'] + gpu=json.loads((R/'long_seasonal_gpu_checks.json').read_text()) + assert gpu['gpu_initial_function_bitwise_equal'] and gpu['reserved_mib']<10000 + env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1') + command=['python3',str(R/'recovery/train.py'),'--code-dir',str(R/'long_seasonal'), + '--packed',str(R/'packed_sample'),'--source-weights-from',str(R/'packed_sample'), + '--out',str(R/'runs/long_seasonal'),'--initialize-from',str(R/'long_seasonal_initial.pt'), + '--steps','12000','--batch','64','--lr','.00002','--seed','197','--loss-mode','paired', + '--stop-file',str(R/'long_seasonal.stop')] + with (R/'long_seasonal_queue.log').open('w') as qlog,(R/'long_seasonal_watch.log').open('w') as wlog: + queued=subprocess.Popen(['python3',str(R/'queued_train.py'),'--label','E107 learned sixteen-cycle summary seed197', + '--log',str(R/'long_seasonal_train.log'),'--receipt',str(R/'long_seasonal_queue.json'), + '--wait-pid','13470','--require-checkpoint',str(R/'runs/stratified_volume/recovery.pt'), + '--',*command],stdout=qlog,stderr=subprocess.STDOUT,env=env) + watch=subprocess.Popen(['python3',str(R/'watch_evaluate.py'),'--run',str(R/'runs/long_seasonal'), + '--evaluator',str(R/'long_seasonal_inference/evaluate.py'),'--name','long_seasonal', + '--expected-packed',str(R/'packed_sample'),'--steps','1000,3000,6000,12000'],stdout=wlog,stderr=subprocess.STDOUT,env=env) + print({'queue_pid':queued.pid,'watch_pid':watch.pid},flush=True) + result=queued.wait() + if result:watch.terminate() + watch.wait();raise SystemExit(result) +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/long_seasonal/long_features.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/long_seasonal/long_features.py new file mode 100644 index 0000000000000000000000000000000000000000..efc6e3ba327c6016d844148fcfcc29ac63863f23 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/long_seasonal/long_features.py @@ -0,0 +1,37 @@ +"""Fixed within-context phase summaries; no estimated or adapted parameters.""" +import torch +from torch.nn import functional as F + + +def centered_seasonal_difference(z, valid, periods, horizon): + b, c = z.shape + time = torch.arange(horizon, device=z.device)[None, :] + sums = F.pad((z * valid).cumsum(-1), (1, 0)) + counts = F.pad(valid.float().cumsum(-1), (1, 0)) + deltas, extras = [], [] + for j in range(2): + period = periods[:, j:j+1].clamp(min=1) + anchor = c - period + time % period + centered, masks = [], [] + for cycle in range(16): + end = (c - cycle * period).clamp(min=0, max=c) + start = (c - (cycle + 1) * period).clamp(min=0, max=c) + count = counts.gather(1, end) - counts.gather(1, start) + mean = (sums.gather(1, end) - sums.gather(1, start)) / count.clamp(min=1) + index = anchor - cycle * period + safe = index.clamp(min=0, max=c-1) + present = (index >= 0) & valid.gather(1, safe) + centered.append(z.gather(1, safe) - mean) + masks.append(present) + values = torch.stack(centered) + seen = torch.stack(masks) + n4 = seen[:4].sum(0) + n16 = seen.sum(0) + mean4 = (values[:4] * seen[:4]).sum(0) / n4.clamp(min=1) + mean16 = (values * seen).sum(0) / n16.clamp(min=1) + active = (period >= 2) & (n4 >= 2) & (n16 >= 8) + delta = torch.where(active, mean16 - mean4, 0.) + support = torch.where(active, n16.float() / 16, 0.) + deltas.append(delta) + extras.extend([delta, support]) + return torch.stack(deltas, -1), torch.stack(extras, -1) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/long_seasonal/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/long_seasonal/model.py new file mode 100644 index 0000000000000000000000000000000000000000..298ee3b840cbc8b7da585ee5e47a3822d06717b0 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/long_seasonal/model.py @@ -0,0 +1,260 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + + +def centered_seasonal_difference(z, valid, periods, horizon): + b, c = z.shape + time = torch.arange(horizon, device=z.device)[None, :] + sums = F.pad((z * valid).cumsum(-1), (1, 0)) + counts = F.pad(valid.float().cumsum(-1), (1, 0)) + deltas, extras = [], [] + for j in range(2): + period = periods[:, j:j+1].clamp(min=1) + anchor = c - period + time % period + centered, masks = [], [] + for cycle in range(16): + end = (c - cycle * period).clamp(min=0, max=c) + start = (c - (cycle + 1) * period).clamp(min=0, max=c) + count = counts.gather(1, end) - counts.gather(1, start) + mean = (sums.gather(1, end) - sums.gather(1, start)) / count.clamp(min=1) + index = anchor - cycle * period + safe = index.clamp(min=0, max=c-1) + present = (index >= 0) & valid.gather(1, safe) + centered.append(z.gather(1, safe) - mean) + masks.append(present) + values = torch.stack(centered) + seen = torch.stack(masks) + n4 = seen[:4].sum(0) + n16 = seen.sum(0) + mean4 = (values[:4] * seen[:4]).sum(0) / n4.clamp(min=1) + mean16 = (values * seen).sum(0) / n16.clamp(min=1) + active = (period >= 2) & (n4 >= 2) & (n16 >= 8) + delta = torch.where(active, mean16 - mean4, 0.) + support = torch.where(active, n16.float() / 16, 0.) + deltas.append(delta) + extras.extend([delta, support]) + return torch.stack(deltas, -1), torch.stack(extras, -1) + + + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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,long_seasonal_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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,long_seasonal_features=long_seasonal_features) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + self.long_query=nn.Linear(patch*4,d,bias=False) if long_seasonal_features else None + self.long_head=nn.Linear(d,patch*2) if long_seasonal_features else None + if long_seasonal_features: + nn.init.zeros_(self.long_query.weight) + nn.init.zeros_(self.long_head.weight);nn.init.zeros_(self.long_head.bias) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + if self.long_query is not None:long_delta,long_extra=centered_seasonal_difference(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + hidden=self.norm(q) + out=self.head(hidden).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + if self.long_head is not None: + gates=self.long_head(hidden).view(b,h,2).float().tanh() + median=median+(gates*long_delta).sum(-1) + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/long_seasonal/transfer.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/long_seasonal/transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..c20a4df852f5b150e634ae2c06510d01c7ea18b3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/long_seasonal/transfer.py @@ -0,0 +1,73 @@ +"""Apply one matched feature-learning difference with explicit zero-extension semantics.""" +import argparse +import hashlib +import importlib.util +import json +import sys +import time +from pathlib import Path + +import numpy as np +import torch + +R = Path('/workspace/research') +parser = argparse.ArgumentParser() +for key in ['base','candidate','control','out']: + parser.add_argument('--'+key,required=True) +args = parser.parse_args() +torch.set_num_threads(2) +torch.manual_seed(571) +started = time.monotonic() +paths = [Path(args.base),Path(args.candidate),Path(args.control)] +base,candidate,control = [torch.load(p,map_location='cpu',weights_only=False) for p in paths] +extra = {'long_query.weight','long_head.weight','long_head.bias'} +assert set(base['model'])==set(control['model']) +assert set(candidate['model'])==set(base['model'])|extra +config = dict(candidate['config']) +assert config.pop('long_seasonal_features') is True +assert config==base['config']==control['config'] +sys.path.insert(0,str(R/'long_seasonal')) +from model import DirectForecaster +extended = DirectForecaster(**candidate['config']) +missing,unexpected = extended.load_state_dict(base['model'],strict=False) +assert set(missing)==extra and not unexpected +assert all(torch.count_nonzero(extended.state_dict()[k])==0 for k in extra) +spec = importlib.util.spec_from_file_location('transfer_original_model',R/'overflow_control/model.py') +code = importlib.util.module_from_spec(spec) +spec.loader.exec_module(code) +original = code.DirectForecaster(**base['config']) +original.load_state_dict(base['model']) +rng = np.random.default_rng(571) +periods = torch.tensor([[24,168],[7,365],[52,1],[1,1]]) +for c,h in [(32,6),(512,128)]: + ctx = torch.tensor(rng.normal(size=(4,c)).astype(np.float32)) + ctx[0,:c//3] = float('nan') + ctx[1] = 0 + ctx[2] = float('nan') + with torch.inference_mode(): + a = original(ctx,periods,h) + b = extended(ctx,periods,h) + assert all(torch.equal(v,w) for v,w in zip(a,b)) +weights = {k:v.clone() for k,v in extended.state_dict().items()} +for k in weights: + if k in extra: + weights[k].copy_(candidate['model'][k]) + else: + assert weights[k].shape==candidate['model'][k].shape==control['model'][k].shape + weights[k].add_(candidate['model'][k]-control['model'][k]) +assert all(torch.isfinite(v).all() for v in weights.values()) +out = Path(args.out) +assert not out.exists(),'Refuse to overwrite a declared fixed candidate' +conversion = dict(method='matched training delta after zero extension of new seasonal query/head parameters', + formula='extend_zero(base) + candidate - extend_zero(control)',coefficient=1.0, + new_parameters_from_candidate=sorted(extra), + parent_hashes={str(p):hashlib.sha256(p.read_bytes()).hexdigest() for p in paths}, + base_extension_forward_bitwise_equal=True,check_seed=571, + seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False) +checkpoint = dict(model=weights,config=candidate['config'],step=0,args={'packed':base['args']['packed']}, + parent_checkpoints=[str(p) for p in paths],conversion=conversion) +torch.save(checkpoint,out) +result = dict(conversion,checkpoint_sha256=hashlib.sha256(out.read_bytes()).hexdigest(), + parameters=sum(v.numel() for v in weights.values())) +out.with_suffix('.json').write_text(json.dumps(result,indent=2)) +print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity/check.py new file mode 100644 index 0000000000000000000000000000000000000000..3b6d1440f762d7e57f47bb267df05b5dd786c223 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity/check.py @@ -0,0 +1,49 @@ +"""Measure maximum training memory and verify compiled paired-loss gradients.""" +import argparse +import fcntl +import json +from pathlib import Path +import time +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +ap=argparse.ArgumentParser();ap.add_argument('--width',type=int,required=True);a=ap.parse_args() +R=Path('/workspace/research');lock=open(R/'.evaluation.lock','a');fcntl.flock(lock,fcntl.LOCK_EX) +torch.set_num_threads(1);torch.manual_seed(313);torch.backends.cuda.matmul.allow_tf32=True +started=time.monotonic();ck=torch.load(R/f'random_capacity_{a.width}_initial.pt',map_location='cpu',weights_only=False) +m=DirectForecaster(**ck['config']).cuda();m.load_state_dict(ck['model']) +sampler=Sampler(R/'packed_sample',seed=313,source_weights_from=R/'packed_sample') +arrays=sampler.sample(48,4096,1024);x,y,p=[torch.from_numpy(v).cuda() for v in arrays] +# Placeholders account for the EMA and two Adam moments without taking any update. +state_placeholders=[torch.empty_like(v) for v in m.parameters() for _ in range(3)] +with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(m,x,y,p,paired=True) +loss.backward();torch.cuda.synchronize() +assert torch.isfinite(loss) and all(v.grad is not None and torch.isfinite(v.grad).all() for v in m.parameters()) +memory={'batch':48,'signed_rows':96,'context':4096,'horizon':1024,'loss':float(loss.detach()), + 'peak_allocated_mib':torch.cuda.max_memory_allocated()/2**20, + 'peak_reserved_mib':torch.cuda.max_memory_reserved()/2**20} +del state_placeholders,loss,x,y,p,arrays +m.zero_grad(set_to_none=True);torch.cuda.empty_cache() +x,y,p=[torch.from_numpy(v).cuda() for v in sampler.sample(8,512,128)] +def step(fn): + m.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=fn(m,x,y,p,paired=True) + loss.backward() + return float(loss.detach()) +reference=step(loss_fn);grads={n:v.grad.detach().clone() for n,v in m.named_parameters()} +compile_started=time.monotonic();actual=step(torch.compile(loss_fn,fullgraph=True,dynamic=False));torch.cuda.synchronize() +dot=norma=normb=0.;maximum=0. +for name,v in m.named_parameters(): + left,right=grads[name],v.grad + assert torch.isfinite(right).all() + dot+=float((left*right).sum());norma+=float(left.square().sum());normb+=float(right.square().sum()) + maximum=max(maximum,float((left-right).abs().max())) +cosine=dot/(norma*normb)**.5 +assert abs(reference-actual)<.003*max(reference,.1) and cosine>.995 +result={'normalization_overflow_fallback':True,'width':a.width,'initialization_seed':307,'fixture_seed':313,'optimizer_updates':0, + 'maximum_shape_memory':memory,'eager_loss':reference,'compiled_loss':actual, + 'gradient_cosine':cosine,'max_gradient_difference':maximum, + 'compile_comparison_seconds':time.monotonic()-compile_started, + 'total_seconds':time.monotonic()-started,'source':'allowed packed_sample and own synthetic generator only'} +(R/f'random_capacity_{a.width}_checks.json').write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity/check_anneal_schedule.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity/check_anneal_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..6c52591b8672097d4dd3466bc7850131929588ce --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity/check_anneal_schedule.py @@ -0,0 +1,24 @@ +"""Check the new cooldown and unchanged default learning-rate arithmetic.""" +import json +import math +import sys +import time +from pathlib import Path +R=Path('/workspace/research');sys.path.insert(0,str(R/'recovery')) +from schedules import learning_rate +started=time.monotonic() +checked=0 +for total,peak,reset in [(12000,2e-5,-1),(96000,2e-4,-1),(32000,3e-5,8000)]: + for step in range(1,total+1): + warm=step-reset if reset>=0 and step>reset else step + original=peak*min(1,warm/400)*(.2+.4*(1+math.cos(math.pi*step/total))) + assert learning_rate(step,total,peak,reset)==original + checked+=1 +start=learning_rate(24000,96000,2e-4) +values=[learning_rate(i,36000,2e-4,-1,24000,start,1e-5) for i in range(24000,36001)] +assert values[0]==start and values[-1]==1e-5 +assert all(08 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity/initialize.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity/initialize.py new file mode 100644 index 0000000000000000000000000000000000000000..ff8f0f3e2d3f9dfa2e8378e90c31bab5ecf4d22e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity/initialize.py @@ -0,0 +1,26 @@ +"""Create fresh local random initializations for the matched capacity comparison.""" +import hashlib +import json +from pathlib import Path +import time +import torch +from model import DirectForecaster + +R=Path('/workspace/research');torch.set_num_threads(2) +receipts=[] +for d,heads in [(512,8),(1024,16)]: + start=time.monotonic();torch.manual_seed(307) + model=DirectForecaster(d=d,heads=heads,enc_layers=6,dec_layers=4,patch=16, + recency_features=True,confidence_features=True,partial_target_lengths=True) + path=R/f'random_capacity_{d}_initial.pt' + assert not path.exists(),path + ck={'model':model.state_dict(),'config':model.config,'step':0, + 'args':{'packed':str(R/'packed_sample'),'seed':307}, + 'initialization':{'method':'torch modules initialized locally, zero output weights with fixed seasonal-mixture and interval biases', + 'seed':307,'parent_weights':[]}, + 'parent_checkpoints':[],'lr_multipliers':{}} + torch.save(ck,path) + receipts.append({'path':str(path),'sha256':hashlib.sha256(path.read_bytes()).hexdigest(), + 'parameters':sum(p.numel() for p in model.parameters()),'seed':307, + 'cpu_seconds':time.monotonic()-start,'optimizer_updates':0}) +(R/'random_capacity_initialization.json').write_text(json.dumps(receipts,indent=2));print(json.dumps(receipts)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity/launch_anneal.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity/launch_anneal.py new file mode 100644 index 0000000000000000000000000000000000000000..b192187a1714510e172dd17378cc6b85bff26744 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity/launch_anneal.py @@ -0,0 +1,38 @@ +"""Branch one fresh37M run for a matched training-only cooldown comparison.""" +def main(): + import json + import os + import subprocess + from pathlib import Path + R=Path('/workspace/research') + snapshot=json.loads((R/'random_capacity_512_recovery024000.json').read_text());assert snapshot['step']==24000 + check=json.loads((R/'random_capacity_anneal_checks.json').read_text());assert check['default_steps_bitwise_equal']==140000 + env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1',TORCHINDUCTOR_COMPILE_THREADS='2',MAX_JOBS='2', + PYTHONPATH=str(R/'compiler_support'),TRITON_CACHE_MANAGER='sibling_cache:SiblingFileCacheManager', + TRITON_CACHE_DIR='/tmp/timeseries-triton-cache',TORCHINDUCTOR_CACHE_DIR='/tmp/timeseries-inductor-cache') + command=['python3',str(R/'recovery/train.py'),'--code-dir',str(R/'random_capacity'), + '--packed',str(R/'packed_sample'),'--source-weights-from',str(R/'packed_sample'), + '--out',str(R/'runs/random_capacity_512_anneal'),'--initialize-from',str(R/'random_capacity_512_initial.pt'), + '--resume',str(R/'random_capacity_512_recovery024000.pt'),'--steps','36000','--batch','48', + '--lr','.0002','--seed','307','--loss-mode','paired','--compile-loss', + '--anneal-from-step','24000','--anneal-from-lr',str(check['join_lr']),'--anneal-final-lr','.00001', + '--stop-file',str(R/'random_capacity_512_anneal.stop')] + with (R/'random_capacity_512_anneal_queue.log').open('w') as qlog: + queued=subprocess.Popen(['python3',str(R/'queued_train.py'),'--label','E99 fresh37M early cooldown', + '--log',str(R/'random_capacity_512_anneal_train.log'), + '--receipt',str(R/'random_capacity_512_anneal_queue.json'), + '--wait-pid','5689','--require-checkpoint',str(R/'runs/patch4_candidate/recovery.pt'), + '--',*command],stdout=qlog,stderr=subprocess.STDOUT,env=env) + watchers=[] + for name in ['random_capacity_512_anneal','random_capacity_512']: + with (R/(name+'_cooldown_watch.log')).open('w') as log: + watchers.append(subprocess.Popen(['python3',str(R/'watch_evaluate.py'),'--run',str(R/'runs'/name), + '--evaluator',str(R/'random_capacity_inference/evaluate.py'),'--name',name, + '--steps','30000,36000'],stdout=log,stderr=subprocess.STDOUT,env=env)) + print({'queue_pid':queued.pid,'watch_pids':[p.pid for p in watchers]},flush=True) + result=queued.wait() + if result: + for p in watchers:p.terminate() + for p in watchers:p.wait() + raise SystemExit(result) +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity/launch_legacy.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity/launch_legacy.py new file mode 100644 index 0000000000000000000000000000000000000000..5bf7ac326ec15b02e9caea0b6357babc57c3d6e5 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity/launch_legacy.py @@ -0,0 +1,43 @@ +def main(): + """Queue the matched fresh-width pair after two existing allocations are released.""" + import json + from pathlib import Path + import subprocess + + R=Path('/workspace/research') + recovery=json.loads((R/'recovery2_launch_receipt.json').read_text()) + dependencies=['wide_capacity_146m_recovery','patch8'] + wait_pids=[recovery['jobs'][name]['pid'] for name in dependencies] + children=[] + for width in [512,1024]: + checks=json.loads((R/f'random_capacity_{width}_checks.json').read_text()) + assert checks['gradient_cosine']>.995 + name=f'random_capacity_{width}' + train=['env','OPENBLAS_NUM_THREADS=1','OMP_NUM_THREADS=1', + 'TORCHINDUCTOR_COMPILE_THREADS=2','MAX_JOBS=2', + 'PYTHONPATH=/workspace/research/compiler_support', + 'TRITON_CACHE_MANAGER=sibling_cache:SiblingFileCacheManager', + 'TRITON_CACHE_DIR=/tmp/timeseries-triton-cache', + 'TORCHINDUCTOR_CACHE_DIR=/tmp/timeseries-inductor-cache', + 'python3',str(R/'recovery/train.py'),'--code-dir',str(R/'random_capacity'), + '--packed',str(R/'packed_sample'),'--source-weights-from',str(R/'packed_sample'), + '--out',str(R/'runs'/name),'--initialize-from',str(R/f'{name}_initial.pt'), + '--steps','96000','--batch','48','--lr','.0002','--seed','307', + '--loss-mode','paired','--compile-loss','--stop-file',str(R/f'{name}.stop')] + command=['python3',str(R/'queued_train.py'),'--label',f'E79 fresh{width} seed307', + '--log',str(R/f'{name}_train.log'),'--receipt',str(R/f'{name}_queue.json')] + for pid in wait_pids:command+=['--wait-pid',str(pid)] + for dep in dependencies:command+=['--require-checkpoint',str(R/'runs'/dep/'recovery.pt')] + command+=['--']+train + with (R/f'{name}_queue.log').open('w') as f: + children.append(subprocess.Popen(command,stdout=f,stderr=subprocess.STDOUT)) + watch=['python3',str(R/'watch_evaluate.py'),'--run',str(R/'runs'/name), + '--evaluator',str(R/'random_capacity_inference/evaluate.py'),'--name',name, + '--steps','4000,8000,16000,24000,48000,72000,96000'] + with (R/f'{name}_watch.log').open('w') as f: + subprocess.Popen(watch,stdout=f,stderr=subprocess.STDOUT) + for child in children:child.wait() + assert all(child.returncode==0 for child in children) + +if __name__ == "__main__": + main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity/launch_lower_rate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity/launch_lower_rate.py new file mode 100644 index 0000000000000000000000000000000000000000..a9b2c79450b71b081832e7eaf0dce361c7da2a8d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity/launch_lower_rate.py @@ -0,0 +1,40 @@ +"""Queue a single-factor lower-learning-rate arm for the fresh146M model.""" +def main(): + import json + import os + import subprocess + from pathlib import Path + R = Path('/workspace/research') + checks = json.loads((R / 'random_capacity_1024_checks.json').read_text()) + assert checks['gradient_cosine'] > .995 and checks['normalization_overflow_fallback'] + name = 'random_capacity_1024_halflr' + env = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1') + train = ['env', 'OPENBLAS_NUM_THREADS=1', 'OMP_NUM_THREADS=1', + 'TORCHINDUCTOR_COMPILE_THREADS=2', 'MAX_JOBS=2', + 'PYTHONPATH=/workspace/research/compiler_support', + 'TRITON_CACHE_MANAGER=sibling_cache:SiblingFileCacheManager', + 'TRITON_CACHE_DIR=/tmp/timeseries-triton-cache', + 'TORCHINDUCTOR_CACHE_DIR=/tmp/timeseries-inductor-cache', + 'python3', str(R / 'recovery/train.py'), '--code-dir', str(R / 'random_capacity'), + '--packed', str(R / 'packed_sample'), '--source-weights-from', str(R / 'packed_sample'), + '--out', str(R / 'runs' / name), '--initialize-from', str(R / 'random_capacity_1024_initial.pt'), + '--steps', '96000', '--batch', '48', '--lr', '.0001', '--seed', '307', + '--loss-mode', 'paired', '--compile-loss', '--stop-file', str(R / (name + '.stop'))] + with (R / (name + '_queue.log')).open('w') as qlog, (R / (name + '_watch.log')).open('w') as wlog: + queued = subprocess.Popen(['python3', str(R / 'queued_train.py'), '--label', 'E94 fresh146M halfLR seed307', + '--log', str(R / (name + '_train.log')), '--receipt', str(R / (name + '_queue.json')), + '--wait-pid', '5690', '--require-checkpoint', str(R / 'runs/patch4_control/recovery.pt'), + '--', *train], stdout=qlog, stderr=subprocess.STDOUT, env=env) + watch = subprocess.Popen(['python3', str(R / 'watch_evaluate.py'), '--run', str(R / 'runs' / name), + '--evaluator', str(R / 'random_capacity_inference/evaluate.py'), '--name', name, + '--steps', '4000,8000,16000,24000,48000,72000,96000'], + stdout=wlog, stderr=subprocess.STDOUT, env=env) + print(json.dumps({'queue_pid': queued.pid, 'watch_pid': watch.pid}), flush=True) + result = queued.wait() + if result: + watch.terminate() + watch.wait() + raise SystemExit(result) + +if __name__ == '__main__': + main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity/model.py new file mode 100644 index 0000000000000000000000000000000000000000..3532e5063bd8b5013f6b6e35703707ffef66e00b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity/model.py @@ -0,0 +1,213 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity/queue_recovery3.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity/queue_recovery3.py new file mode 100644 index 0000000000000000000000000000000000000000..ca60d7ce3a745482824790ba818da843c84274fc --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity/queue_recovery3.py @@ -0,0 +1,44 @@ +def main(): + """Queue the matched fresh-width pair after two existing allocations are released.""" + import json + from pathlib import Path + import subprocess + + R=Path('/workspace/research') + recovery=json.loads((R/'recovery3_launch_receipt.json').read_text()) + dependencies=['wide_capacity_146m_recovery','patch8'] + wait_pids=[recovery['jobs'][name]['pid'] for name in dependencies] + children=[] + for width in [512,1024]: + checks=json.loads((R/f'random_capacity_{width}_checks.json').read_text()) + assert checks['gradient_cosine']>.995 and checks.get('normalization_overflow_fallback') is True + name=f'random_capacity_{width}' + train=['env','OPENBLAS_NUM_THREADS=1','OMP_NUM_THREADS=1', + 'TORCHINDUCTOR_COMPILE_THREADS=2','MAX_JOBS=2', + 'PYTHONPATH=/workspace/research/compiler_support', + 'TRITON_CACHE_MANAGER=sibling_cache:SiblingFileCacheManager', + 'TRITON_CACHE_DIR=/tmp/timeseries-triton-cache', + 'TORCHINDUCTOR_CACHE_DIR=/tmp/timeseries-inductor-cache', + 'python3',str(R/'recovery/train.py'),'--code-dir',str(R/'random_capacity'), + '--packed',str(R/'packed_sample'),'--source-weights-from',str(R/'packed_sample'), + '--out',str(R/'runs'/name),'--initialize-from',str(R/f'{name}_initial.pt'), + '--steps','96000','--batch','48','--lr','.0002','--seed','307', + '--loss-mode','paired','--compile-loss','--stop-file',str(R/f'{name}.stop')] + command=['python3',str(R/'queued_train.py'),'--label',f'E79 fresh{width} seed307', + '--log',str(R/f'{name}_train.log'),'--receipt',str(R/f'{name}_queue.json')] + for pid in wait_pids:command+=['--wait-pid',str(pid)] + for dep in dependencies:command+=['--require-checkpoint',str(R/'runs'/dep/'recovery.pt')] + command+=['--']+train + with (R/f'{name}_queue.log').open('w') as f: + children.append(subprocess.Popen(command,stdout=f,stderr=subprocess.STDOUT)) + watch=['python3',str(R/'watch_evaluate.py'),'--run',str(R/'runs'/name), + '--evaluator',str(R/'random_capacity_inference/evaluate.py'),'--name',name, + '--steps','4000,8000,16000,24000,48000,72000,96000'] + with (R/f'{name}_watch.log').open('w') as f: + watcher=subprocess.Popen(watch,stdout=f,stderr=subprocess.STDOUT) + print(json.dumps({'width':width,'queue_pid':children[-1].pid,'watch_pid':watcher.pid}),flush=True) + for child in children:child.wait() + assert all(child.returncode==0 for child in children) + +if __name__ == "__main__": + main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity/restart_corrected.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity/restart_corrected.py new file mode 100644 index 0000000000000000000000000000000000000000..0fa492437cc10d940ab177575b4583064dedfcb5 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity/restart_corrected.py @@ -0,0 +1,13 @@ +"""Validate the shared numerical correction, then start exactly one matched fresh pair.""" +def main(): + import json,os,subprocess,time + from pathlib import Path + R=Path('/workspace/research');env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1',TORCHINDUCTOR_COMPILE_THREADS='2',MAX_JOBS='2',PYTHONPATH=str(R/'compiler_support'),TRITON_CACHE_MANAGER='sibling_cache:SiblingFileCacheManager',TRITON_CACHE_DIR='/tmp/timeseries-triton-cache',TORCHINDUCTOR_CACHE_DIR='/tmp/timeseries-inductor-cache') + for width in (512,1024): + assert not list((R/'runs'/f'random_capacity_{width}').glob('*.pt')) + log=R/f'random_capacity_{width}_corrected_check.log' + with log.open('w') as f:subprocess.run(['python3',str(R/'random_capacity/check.py'),'--width',str(width)],stdout=f,stderr=subprocess.STDOUT,env=env,check=True) + result=json.loads((R/f'random_capacity_{width}_checks.json').read_text());print(json.dumps(result),flush=True) + with (R/'direct_v1/EXPERIMENTS.md').open('a') as f:f.write('\nE79 corrected-normalization fixture: '+json.dumps(result)+'\n') + subprocess.run(['python3',str(R/'random_capacity/queue_recovery3.py')],env=env,check=True) +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity_long_seasonal/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity_long_seasonal/check.py new file mode 100644 index 0000000000000000000000000000000000000000..057e28d3e4069be747026b1c59475048823653ab --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity_long_seasonal/check.py @@ -0,0 +1,71 @@ +"""E131 own-random function-preserving initialization and maximum compiled-loss audit.""" +import argparse,hashlib,importlib.util,json,sys,time +from pathlib import Path +import numpy as np +import torch +R=Path('/workspace/research');name='random_capacity_long_seasonal';sys.path.insert(0,str(R/name)) +from model import DirectForecaster,loss_fn +from data import Sampler +ap=argparse.ArgumentParser();ap.add_argument('--gpu',action='store_true');a=ap.parse_args() +torch.set_num_threads(2);torch.manual_seed(677);started=time.monotonic() +parent_path=R/'random_capacity_1024_initial.pt';parent=torch.load(parent_path,map_location='cpu',weights_only=False) +assert hashlib.sha256(parent_path.read_bytes()).hexdigest()=='c9693619ca6277c26fef3b2bde37ff6796bec97b3af9f94588bbc5ddd329ec90' +spec=importlib.util.spec_from_file_location('fresh_seasonal_control',R/'random_capacity/model.py');code=importlib.util.module_from_spec(spec);spec.loader.exec_module(code) +config=dict(parent['config'],long_seasonal_features=True);candidate=DirectForecaster(**config) +missing,unexpected=candidate.load_state_dict(parent['model'],strict=False) +extra={'long_query.weight','long_head.weight','long_head.bias'} +assert set(missing)==extra and not unexpected and all(torch.count_nonzero(candidate.state_dict()[k])==0 for k in extra) +assert all(torch.equal(v,candidate.state_dict()[k]) for k,v in parent['model'].items()) +assert all(p.requires_grad for p in candidate.parameters()) +assert (R/name/'data.py').read_bytes()==(R/'random_capacity/data.py').read_bytes() +assert (R/name/'model.py').read_bytes()==(R/'long_seasonal/model.py').read_bytes()==(R/(name+'_inference')/'model.py').read_bytes() +control=code.DirectForecaster(**parent['config']);control.load_state_dict(parent['model']) +if a.gpu: + import fcntl + lock=open(R/'.evaluation.lock','a');tick=time.monotonic();fcntl.flock(lock,fcntl.LOCK_EX);wait=time.monotonic()-tick;torch.backends.cuda.matmul.allow_tf32=True + candidate,control=candidate.cuda(),control.cuda();rng=np.random.default_rng(683) + ctx=torch.tensor(rng.normal(size=(8,512)).astype(np.float32),device='cuda');ctx[0,:23]=float('nan');ctx[1]=0 + periods=torch.tensor([[24,168],[7,365],[12,1],[52,1],[4,1],[1,1],[96,672],[2,14]],device='cuda');target=torch.tensor(rng.normal(size=(8,128)).astype(np.float32),device='cuda') + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16): + actual=candidate(ctx,periods,128);expected=control(ctx,periods,128) + lossa=loss_fn(candidate,ctx,target,periods,paired=True);lossb=code.loss_fn(control,ctx,target,periods,paired=True) + assert all(torch.equal(v,w) for v,w in zip(actual,expected)) and torch.equal(lossa,lossb) + del control,ctx,target,periods,actual,expected,lossa,lossb + torch.cuda.empty_cache();torch.cuda.reset_peak_memory_stats();free_before=torch.cuda.mem_get_info()[0]/2**20 + sampler=Sampler(R/'packed_sample',seed=683,source_weights_from=R/'packed_sample') + arrays=sampler.sample(48,4096,1024);x,y,p=[torch.from_numpy(v).cuda() for v in arrays] + placeholders=[torch.zeros_like(v) for v in candidate.parameters() for _ in range(3)] + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(candidate,x,y,p,paired=True) + loss.backward();torch.cuda.synchronize();assert torch.isfinite(loss) + assert all(v.grad is not None and torch.isfinite(v.grad).all() for v in candidate.parameters()) + gradients={k:float(dict(candidate.named_parameters())[k].grad.norm()) for k in ['long_query.weight','long_head.weight','long_head.bias','head.weight']} + assert gradients['long_head.weight']>0 and gradients['head.weight']>0 + memory=dict(batch=48,signed_rows=96,context=4096,horizon=1024,loss=float(loss.detach()),peak_allocated_mib=torch.cuda.max_memory_allocated()/2**20,peak_reserved_mib=torch.cuda.max_memory_reserved()/2**20,free_before_mib=free_before,includes_adam_and_ema_placeholders=True,selected_gradient_norms=gradients) + del placeholders,loss,x,y,p,arrays + candidate.zero_grad(set_to_none=True);torch.cuda.empty_cache() + x,y,p=[torch.from_numpy(v).cuda() for v in sampler.sample(8,512,128)] + def step(fn): + candidate.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=fn(candidate,x,y,p,paired=True) + loss.backward();return float(loss.detach()) + reference=step(loss_fn);grads={n:v.grad.detach().clone() for n,v in candidate.named_parameters()};tick=time.monotonic() + actual=step(torch.compile(loss_fn,fullgraph=True,dynamic=False));torch.cuda.synchronize();dot=norma=normb=0.;maximum=0. + for key,v in candidate.named_parameters(): + left,right=grads[key],v.grad;assert torch.isfinite(right).all() + dot+=float((left*right).sum());norma+=float(left.square().sum());normb+=float(right.square().sum());maximum=max(maximum,float((left-right).abs().max())) + cosine=dot/(norma*normb)**.5;assert abs(reference-actual)<.003*max(reference,.1) and cosine>.995 + result=dict(fixture_seed=683,training_seed=307,gpu_initial_forward_and_loss_bitwise_equal=True,all_parameters_trainable=True,maximum_shape_memory=memory,eager_loss=reference,compiled_loss=actual,gradient_cosine=cosine,max_gradient_difference=maximum,compile_comparison_seconds=time.monotonic()-tick,lock_wait_seconds=wait,seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False) + (R/(name+'_gpu_checks.json')).write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True);raise SystemExit() +rng=np.random.default_rng(677);periods=torch.tensor([[24,168],[7,365],[52,1],[1,1],[4,1],[12,1]]) +for c,h in [(32,6),(128,29),(512,128)]: + ctx=torch.tensor(rng.normal(size=(6,c)).astype(np.float32));ctx[0,:c//3]=float('nan');ctx[1]=0;ctx[2]=float('nan') + target=torch.tensor(rng.normal(size=(6,h)).astype(np.float32));target[1,h//2:]=float('nan') + with torch.inference_mode(): + actual=candidate(ctx,periods,h);expected=control(ctx,periods,h) + lossa=loss_fn(candidate,ctx,target,periods,paired=True);lossb=code.loss_fn(control,ctx,target,periods,paired=True) + assert all(torch.equal(v,w) for v,w in zip(actual,expected)) and torch.equal(lossa,lossb) +out=R/(name+'_initial.pt');assert not out.exists() +checkpoint=dict(model=candidate.state_dict(),config=config,step=0,args=dict(parent['args']),parent_checkpoints=[str(parent_path)],conversion=dict(method='zero-initialize E107 seasonal query/head on own untrained E79random146M backbone',parent_sha256=hashlib.sha256(parent_path.read_bytes()).hexdigest(),fixture_seed=677,initial_function_bitwise_equal=True,optimizer_updates=0)) +torch.save(checkpoint,out) +result=dict(fixture_seed=677,training_seed=307,initial_forward_and_loss_bitwise_equal=True,inherited_weights_bitwise_equal=True,sampler_byte_identical=True,model_code_byte_identical_to_E107=True,all_parameters_trainable=True,added_parameters=sum(candidate.state_dict()[k].numel() for k in extra),parameters=sum(p.numel() for p in candidate.parameters()),checkpoint_sha256=hashlib.sha256(out.read_bytes()).hexdigest(),seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False) +(R/(name+'_checks.json')).write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity_long_seasonal/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity_long_seasonal/data.py new file mode 100644 index 0000000000000000000000000000000000000000..9bd574ba6a585ed0e949397770d0d4c93636e608 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity_long_seasonal/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=np.exp(-10**(-r.uniform(0,4)));noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity_long_seasonal/launch.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity_long_seasonal/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..a320eb6bc14e36047e4de7edab3629ed9668cfdb --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity_long_seasonal/launch.py @@ -0,0 +1,24 @@ +"""E131 replaces the completed E94 allocation, with E79 as the matched control.""" +def main(): + import hashlib,json,os,subprocess + from pathlib import Path + R=Path('/workspace/research');name='random_capacity_long_seasonal';run=R/'runs'/name + cpu=json.loads((R/(name+'_checks.json')).read_text());gpu=json.loads((R/(name+'_gpu_checks.json')).read_text()) + assert cpu['initial_forward_and_loss_bitwise_equal'] and cpu['sampler_byte_identical'] and cpu['model_code_byte_identical_to_E107'] + assert gpu['gpu_initial_forward_and_loss_bitwise_equal'] and gpu['gradient_cosine']>.995 and gpu['optimizer_updates']==0 + assert gpu['maximum_shape_memory']['peak_reserved_mib']<12000 + initial=R/(name+'_initial.pt');assert hashlib.sha256(initial.read_bytes()).hexdigest()==cpu['checkpoint_sha256'] + control=json.loads((R/'random_capacity_1024_queue.json').read_text());allocation=json.loads((R/'random_capacity_1024_halflr_queue.json').read_text());command=list(control['command']) + assert '--resume' not in command and '--start-step' not in command + assert command[command.index('--steps')+1]=='96000' and command[command.index('--batch')+1]=='48' and command[command.index('--lr')+1]=='.0002' and command[command.index('--seed')+1]=='307' and '--compile-loss' in command + for flag,value in [('--code-dir',str(R/name)),('--out',str(run)),('--initialize-from',str(initial)),('--stop-file',str(R/(name+'.stop')))]:command[command.index(flag)+1]=value + env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1') + with (R/(name+'_queue.log')).open('w') as qlog,(R/(name+'_watch.log')).open('w') as wlog,(R/(name+'_matched_cutoffs.log')).open('w') as clog: + queue=subprocess.Popen(['python3',str(R/'queued_train.py'),'--label','E131 fresh146M learned seasonal summaries seed307','--log',str(R/(name+'_train.log')),'--receipt',str(R/(name+'_queue.json')),'--wait-pid',str(allocation['launcher_pid']),'--wait-pid',str(control['launcher_pid']),'--require-checkpoint',str(R/'runs/random_capacity_1024_halflr/ema096000.pt'),'--require-checkpoint',str(R/'runs/random_capacity_1024/ema096000.pt'),'--',*command],stdout=qlog,stderr=subprocess.STDOUT,env=env) + watch=subprocess.Popen(['python3',str(R/'watch_evaluate.py'),'--run',str(run),'--evaluator',str(R/(name+'_inference')/'evaluate.py'),'--name',name,'--expected-packed',str(R/'packed_sample'),'--steps','4000,8000,16000,24000,48000,72000,96000'],stdout=wlog,stderr=subprocess.STDOUT,env=env) + compare=subprocess.Popen(['python3',str(R/'recovery/watch_matched_cutoffs.py'),'--run',name,'--control','random_capacity_1024','--evaluator',str(R/(name+'_inference')/'evaluate.py'),'--label','E131','--control-evaluator',str(R/'random_capacity_inference/evaluate.py'),'--steps','48000,96000'],stdout=clog,stderr=subprocess.STDOUT,env=env) + print(json.dumps(dict(queue_pid=queue.pid,watch_pid=watch.pid,comparison_pid=compare.pid)),flush=True) + result=queue.wait() + if result:watch.terminate();compare.terminate() + watch.wait();compare.wait();raise SystemExit(result) +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity_long_seasonal/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity_long_seasonal/model.py new file mode 100644 index 0000000000000000000000000000000000000000..298ee3b840cbc8b7da585ee5e47a3822d06717b0 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/random_capacity_long_seasonal/model.py @@ -0,0 +1,260 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + + +def centered_seasonal_difference(z, valid, periods, horizon): + b, c = z.shape + time = torch.arange(horizon, device=z.device)[None, :] + sums = F.pad((z * valid).cumsum(-1), (1, 0)) + counts = F.pad(valid.float().cumsum(-1), (1, 0)) + deltas, extras = [], [] + for j in range(2): + period = periods[:, j:j+1].clamp(min=1) + anchor = c - period + time % period + centered, masks = [], [] + for cycle in range(16): + end = (c - cycle * period).clamp(min=0, max=c) + start = (c - (cycle + 1) * period).clamp(min=0, max=c) + count = counts.gather(1, end) - counts.gather(1, start) + mean = (sums.gather(1, end) - sums.gather(1, start)) / count.clamp(min=1) + index = anchor - cycle * period + safe = index.clamp(min=0, max=c-1) + present = (index >= 0) & valid.gather(1, safe) + centered.append(z.gather(1, safe) - mean) + masks.append(present) + values = torch.stack(centered) + seen = torch.stack(masks) + n4 = seen[:4].sum(0) + n16 = seen.sum(0) + mean4 = (values[:4] * seen[:4]).sum(0) / n4.clamp(min=1) + mean16 = (values * seen).sum(0) / n16.clamp(min=1) + active = (period >= 2) & (n4 >= 2) & (n16 >= 8) + delta = torch.where(active, mean16 - mean4, 0.) + support = torch.where(active, n16.float() / 16, 0.) + deltas.append(delta) + extras.extend([delta, support]) + return torch.stack(deltas, -1), torch.stack(extras, -1) + + + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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,long_seasonal_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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,long_seasonal_features=long_seasonal_features) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + self.long_query=nn.Linear(patch*4,d,bias=False) if long_seasonal_features else None + self.long_head=nn.Linear(d,patch*2) if long_seasonal_features else None + if long_seasonal_features: + nn.init.zeros_(self.long_query.weight) + nn.init.zeros_(self.long_head.weight);nn.init.zeros_(self.long_head.bias) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + if self.long_query is not None:long_delta,long_extra=centered_seasonal_difference(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + hidden=self.norm(q) + out=self.head(hidden).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + if self.long_head is not None: + gates=self.long_head(hidden).view(b,h,2).float().tanh() + median=median+(gates*long_delta).sum(-1) + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/accumulation.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/accumulation.py new file mode 100644 index 0000000000000000000000000000000000000000..93546060dd431f932e5f421adcdf8a35f10b46eb --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/accumulation.py @@ -0,0 +1,14 @@ +"""Context-only row weights for the existing paired forecasting objective.""" +import torch + +@torch.no_grad() +def context_loss_weights(model,ctx,periods): + # Keep the arithmetic and fallback identical to random_capacity.loss_fn. + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + return (.25+errscale).reciprocal().clamp(.25,4.) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/brief.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/brief.py new file mode 100644 index 0000000000000000000000000000000000000000..b533acc2959394d38c13cb6b619118c32e48e736 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/brief.py @@ -0,0 +1,50 @@ +"""Current recovery handoff derived from receipts; never changes training state.""" +import datetime,json +from pathlib import Path +R=Path('/workspace/research');state=json.loads((R/'CURRENT_RESEARCH_STATE.json').read_text()) +now=datetime.datetime.now(datetime.timezone.utc).isoformat() +lines=['# Current recovery brief','',now,'', + 'Continuous research; no endpoint or final hand-in. One H10080GB,22CPUs,224GiB requested RAM; no network or pretrained assets. Do not inspect credentials or spawn agents. Only the95allowlisted corpus directories and own synthetic generators may train models. All validation cutoffs are selection/diagnostics only.','', + '## Published','',json.dumps(state['published']),'','## Active selection and engineering',''] +for key in ['E132','E135','E138','E139','E140','E141','E142','E143','E144','E145','E146','E147','E148','E149','E151','E153','E154','E156']: + if key in state.get('selection_probes',{}):lines.append('- '+key+': '+json.dumps(state['selection_probes'][key])) +for key in ['E149','E150','E152','E155','E157','E158']: + if key in state.get('prepared_research',{}):lines.append('- '+key+': '+json.dumps(state['prepared_research'][key])) +lines+=['','## Live controller receipts',''] +for name in ['fresh96_full_pipeline_receipt.json','width6_fresh96_ensemble_validation_receipt.json','width12_ensemble_validation_receipt.json','width12_fresh96_ensemble_validation_receipt.json','width_trend_transfer_receipt.json','ensemble_gate_selection_receipt.json','distilled_fourth_member_receipt.json','full_capacity_ensemble_receipt.json','ensemble_gate_refresh_selection_receipt.json','ensemble_gate_full_selection_receipt.json','ensemble_gate_refresh_full_selection_receipt.json','capacity_patch8_ensemble_receipt.json','capacity_patch8_6k_ensemble_validation_receipt.json','capacity_patch8_12k_ensemble_validation_receipt.json','horizon_patch8_routing_validation_receipt.json','fresh_seasonal_ensemble_receipt.json','random_capacity_1536_engineering_receipt.json','seasonal_distillation_factorial_engineering_receipt.json','seasonal_distillation_factorial_selection_receipt.json','seasonal_distillation_factorial_start_gate_receipt.json','fresh_seasonal_width_engineering_receipt.json','fresh_seasonal_width_start_gate_receipt.json']: + p=R/name + if p.exists(): + d=json.loads(p.read_text());compact={k:d[k] for k in ['pid','status','current_kind','current_step','seconds','skill'] if k in d} + if 'results' in d:compact['completed_results']=[{k:v[k] for k in ['step','duration','positive_cutoffs','mean_delta','selection_gate_passed'] if k in v} for v in d['results']] + lines.append('- '+str(p)+': '+json.dumps(compact)) +lines+=['','## Active and queued training',''] +for name,job in state.get('external_jobs',{}).items(): + if job['status'] not in ['running','waiting']:continue + lines += ['- '+name+': '+str(job['status'])+'; receipt '+job['receipt']+'; queue PID snapshot '+str(job['queue_pid_at_snapshot'])+'; children '+str(job['child_pids_at_snapshot'])+'.', + ' Last record: '+json.dumps(job['last_phase_record']), + ' Complete recovery: '+str(job['complete_recovery_checkpoint'])+'; latest EMA: '+str(job['latest_saved_ema'])+'.'] +lines+=['','## Recovery rules','', + '- After an operator restart, inspect actual processes before launch. Restore each active trainer from complete recovery.pt: optimizer, ema_state, all NumPy/Torch/CUDA RNGs, prefetched batch, original LR schedule and maximum steps. Selection EMA weights are not full recovery state. Never blindly rerun an old launch.py; rewire queue dependencies to new PIDs and require the same endpoint files.', + '- Keep long-lived launchers/controllers alive. Child Popen jobs are killed when a short-lived tool parent exits. Persistent tool sessions or a waiting parent are required.', + '- E101 teacher is immutable distill_teacher_E96, descriptor1503d92c...; E138 experts are separately immutable gating_experts_E130, descriptorfa97880d.... Never replace either with submission. Original E101 compiled loss is allowed, compiled teacher is NOT. Rejected E126 stays stopped.', + '- E138 gate resume requires --gate-package /workspace/research/gating_experts_E130, TF32False, only6340gateparams optimized. E134 curriculum requires --visibility-curriculum. E143 synthetic origin adds no persistent RNG/state beyond E113. E145 buildings4x adds no RNG/state beyond the original sampler. Preserve actual code-dir on resume.', + '- Current allocation chains: E110full -> E134visibility; E122originalAR -> E137freshdepth; E131freshseasonal -> E145buildings4x; E138gate -> E143lowfreqage -> E146directtrendreplication -> E149integratedlevel -> E152refresh -> E152full -> E152refresh_full; E141patch16control -> E141patch8candidate -> E147fullcorpushighLR. E101distillation continues its original96k schedule; E155fresh329M is queued for its allocation after96k, fullaudits passed; queue8068 is a snapshot, inspectreceipt. Completed E79/E94/E123/E129/E136/E141control are not resumed.', + '- E157conditional feature/distillation2x2: newfeaturehalfLR afterE13496 and feature+distill afterE14796, onlyifE13148k matched>=3positive/positive mean andCPU/GPU/fullrecoverypass. InitialE131f7e35fresh,seed307/B48/LR1e-4/96k, immutableuncompiledE96teacher coefficient.5. Notqueued until actual launchreceipt exists. Newstudentcode random_capacity_long_seasonal_distill; plainfeature reusesrandom_capacity_long_seasonal.', + '- E158conditional width-only fresh146M: sameE131recipe, add32800zero width-head params; no dispersionquery. Own initial4df8f106...,146608480params,seed307/B48/LR2e-4/original96k. SourceE13148>=3positive/positive mean plusCPU/GPU/recovery gates before queuing; replacesE137deepallocation after96k. Startcontroller/engineering receipts authoritative, never duplicate launch.', + '- E149 adds integrated_rng(seed+1300003) to the original sampler; complete recovery captures it alongside original/horizon RNG and prefetched batch. E150 optional --micro-batch preserves weighted effective-batch loss; E155declares effectiveB48/micro16, with code-dirrandom_capacity. Its resume must preserve --micro-batch16; verify whether it is actually queued/running from its receipt.', + '- E141 uses same random_capacity code and own E79wide96 parent, seed809/B32/LR2e-5/12k, control then folded patch8 candidate sequentially. E137 is freshd768/11encoder/7decoder, not a mature depth graft. E145 uses full corpus but same E110LR1e-4/seed307/B48/96k.', + '- Restore compiler_cache_backup to the SAME /tmp paths before compiled jobs. Exact compiler environment is in CURRENT_RESEARCH_STATE.json and recovery/train.py now explicitly establishes the six compilation/cache settings before importingtorch for future compiled jobs. Cold compilation can span many first shapes; check first-step recovery and CPU activity before diagnosing a stall.', + '- All full replays and GPU engineering audits serialize with .evaluation.lock. Six main trainers share the single H100; queued experiments replace existing allocations. No extra GPU assumption.', + '- E154fixedH>=720 five-expert rule has own runtime/publisher/promoter in horizon_patch8_routing; all5 models MUST execute on every instance before choosing the fourth contribution. Its private validation/publication status is in receipts. E153primary6k failed full validation and final12k source gate failed; do not publishE153.', + '- E140 meta-device loader was published, predictSHA4de2b53c..., with all97forecasts unchanged. Shared four_member_ensemble/runtime now uses it. E138 FrozenExperts and E101teacher loaders remain unchanged. Four-member candidates built with older runtime need rebuilding/revalidation before guarded promotion.', + '- Four-member publisher: four_member_ensemble/publish.py. E139 promoter: seasonal_width_transfer/promote.py --duration6|12. E142 promoter: fresh_capacity_duration/promote.py --kindjoint. E144 promoter: width_trend_transfer/promote.py --duration6|12. E148 promoter: width12_capacity_combination/promote.py (fixedjoint12 default). E138 has separate ensemble_gate/{validate,promote}.py --step6000|12000. No auto-promotion; read full results/group tradeoffs and require complete checks plus current-best improvement.', + '- E132 isolated final fresh fourth member lost full validation to E139; do not publish it. E142 is the previously declared width6+fresh96 combination. E144 fixes width6+trenddelta with fresh48, not fresh96 or width12. Preserve these declared contrasts. E138primary6k/final12k; 1k/3k are learning diagnostics.', + '- E128dispersion transfers, E133seed-average correction, E124weekly-average gate, E113short-LFwindows, E121older-history, E115joint-phase, E126compiledteacher and other negative branches remain rejected. E123final durability determines whether any new horizon transfer is warranted; none currently selected.', + '- E105output collision: corrected output runs/stratified_volume; E95final and2k..12kweights survive, but E95recovery/original1k do not. Never resume E95. Incident folder incidents/stratified_volume_output_collision.', + '- Never retrain supplied baselines. Keep all scratch parent hashes, actual seeds/schedules, source directories/generators and runtime assets in selected packages. Publishers archive all declared Python code including schedules.py and spectral.py. Every expert forecasts every instance.', + '- Replace submission only atomically. recovery/refresh_journal.py performs an atomic journal-only replacement while hashing all other package files. Avoid running it concurrently with a publication.', + '- Masterjournal direct_v1/EXPERIMENTS.md, SESSION_20261023_PROGRESS.md and RESEARCH_IDEAS.md contain declarations and negative outcomes. Receipts/checkpoints are authoritative over snapshot PIDs.','', + '## Latest operator recovery','',json.dumps(state.get('operator_recovery4',{}),ensure_ascii=False),'','## Time anchor','', + 'Historical recovery allowance:151596research seconds at2026-10-23T02:45:51UTC. Storage outage interrupted about11:18UTC; recovery4 found a new container at21:19:38UTC. Approximately10h operator downtime and preflight are excluded, so do not subtract raw wall time from that allowance. The original external research budget remains authoritative; no new allowance was supplied at recovery4. Active goal has no requested token budget.',''] +(R/'RECOVERY_BRIEF.md').write_text('\n'.join(lines)) +print('Wrote current brief; active/queued',sum(j['status'] in ['running','waiting'] for j in state.get('external_jobs',{}).values())) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/brief_before_E145.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/brief_before_E145.py new file mode 100644 index 0000000000000000000000000000000000000000..ac482e7e2e1c0c3199c6c7286031df7c45ce8881 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/brief_before_E145.py @@ -0,0 +1,34 @@ +"""Write a short, current recovery handoff; never modify training state.""" +import datetime +import json +from pathlib import Path + +R = Path('/workspace/research') +s = json.loads((R/'CURRENT_RESEARCH_STATE.json').read_text()) +lines = ['# Current recovery brief', '', datetime.datetime.now(datetime.timezone.utc).isoformat(), '', + 'Continuous research; no endpoint/final hand-in. One H10080GB,22CPUs,224GiB requested RAM; no network or pretrained assets. Do not inspect credentials or spawn agents.', '', + '## Published', '', json.dumps(s['published']), '', '## Pending selection', '', + json.dumps(s.get('next_candidate',{})), '', json.dumps({k:v for k,v in s.get('selection_probes',{}).items() if k in ['E128','E130','E132','E133','E134','E135','E136','E137','E138','E139','E140','E141','E142','E143']}), '', '## Active and queued training', ''] +for name, job in s.get('external_jobs',{}).items(): + if job['status'] not in ['running','waiting']: + continue + lines += [f'- {name}: {job["status"]}; receipt {job["receipt"]}; queue PID snapshot {job["queue_pid_at_snapshot"]}; children {job["child_pids_at_snapshot"]}.', + f' Last logged record: {json.dumps(job["last_phase_record"])}', + f' Complete recovery: {job["complete_recovery_checkpoint"]}; latest EMA: {job["latest_saved_ema"]}.'] +lines += ['', '## Recovery rules', '', + '- PIDs and launch-script dependencies are snapshots. After an operator restart, restore running jobs from each complete recovery.pt, preserving optimizer/EMA/RNG/prefetched batch and original schedules. Rewire waiting jobs to the newly launched dependency PIDs; do not blindly rerun old launch scripts.', + '- Waiting dependency chain: weekly_replication_control after long_seasonal; weekly_replication_candidate after that control; lowfreq_windows after that candidate; long_seasonal_replication after lowfreq_windows. phase_joint waits for random_capacity_512 final96000; seasonal_dispersion waits for phase_joint final12000; seasonal_history waits for seasonal_dispersion final12000. random_capacity_original_ar waits for random_capacity_1024 final96000; log_horizon waits for long_seasonal_replication final12000; seasonal_width waits for seasonal_history final12000; random_capacity_long_seasonal waits for both E94halfLR and E79wide final96000 and replaces only the E94allocation. visibility_curriculum waits for E110full and E79wide final96000 and replaces only the E110allocation; preserve --visibility-curriculum on any resume. direct_trend_head waits for E129seasonal_width final12000 and replaces that allocation. random_capacity_deep waits for E122originalAR and E79wide final96000, replacing only the E122allocation.', + '- E121 history-aware ensemble runtime is prepared at history_three_patch_ensemble; synthetic audit checks exact standalone composition and ordinary legacy equality. It also applies member finite cleanup before averaging, correcting a pre-existing extreme-value discrepancy. Use this separate publisher and complete public replay before any E121 publication; E130 now publishes four members using four_member_ensemble/publish.py, retaining both finite cleanup and per-member history support. Use that publisher for four-member packages.', + '- E126 compiled_teacher_trial completed its mandatory17000stop; do not resume it. It preserved original96000 LR schedule from immutable distill_ensemble_recovery016000.pt. Original E101 stays active. Compiler takeover rejected: max cutoff drift0.001964 exceeded0.0005 tolerance, with only3to5percent warm shared-device timing gain. No coefficient change selected. E125 component ablations completed; both paths help. E127 finite-member numerical fix is published with all97predictions bitwise unchanged; do not republish it. E128 dispersion transfers6000 and12000 both lost full validation; neither is published. E130 equal-quarter package is the current best. E132 checks scheduled E79wide96000 as the fourth member; E133 passed both source replication gates but its fixed averaged correction failed the ensemble gate (2of4positive, mean-0.0000154271); no full replay or averaging sweep. Receipts are indexed in CURRENT_RESEARCH_STATE.json.', + '- E138 learned gate uses immutable /workspace/research/gating_experts_E130, descriptorfa97880d..., even if submission improves. CPU/GPU/recovery/publicruntime/relocation audits passed; active since10:27 after E123final12000. Check queue receipt and rewire dependencies after restart. Training must preserve --gate-package and restore complete optimizer/EMA/RNG/prefetched batch. No expert tensors enter the gate optimizer. Gate publisher is ensemble_gate/publish.py. E139width primary6k is published at0.3843356309048914 after allfour diagnostics/fullsuite/bitwisecomposition;12k requires matched-source gate. E140loader-only runtime published10:24:27 after full97bitwiseidentity/relocation; sameE139weights/score, predictSHA4de2b53c.... Sharedfour-memberruntime nowmeta-loads; newquadcandidates useit. Gate trainer/experts loader unchanged. E132final fourthmember fullsuite complete but rejected:0.384297081868 below E1390.384335630905. E142width6+final quartet passeddiagnostics; persistent fresh_capacity_duration/full_pipeline.py runs its complete suite, no automaticpromotion. E13912ktransfer also passed3of4vscurrent andis inwidth12fullsuite. E144fixed direct-trend transfer on frozenwidth6base: width_trend_transfer/run.py primary6active, conditional12sourcegate; no fullsuite unless diagnosticgatepasses. E145fresh146Mfull-corpusbuilding4x sampler audited andqueued afterE131final96000, sameE110seed307/B48/LR1e-4/96k; resumecompleteRNG/optimizerstate, no newgenerator. E143low-frequency synthetic prefix-origin study CPU/GPU/recovery passed; queued29836 afterE13828517final12000, launcher persistent61462. Sampler state needs no extra RNG. E141matched146Mpatch16/patch8 continuations seed809/B32/LR2e-5/12k passed CPU/GPUaudits, queued29105control afterE13626926final12000 then29107candidate aftercontrolfinal12000. Same random_capacity model/data code, candidate folded ownE79wide96checkpoint. Preserve fullrecovery/compiledloss andsequentialdependency after restart. Use seasonal_width_transfer/promote.py only after better full replay and all checks.', + '- E101 distillation teacher is immutable /workspace/research/distill_teacher_E96, even after later publications. Do not substitute the current submission.', + '- Restore compiler_cache_backup to the same /tmp cache paths before restarting compiled trainers. Exact environment and commands are in CURRENT_RESEARCH_STATE.json.', + '- E105 output collision is documented in incidents/stratified_volume_output_collision. Correct E105 output is runs/stratified_volume. E95final and2k..12k weights survive, but E95optimizer recovery and original1k weights were lost. Do not resume completed E95.', + '- All previous negative/stopped branches stay stopped unless a new matched experiment explicitly revisits them. Never retrain the supplied baselines.', + '- Current training-source publisher archives all Python modules from explicitly declared directories, fixing earlier omissions of spectral.py and schedules.py. Complete-source members carry a -complete suffix when rebuilt. Runtime/weight hashes were unchanged.', + '- Full evaluation and GPU diagnostics use .evaluation.lock; the six main trainers share the one H100. The bounded E126 seventh-process probe completed17000 and should remain stopped. Dataset windows under data/valid and all earlier cutoffs are selection only, never training.', + '- Master journal direct_v1/EXPERIMENTS.md, chronological SESSION_20261023_PROGRESS.md, and RESEARCH_IDEAS.md contain decisions and rejected candidates. Recheck live processes and latest reports before acting.', + '', '## Time anchor', '', + 'Latest operator recovery allowance:151596research seconds at2026-10-23T02:45:51UTC. Pauses/preflight excluded. The goal remains active and has no requested token budget.', ''] +(R/'RECOVERY_BRIEF.md').write_text('\n'.join(lines)) +print('Wrote RECOVERY_BRIEF.md with '+str(sum(j['status'] in ['running','waiting'] for j in s.get('external_jobs',{}).values()))+' active/queued jobs.') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/capacity_curves.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/capacity_curves.py new file mode 100644 index 0000000000000000000000000000000000000000..c24e437c667b7ace7bd8b7ce74a037912dee613b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/capacity_curves.py @@ -0,0 +1,81 @@ +"""Summarize completed validation checkpoints and measured shared-GPU training time.""" +import csv +import json +import time +from pathlib import Path + +R = Path('/workspace/research') +started = time.monotonic() +names = ['random_capacity_512', 'random_capacity_1024', 'random_capacity_1024_halflr', + 'random_capacity_full', 'distill_ensemble', 'random_capacity_512_anneal', + 'random_capacity_original_ar', 'random_capacity_long_seasonal', + 'visibility_curriculum', 'random_capacity_deep', 'random_capacity_buildings', + 'random_capacity_full_highlr', 'ensemble_gate', 'capacity_patch8_control', + 'capacity_patch8_candidate', 'lowfreq_age', 'direct_trend_replication', 'integrated_level', + 'ensemble_gate_refresh', 'ensemble_gate_full', 'ensemble_gate_refresh_full', 'random_capacity_1536', 'random_capacity_long_seasonal_halflr', + 'random_capacity_long_seasonal_distill', 'random_capacity_seasonal_width'] +rows = [] +phase_ledger = {} +for name in names: + records = {} + phases = [] + logs = sorted(R.glob(name+'_train*.log'), key=lambda p:(p.name!=name+'_train.log',p.name)) + preceding_loop_seconds = 0. + for log in logs: + phase_records = {} + completed_seconds = None + starting_step = None + for line in log.read_text().splitlines(): + try: + item = json.loads(line) + except json.JSONDecodeError: + continue + if not isinstance(item,dict): + continue + if 'starting_step' in item: + starting_step = item['starting_step'] + if 'training_process_loop_seconds' in item: + completed_seconds = item['training_process_loop_seconds'] + if isinstance(item,dict) and 'step' in item and 'seconds' in item: + phase_records[item['step']] = item + records[item['step']] = dict(item,phase_log=str(log), + accumulated_logged_loop_seconds=preceding_loop_seconds+item['seconds']) + logged_seconds = max((v['seconds'] for v in phase_records.values()),default=0.) + measured_seconds = completed_seconds if completed_seconds is not None else logged_seconds + phases.append(dict(log=str(log),starting_step=starting_step, + last_logged_step=max(phase_records,default=None), + measured_training_loop_seconds=measured_seconds, + endpoint_record_present=completed_seconds is not None, + unlogged_interrupted_or_running_tail_not_included=completed_seconds is None)) + preceding_loop_seconds += measured_seconds + phase_ledger[name] = phases + config_path = R/'runs'/name/'config.json' + config = json.loads(config_path.read_text()) if config_path.exists() else {} + for report in sorted((R/'evals').glob(name+'_ema*/report.json')): + result = json.loads(report.read_text()) + step = int(report.parent.name.rsplit('ema',1)[1]) + if result['n_failed']: + continue + record = records.get(step,{}) + rows.append(dict(run=name,step=step,parameters=config.get('parameters'), + seed=config.get('seed'),batch=config.get('batch'),micro_batch=config.get('micro_batch'),learning_rate=config.get('lr'), + packed=config.get('packed'),skill=result['skill_score'], + rel_mase=result['rel_mase_gmean'],rel_wql=result['rel_wql_gmean'], + checkpoint_sha256=result['checkpoint_sha256'], + training_phase_loop_seconds=record.get('seconds'), + accumulated_logged_training_loop_seconds=record.get('accumulated_logged_loop_seconds'), + training_phase_log=record.get('phase_log'), + evaluation_seconds=result.get('eval_seconds'),report=str(report))) +rows.sort(key=lambda item:(names.index(item['run']),item['step'])) +output = dict(generated_utc=time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()), + note='Validation selection only. Time is logged training-loop wall on the shared single H100, not isolated GPU time or the external research budget. Accumulation includes recorded earlier phases and repeated updates after recovery, but excludes operator downtime and startup time. Interrupted/running phase tails beyond the final log record are unknown and excluded; accumulated values can therefore be lower bounds. The cooldown arm starts from saved24000state. No missing time is inferred.', + phases=phase_ledger,rows=rows,analysis_seconds=time.monotonic()-started,no_training_or_new_inference=True) +(R/'capacity_learning_curves.json').write_text(json.dumps(output,indent=2)) +with (R/'capacity_learning_curves.csv').open('w',newline='') as handle: + writer = csv.DictWriter(handle,fieldnames=list(rows[0]) if rows else ['run']) + writer.writeheader() + writer.writerows(rows) +for name in names: + selected = [r for r in rows if r['run']==name] + if selected: + print(json.dumps(selected[-1])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/check_accumulation_cpu.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/check_accumulation_cpu.py new file mode 100644 index 0000000000000000000000000000000000000000..d159d44dd98a21d35e1919615f9c5e9d173f5d1e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/check_accumulation_cpu.py @@ -0,0 +1,43 @@ +"""Check objective/gradient preservation where equal microbatch averaging is wrong.""" +import copy,json,sys,time +from pathlib import Path +import torch +R=Path('/workspace/research');sys.path.insert(0,str(R/'random_capacity')) +from model import DirectForecaster,loss_fn +from accumulation import context_loss_weights +started=time.monotonic();torch.set_num_threads(1);torch.manual_seed(967) +model=DirectForecaster(d=64,heads=8,enc_layers=2,dec_layers=2,patch=16) +with torch.no_grad():model.head.weight.normal_(std=.015) +x=torch.randn(9,128);t=torch.arange(128).float() +x[0]=x[0].cumsum(0);x[1]=2+.005*x[1];x[2]=torch.sin(t/4)+.01*x[2] +x[4,:80]=float('nan');x[5]=float('nan');x[6]=.02*t+.03*x[6] +x[7]=1e22+5e20*x[7] +y=torch.randn(9,32);y[4,7:]=float('nan');y[5]=float('nan');y[7]=1e22+5e20*y[7] +p=torch.tensor([[1,1],[1,1],[24,168],[1,1],[7,365],[12,1],[1,1],[1,1],[24,168]]) +reference=loss_fn(model,x,y,p,paired=True);reference.backward() +grads={k:v.grad.detach().clone() for k,v in model.named_parameters()} +model.zero_grad(set_to_none=True) +weights=context_loss_weights(model,x,p);parts=[];factors=[] +for begin in range(0,len(x),3): + end=begin+3;part=loss_fn(model,x[begin:end],y[begin:end],p[begin:end],paired=True) + factor=weights[begin:end].sum()/weights.sum() + (part*factor).backward();parts.append(float(part.detach()));factors.append(float(factor)) +actual=sum(a*b for a,b in zip(parts,factors));wrong=sum(parts)/len(parts) +maximum=0.;dot=norma=normb=0. +for name,value in model.named_parameters(): + a=grads[name].double();b=value.grad.double() + assert torch.isfinite(b).all(),name + maximum=max(maximum,float((a-b).abs().max())) + dot+=float((a*b).sum());norma+=float(a.square().sum());normb+=float(b.square().sum()) +cosine=dot/(norma*normb)**.5 +assert abs(float(reference.detach())-actual)<2e-6 +assert maximum<2e-5 and cosine>.999999 +assert max(factors)-min(factors)>.02 and abs(wrong-actual)>1e-4 +assert all(grads[n].norm()>0 for n in grads if n.endswith('attn.q.weight')) +result=dict(seed=967,batch=9,micro_batch=3,context=128,horizon=32,parameters=sum(v.numel() for v in model.parameters()), + full_batch_loss=float(reference.detach()),accumulated_loss=actual,incorrect_equal_microbatch_loss=wrong, + microbatch_weight_fractions=factors,maximum_gradient_difference=maximum,gradient_cosine=cosine, + all_attention_query_gradients_nonzero=True,finite_gradients=True,missing_contexts_and_targets=True, + float32_overflow_fallback_exercised=True,seconds=time.monotonic()-started,optimizer_updates=0, + validation_data_read=False,source='Own Gaussian/random-walk/sinusoid/constant fixtures; random small model and nonzero random head initialization') +(R/'accumulation_cpu_checks.json').write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/check_accumulation_gpu.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/check_accumulation_gpu.py new file mode 100644 index 0000000000000000000000000000000000000000..dad3ecb57dd86acaa01301aee5d29467b54fe567 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/check_accumulation_gpu.py @@ -0,0 +1,65 @@ +"""Compiled BF16 gradient agreement and maximum-shape accumulated training memory.""" +import fcntl,hashlib,json,sys,time +from pathlib import Path +import torch +R=Path('/workspace/research');sys.path.insert(0,str(R/'random_capacity')) +from model import DirectForecaster,loss_fn +from data import Sampler +from accumulation import context_loss_weights +started=time.monotonic();lock=open(R/'.evaluation.lock','a');tick=time.monotonic() +fcntl.flock(lock,fcntl.LOCK_EX);wait=time.monotonic()-tick +torch.set_num_threads(2);torch.manual_seed(971);torch.backends.cuda.matmul.allow_tf32=True +torch._dynamo.config.recompile_limit=64 +initial=R/'runs/random_capacity_1024/ema096000.pt' +with initial.open('rb') as f:digest=hashlib.file_digest(f,'sha256').hexdigest() +assert digest=='d7cfcd72c3cb84aa69e447b76c4c3ab98c21b7c600a463f0b805f4b4300baf33' +ck=torch.load(initial,map_location='cpu',weights_only=False) +m=DirectForecaster(**ck['config']).cuda();m.load_state_dict(ck['model']) +sampler=Sampler(R/'packed_sample',seed=971,source_weights_from=R/'packed_sample') +objective=torch.compile(loss_fn,fullgraph=True,dynamic=False) +x,y,p=[torch.from_numpy(a).cuda() for a in sampler.sample(48,512,128)] +def full(): + m.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):value=objective(m,x,y,p,paired=True) + value.backward();torch.cuda.synchronize();return float(value.detach()) +def accumulated(): + m.zero_grad(set_to_none=True);w=context_loss_weights(m,x,p);denominator=w.sum() + result=torch.zeros((),device=x.device) + for begin in range(0,len(x),16): + end=begin+16 + with torch.autocast('cuda',dtype=torch.bfloat16):value=objective(m,x[begin:end],y[begin:end],p[begin:end],paired=True) + scaled=value*(w[begin:end].sum()/denominator);scaled.backward();result=result+scaled.detach() + torch.cuda.synchronize();return float(result) +reference_loss=full();reference={k:v.grad.detach().clone() for k,v in m.named_parameters()} +def differences(): + groups={key:dict(dot=0.,reference_squared=0.,actual_squared=0.,maximum_abs_difference=0.) for key in ['all','encoder','decoder']} + for name,value in m.named_parameters(): + a=reference[name].float();b=value.grad.float();assert torch.isfinite(b).all() + keys=['all']+([name.split('.')[0]] if name.startswith(('encoder.','decoder.')) else []) + for key in keys: + row=groups[key];row['dot']+=float((a*b).sum());row['reference_squared']+=float(a.square().sum());row['actual_squared']+=float(b.square().sum());row['maximum_abs_difference']=max(row['maximum_abs_difference'],float((a-b).abs().max())) + for row in groups.values():row['gradient_cosine']=row['dot']/(row['reference_squared']*row['actual_squared'])**.5 + return groups +repeat_loss=full();repeat_difference=differences() +tick=time.monotonic();accumulated_loss=accumulated();accumulation_difference=differences();comparison_seconds=time.monotonic()-tick +assert abs(reference_loss-accumulated_loss)<.003*max(reference_loss,.1) +assert accumulation_difference['all']['gradient_cosine']>.999 +assert all(v['gradient_cosine']>.995 for v in accumulation_difference.values()) +del reference,x,y,p;m.zero_grad(set_to_none=True);torch.cuda.empty_cache() +placeholder=[torch.empty_like(v) for v in m.parameters() for _ in range(3)] +x,y,p=[torch.from_numpy(a).cuda() for a in sampler.sample(48,4096,1024)] +torch.cuda.reset_peak_memory_stats();tick=time.monotonic();maximum_loss=accumulated() +assert all(v.grad is not None and torch.isfinite(v.grad).all() for v in m.parameters()) +memory=dict(effective_batch=48,micro_batch=16,signed_rows_per_microbatch=32,context=4096,horizon=1024, + loss=maximum_loss,peak_allocated_mib=torch.cuda.max_memory_allocated()/2**20, + peak_reserved_mib=torch.cuda.max_memory_reserved()/2**20,includes_adam_and_ema_placeholders=True, + seconds=time.monotonic()-tick) +assert memory['peak_reserved_mib']<12000 +for name,value in m.state_dict().items():assert torch.equal(value.cpu(),ck['model'][name]),name +result=dict(fixture_seed=971,initial_checkpoint_sha256=digest,parameters=sum(v.numel() for v in m.parameters()), + reference_loss=reference_loss,uninterrupted_repeat_loss=repeat_loss,accumulated_loss=accumulated_loss, + uninterrupted_repeat_gradients=repeat_difference,accumulated_gradients=accumulation_difference, + compiled_microbatch_comparison_seconds=comparison_seconds,maximum_shape_memory=memory, + all_gradients_finite=True,initial_parameters_bitwise_unchanged=True,lock_wait_seconds=wait, + seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False) +(R/'accumulation_gpu_checks.json').write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/check_accumulation_recovery.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/check_accumulation_recovery.py new file mode 100644 index 0000000000000000000000000000000000000000..ca6f8f22ce8bec6d237a910b23f9519d5b1a22fd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/check_accumulation_recovery.py @@ -0,0 +1,71 @@ +"""Check effective batch, optimizer counts and complete recovery with accumulation.""" +import datetime,fcntl,hashlib,json,os,subprocess,time +from pathlib import Path +import numpy as np +import torch + +R=Path('/workspace/research');root=R/'recovery/accumulation_recovery_fixture';root.mkdir(exist_ok=False) +started=time.monotonic();lock=open(R/'.evaluation.lock','a');tick=time.monotonic() +fcntl.flock(lock,fcntl.LOCK_EX);wait=time.monotonic()-tick +env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1', + TORCHINDUCTOR_COMPILE_THREADS='2',MAX_JOBS='2',PYTHONPATH=str(R/'compiler_support'), + TRITON_CACHE_MANAGER='sibling_cache:SiblingFileCacheManager', + TRITON_CACHE_DIR='/tmp/timeseries-triton-cache',TORCHINDUCTOR_CACHE_DIR='/tmp/timeseries-inductor-cache') +initial=R/'runs/random_capacity_1024/ema096000.pt' +with initial.open('rb') as f:initial_hash=hashlib.file_digest(f,'sha256').hexdigest() +assert initial_hash=='d7cfcd72c3cb84aa69e447b76c4c3ab98c21b7c600a463f0b805f4b4300baf33' +commands=[] +def run(name,extra=(),suffix=''): + out=root/name + command=['python3',str(R/'recovery/train.py'),'--code-dir',str(R/'random_capacity'), + '--packed',str(R/'packed_sample'),'--source-weights-from',str(R/'packed_sample'), + '--out',str(out),'--initialize-from',str(initial),'--steps','6','--batch','48', + '--lr','.001','--seed','977','--loss-mode','paired','--compile-loss', + '--save-every','1000000','--micro-batch','16',*extra] + tick=time.monotonic() + with (root/(name+suffix+'.log')).open('w') as f:code=subprocess.run(command,stdout=f,stderr=subprocess.STDOUT,env=env).returncode + commands.append(dict(name=name+suffix,command=command,returncode=code,seconds=time.monotonic()-tick)) + assert code==0,(name,code) + print(json.dumps(commands[-1]),flush=True) + +run('repeat_a');run('repeat_b');run('interrupted',['--halt-after','3']) +run('interrupted',['--resume',str(root/'interrupted/recovery.pt')],suffix='_resumed') +def compare(left,right): + a=torch.load(root/left/'recovery.pt',map_location='cpu',weights_only=False,mmap=True) + b=torch.load(root/right/'recovery.pt',map_location='cpu',weights_only=False,mmap=True) + groups={} + def descend(x,y,stats): + if isinstance(x,torch.Tensor): + assert isinstance(y,torch.Tensor) and x.shape==y.shape and x.dtype==y.dtype + stats['tensor_count']+=1;stats['tensor_elements']+=x.numel() + same=torch.equal(x,y);stats['different_tensors']+=int(not same) + if x.is_floating_point() and not same: + assert torch.isfinite(x).all() and torch.isfinite(y).all() + d=(x-y).double();stats['maximum_abs_difference']=max(stats['maximum_abs_difference'],float(d.abs().max())) + stats['sum_squared_difference']+=float(d.square().sum());stats['sum_squared_reference']+=float(x.double().square().sum()) + return same + if isinstance(x,np.ndarray):return np.array_equal(x,y,equal_nan=True) + if isinstance(x,dict):return set(x)==set(y) and all([descend(x[k],y[k],stats) for k in x]) + if isinstance(x,(tuple,list)):return len(x)==len(y) and all([descend(v,w,stats) for v,w in zip(x,y)]) + return x==y + for key in ['model','ema_state','optimizer','batch_rng_state','sampler_rng_state','sampler_rng_states','torch_rng_state','cuda_rng_state','prefetched_batch','parent_checkpoints']: + stats=dict(tensor_count=0,tensor_elements=0,different_tensors=0,maximum_abs_difference=0.,sum_squared_difference=0.,sum_squared_reference=0.) + stats['bitwise_equal']=bool(descend(a[key],b[key],stats));groups[key]=stats + assert a['step']==b['step']==6 + assert a['args']['micro_batch']==b['args']['micro_batch']==16 + assert a['args']['batch']==b['args']['batch']==48 + for checkpoint in [a,b]: + assert all(float(v['step'])==6 for v in checkpoint['optimizer']['state'].values()) + assert checkpoint['prefetched_batch'][0].shape[0]==48 + return groups +comparisons={'uninterrupted_repeat':compare('repeat_a','repeat_b'), + 'uninterrupted_vs_restart':compare('repeat_a','interrupted')} +for row in comparisons.values(): + for key in ['batch_rng_state','sampler_rng_state','sampler_rng_states','torch_rng_state','cuda_rng_state','prefetched_batch','parent_checkpoints']: + assert row[key]['bitwise_equal'],key +result=dict(utc=datetime.datetime.now(datetime.timezone.utc).isoformat(),initial_checkpoint_sha256=initial_hash, + fixture_seed=977,model_parameters=146477344,batch=48,micro_batch=16,optimizer_updates=18,backward_passes=54,steps_per_trajectory=6,one_optimizer_step_per_effective_batch_verified=True, + commands=commands,comparisons=comparisons,lock_wait_seconds=wait,seconds=time.monotonic()-started, + validation_data_read=False,fixture_weights_are_not_research_candidates=True, + note='Own mature scratch checkpoint and allowed training windows only. Two independent uninterrupted runs distinguish ordinary compiled numerical variation from an interrupted3+resumed3 trajectory, with effectiveB48 and micro16 throughout. This is an engineering diagnostic, not a training recipe or model selection.') +(R/'accumulation_recovery_checks.json').write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/check_compiled_restart.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/check_compiled_restart.py new file mode 100644 index 0000000000000000000000000000000000000000..ccf17541c33dd5a4151f23b78dbb2e020de205e2 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/check_compiled_restart.py @@ -0,0 +1,66 @@ +"""Separate ordinary compiled-run repeatability from a serialized restart effect.""" +import datetime,fcntl,hashlib,json,os,subprocess,time +from pathlib import Path +import numpy as np +import torch + +R=Path('/workspace/research');root=R/'recovery/compiled_restart_fixture';root.mkdir(exist_ok=False) +started=time.monotonic();lock=open(R/'.evaluation.lock','a');tick=time.monotonic() +fcntl.flock(lock,fcntl.LOCK_EX);wait=time.monotonic()-tick +env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1', + TORCHINDUCTOR_COMPILE_THREADS='2',MAX_JOBS='2',PYTHONPATH=str(R/'compiler_support'), + TRITON_CACHE_MANAGER='sibling_cache:SiblingFileCacheManager', + TRITON_CACHE_DIR='/tmp/timeseries-triton-cache',TORCHINDUCTOR_CACHE_DIR='/tmp/timeseries-inductor-cache') +initial=R/'runs/random_capacity_1024/ema096000.pt' +with initial.open('rb') as f:initial_hash=hashlib.file_digest(f,'sha256').hexdigest() +assert initial_hash=='d7cfcd72c3cb84aa69e447b76c4c3ab98c21b7c600a463f0b805f4b4300baf33' +commands=[] +def run(name,extra=(),suffix=''): + out=root/name + command=['python3',str(R/'recovery/train.py'),'--code-dir',str(R/'random_capacity'), + '--packed',str(R/'packed_sample'),'--source-weights-from',str(R/'packed_sample'), + '--out',str(out),'--initialize-from',str(initial),'--steps','6','--batch','48', + '--lr','.001','--seed','953','--loss-mode','paired','--compile-loss', + '--save-every','1000000',*extra] + tick=time.monotonic() + with (root/(name+suffix+'.log')).open('w') as f:code=subprocess.run(command,stdout=f,stderr=subprocess.STDOUT,env=env).returncode + commands.append(dict(name=name+suffix,command=command,returncode=code,seconds=time.monotonic()-tick)) + assert code==0,(name,code) + print(json.dumps(commands[-1]),flush=True) + +run('repeat_a');run('repeat_b');run('interrupted',['--halt-after','3']) +run('interrupted',['--resume',str(root/'interrupted/recovery.pt')],suffix='_resumed') +def compare(left,right): + a=torch.load(root/left/'recovery.pt',map_location='cpu',weights_only=False,mmap=True) + b=torch.load(root/right/'recovery.pt',map_location='cpu',weights_only=False,mmap=True) + groups={} + def descend(x,y,stats): + if isinstance(x,torch.Tensor): + assert isinstance(y,torch.Tensor) and x.shape==y.shape and x.dtype==y.dtype + stats['tensor_count']+=1;stats['tensor_elements']+=x.numel() + same=torch.equal(x,y);stats['different_tensors']+=int(not same) + if x.is_floating_point() and not same: + assert torch.isfinite(x).all() and torch.isfinite(y).all() + d=(x-y).double();stats['maximum_abs_difference']=max(stats['maximum_abs_difference'],float(d.abs().max())) + stats['sum_squared_difference']+=float(d.square().sum());stats['sum_squared_reference']+=float(x.double().square().sum()) + return same + if isinstance(x,np.ndarray):return np.array_equal(x,y,equal_nan=True) + if isinstance(x,dict):return set(x)==set(y) and all([descend(x[k],y[k],stats) for k in x]) + if isinstance(x,(tuple,list)):return len(x)==len(y) and all([descend(v,w,stats) for v,w in zip(x,y)]) + return x==y + for key in ['model','ema_state','optimizer','batch_rng_state','sampler_rng_state','sampler_rng_states','torch_rng_state','cuda_rng_state','prefetched_batch','parent_checkpoints']: + stats=dict(tensor_count=0,tensor_elements=0,different_tensors=0,maximum_abs_difference=0.,sum_squared_difference=0.,sum_squared_reference=0.) + stats['bitwise_equal']=bool(descend(a[key],b[key],stats));groups[key]=stats + assert a['step']==b['step']==6 + return groups +comparisons={'uninterrupted_repeat':compare('repeat_a','repeat_b'), + 'uninterrupted_vs_restart':compare('repeat_a','interrupted')} +for row in comparisons.values(): + for key in ['batch_rng_state','sampler_rng_state','sampler_rng_states','torch_rng_state','cuda_rng_state','prefetched_batch','parent_checkpoints']: + assert row[key]['bitwise_equal'],key +result=dict(utc=datetime.datetime.now(datetime.timezone.utc).isoformat(),initial_checkpoint_sha256=initial_hash, + fixture_seed=953,model_parameters=146477344,batch=48,optimizer_updates=18,steps_per_trajectory=6, + commands=commands,comparisons=comparisons,lock_wait_seconds=wait,seconds=time.monotonic()-started, + validation_data_read=False,fixture_weights_are_not_research_candidates=True, + note='Own mature scratch checkpoint and allowed training windows only. Two independent uninterrupted runs distinguish ordinary compiled numerical variation from an interrupted3+resumed3 trajectory. This is an engineering diagnostic, not a training recipe or model selection.') +(R/'compiled_restart_checks.json').write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/distillation_error_dependence.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/distillation_error_dependence.py new file mode 100644 index 0000000000000000000000000000000000000000..6257973f88ed0749ee34130fa3b1c30ad929c74b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/distillation_error_dependence.py @@ -0,0 +1,53 @@ +"""Describe E135 median-error dependence using cached forecasts, without fitting weights.""" +import datetime, json, math, sys, time +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +from ts_io import read_prediction_file, read_truth_file + +R=Path('/workspace/research');started=time.monotonic();panels=[] +for cutoff in ['valid_screen','valid_backcast','valid_backcast2','valid_backcast3']: + control=json.loads((R/f'fresh_capacity4_ensemble_{cutoff}.json').read_text()) + candidate=json.loads((R/f'distilled48_ensemble_{cutoff}.json').read_text()) + assert control['member_checkpoint_hashes'][:3]==candidate['member_checkpoint_hashes'][:3] + members=[Path(p) for p in control['members']]+[Path(candidate['members'][3])] + hashes=control['member_checkpoint_hashes']+[candidate['member_checkpoint_hashes'][3]] + for member,expected in zip(members,hashes): + assert json.loads((member/'report.json').read_text())['checkpoint_sha256']==expected + rows=[] + for cfg in json.loads((R/cutoff/'input/index.json').read_text())['configs']: + cid=cfg['config_id'];y,scale,_=read_truth_file(R/cutoff/'truth/cases'/f'{cid}.h5') + good=np.isfinite(scale)&(scale>0);valid=np.isfinite(y)&good[...,None] + safe=np.where(good,scale,1.).astype(np.float64) + medians=[read_prediction_file(p/'cases'/f'{cid}.h5')[1][:,:,4,:].astype(np.float64) for p in members] + base=(medians[0]+medians[1]+medians[2])/3 + errors=[((q-y)/safe[...,None])[valid] for q in [base,medians[3],medians[4]]] + assert all(np.isfinite(e).all() for e in errors) + if not len(errors[0]):continue + base_mae=float(np.abs(errors[0]).mean());base_energy=float(np.dot(errors[0],errors[0])) + if base_energy==0 or any(float(np.dot(e,e))==0 for e in errors[1:]):continue + values={} + for name,e in zip(['fresh48','distilled48'],errors[1:]): + values[name]=dict(mase=float(np.abs(e).mean()), + error_cosine_with_first_three=float(np.dot(errors[0],e)/math.sqrt(base_energy*float(np.dot(e,e)))), + median_disagreement_over_base_mae=float(np.abs(e-errors[0]).mean()/base_mae)) + rows.append(dict(config_id=cid,term=cfg['term'],domain=cfg['domain'],frequency=cfg['freq'], + finite_mase_elements=len(errors[0]),first_three_mase=base_mae,**values, + distilled_minus_fresh_error_cosine=values['distilled48']['error_cosine_with_first_three']-values['fresh48']['error_cosine_with_first_three'], + distilled_minus_fresh_disagreement=values['distilled48']['median_disagreement_over_base_mae']-values['fresh48']['median_disagreement_over_base_mae'])) + groups={} + for key in ['term','domain']: + groups[key]={} + for value in sorted({row[key] for row in rows}): + selected=[row for row in rows if row[key]==value] + groups[key][value]=dict(configs=len(selected), + mean_error_cosine_delta=float(np.mean([row['distilled_minus_fresh_error_cosine'] for row in selected])), + mean_disagreement_delta=float(np.mean([row['distilled_minus_fresh_disagreement'] for row in selected]))) + panel=dict(cutoff=cutoff,configs=rows,groups=groups, + equal_configuration_mean_error_cosine_delta=float(np.mean([row['distilled_minus_fresh_error_cosine'] for row in rows])), + equal_configuration_mean_disagreement_delta=float(np.mean([row['distilled_minus_fresh_disagreement'] for row in rows]))) + panels.append(panel);print(json.dumps({k:v for k,v in panel.items() if k not in ['configs','groups']}),flush=True) +result=dict(utc=datetime.datetime.now(datetime.timezone.utc).isoformat(),panels=panels,seconds=time.monotonic()-started, + optimizer_updates=0,new_neural_inference=False,fitted_coefficients=False, + note='Validation-only descriptive comparison of the actual E135 distilled48 and E130 fresh48 fourth experts. The other three cached medians form a fixed equal mean solely as an error reference. Errors use valid MASE scales; configurations with zero error energy are excluded from cosines. Groups weight configurations equally. Higher cosine means more aligned scaled median errors; this is not a causal attribution to distillation and does not explain WQL by itself. No new forecast package, correction, selection criterion or fitted weight.') +(R/'distillation48_error_dependence.json').write_text(json.dumps(result,indent=2));print(json.dumps({k:v for k,v in result.items() if k!='panels'}),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/exposure_audit.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/exposure_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..fb67738bc9ed77f87173feda2430365e66c75966 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/exposure_audit.py @@ -0,0 +1,46 @@ +"""Describe sampled observation exposure and training invested in selected ancestry.""" +import json +import sys +import time +from pathlib import Path +import numpy as np + +R=Path('/workspace/research') +sys.path.insert(0,str(R/'random_capacity')) +from data import Sampler + +started=time.monotonic() +seed=521 +sampler=Sampler(R/'packed_sample',seed=seed,source_weights_from=R/'packed_sample') +rng=np.random.default_rng(seed) +rows=context_points=target_points=0 +for _ in range(320): + 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])) + x,y,p=sampler.sample(64,c,h) + rows+=len(x) + context_points+=int(np.isfinite(x).sum()) + target_points+=int(np.isfinite(y).sum()) +manifest=json.loads(Path('/workspace/submission/model_manifest.json').read_text()) +runs={} +for item in manifest['training_lineage']: + path=Path(item['checkpoint']) + batch=item.get('training_settings',{}).get('batch') + if path.parts[0]!='runs' or not batch: + continue + run=path.parts[1] + step=item.get('step',0) + if step>runs.get(run,{}).get('step',0): + runs[run]=dict(step=step,batch=batch,rows=step*batch,checkpoint=item['checkpoint']) +ancestral_rows=sum(v['rows'] for v in runs.values()) +mean_points=(context_points+target_points)/rows +result=dict(seed=seed,seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False, + sampled_rows=rows,mean_finite_context_points=context_points/rows, + mean_finite_target_points=target_points/rows,mean_finite_points=mean_points, + selected_descriptor=manifest['checkpoint_sha256'],ancestral_runs=runs, + selected_ancestral_rows_before_sign_pairing=ancestral_rows, + fresh96000_batch48_rows=96000*48, + fresh96000_batch48_gross_observation_presentations_estimate=96000*48*mean_points, + note='Gross sampled presentations include overlapping/resampled windows and synthetic values, not unique observations. Ancestral run maxima count compute invested in different branches, including subtracted controls; they are not an equivalent single-model training trajectory. Sign pairing duplicates compute but not distinct sampled rows. No future training recipe is inferred from this audit alone.') +(R/'training_exposure_audit.json').write_text(json.dumps(result,indent=2)) +print(json.dumps({k:v for k,v in result.items() if k!='ancestral_runs'})) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/launch_matched_cutoffs.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/launch_matched_cutoffs.py new file mode 100644 index 0000000000000000000000000000000000000000..6d33e64b8212b250fc38a2990604c80228b94c80 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/launch_matched_cutoffs.py @@ -0,0 +1,14 @@ +"""Keep evaluation controllers alive for the declared queued comparisons.""" +from pathlib import Path +import datetime,json,os,subprocess +R=Path('/workspace/research');jobs={};processes={};env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1') +for name,control,runtime,label in [('lowfreq_windows','overflow_control','postloss_inference','E113'),('seasonal_history','long_seasonal','seasonal_history_inference','E121'),('seasonal_width','seasonal_dispersion','seasonal_width_inference','E129'),('long_seasonal_replication','weekly_replication_control','long_seasonal_inference','E118'),('log_horizon','overflow_control','postloss_inference','E123')]: + path=R/(name+'_matched_cutoffs.log') + with path.open('a') as log: + command=['python3',str(R/'recovery/watch_matched_cutoffs.py'),'--run',name,'--control',control,'--evaluator',str(R/runtime/'evaluate.py'),'--label',label] + p=subprocess.Popen(command,stdout=log,stderr=subprocess.STDOUT,env=env) + processes[label]=p;jobs[label]=dict(pid=p.pid,parent_pid=os.getpid(),command=command,log=str(path),receipt=str(R/(name+'_matched_cutoffs_receipt.json'))) +q=R/'CURRENT_RESEARCH_STATE.json';state=json.loads(q.read_text());state['diagnostics']['matched_cutoff_controllers']=jobs;t=q.with_suffix('.tmp');t.write_text(json.dumps(state,indent=2));os.replace(t,q) +print(json.dumps(jobs),flush=True) +for label,p in processes.items(): + result=p.wait();print(json.dumps(dict(label=label,returncode=result)),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/matched_report.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/matched_report.py new file mode 100644 index 0000000000000000000000000000000000000000..105e5dc96b182d3cbca68c7318d6256ae739f619 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/matched_report.py @@ -0,0 +1,18 @@ +"""Record matched validation reports, including all configuration-group metrics.""" +import argparse,datetime,json,math,os +from pathlib import Path +R=Path('/workspace/research');ap=argparse.ArgumentParser() +for key in ['candidate','control','label','out']:ap.add_argument('--'+key,required=True) +ap.add_argument('--cutoffs',default='0');ap.add_argument('--outcome',required=True);a=ap.parse_args() +folders=['evals','backcast_evals','backcast2_evals','backcast3_evals'];rows=[] +for index in map(int,a.cutoffs.split(',')): + folder=folders[index];x=json.loads((R/folder/a.candidate/'report.json').read_text());y=json.loads((R/folder/a.control/'report.json').read_text()) + assert x['n_failed']==y['n_failed']==0 and x['n_configs']==y['n_configs'] + delta={g:{k:math.sqrt(y['groups'][g][k]['rel_mase_gmean']*y['groups'][g][k]['rel_wql_gmean'])-math.sqrt(v['rel_mase_gmean']*v['rel_wql_gmean']) for k,v in entries.items()} for g,entries in x['groups'].items()} + rows.append(dict(cutoff=folder,candidate_skill=x['skill_score'],control_skill=y['skill_score'],delta=x['skill_score']-y['skill_score'],candidate_checkpoint=x['checkpoint_sha256'],control_checkpoint=y['checkpoint_sha256'],candidate_eval_seconds=x.get('eval_seconds'),candidate_groups=x['groups'],control_groups=y['groups'],group_skill_delta=delta)) +result=dict(label=a.label,utc=datetime.datetime.now(datetime.timezone.utc).isoformat(),candidate=a.candidate,control=a.control,rows=rows,mean_delta=sum(v['delta'] for v in rows)/len(rows),positive_cutoffs=sum(v['delta']>0 for v in rows),outcome=a.outcome) +p=Path(a.out);assert not p.exists(),'Refuse duplicate comparison record' +temporary=p.with_name(p.name+'.'+str(os.getpid())+'.tmp') +temporary.write_text(json.dumps(result,indent=2));os.replace(temporary,p) +with (R/'direct_v1/EXPERIMENTS.md').open('a') as f:f.write('\n'+a.label+': '+json.dumps(result)+'\n') +print(json.dumps({k:v for k,v in result.items() if k!='rows'})) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/median_error_structure.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/median_error_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..83bb24d13841f0266d0947799c682f47e8641474 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/median_error_structure.py @@ -0,0 +1,30 @@ +"""Describe validation median errors without fitting or proposing corrected forecasts.""" +import argparse,json,sys,time +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +from ts_io import read_prediction_file,read_truth_file +ap=argparse.ArgumentParser() +for n in ['valid','pred','report','out']:ap.add_argument('--'+n,required=True) +a=ap.parse_args();start=time.monotonic();root=Path(a.valid);report=json.loads(Path(a.report).read_text());rows=[] +for cfg in report['configs']: + cid=cfg['config_id'];y,scale,_=read_truth_file(root/'truth/cases'/(cid+'.h5'));_,q=read_prediction_file(Path(a.pred)/'cases'/(cid+'.h5')) + good=np.isfinite(scale)&(scale>0);valid=np.isfinite(y)&good[...,None];safe=np.where(good,scale,1).astype(np.float64) + err=np.where(valid,(q[:,:,4,:].astype(np.float64)-y.astype(np.float64))/safe[...,None],0.) + n=valid.sum(-1);total=int(n.sum());mae=float(np.abs(err).sum()/total) + signed=float(err.sum()/total);absolute_window_mean=float(np.abs(err.sum(-1)).sum()/total) + assert absolute_window_mean<=mae+1e-10 + lead=[] + for positions in np.array_split(np.arange(y.shape[-1]),4): + mask=valid[...,positions];count=int(mask.sum());values=err[...,positions] + lead.append(dict(count=count,mase=float(np.abs(values).sum()/count),signed_scaled_error=float(values.sum()/count))) + rows.append(dict(config_id=cid,term=cfg['term'],domain=cfg['domain'],frequency=cfg['freq'],horizon=cfg['prediction_length'],mase=mae,scorer_mase=cfg['metrics']['mase'],signed_scaled_error=signed,absolute_window_mean_error=absolute_window_mean,window_mean_error_fraction_of_mae=absolute_window_mean/max(mae,1e-30),lead_quarters=lead)) + assert abs(mae-cfg['metrics']['mase'])<1e-6*max(1,mae) +groups={} +for key in ['term','domain','frequency']: + groups[key]={} + for value in sorted({row[key] for row in rows}): + selected=[row for row in rows if row[key]==value] + groups[key][value]=dict(configs=len(selected),mean_window_mean_error_fraction=float(np.mean([row['window_mean_error_fraction_of_mae'] for row in selected])),mean_signed_error_over_mae=float(np.mean([row['signed_scaled_error']/max(row['mase'],1e-30) for row in selected])),mean_lead_quarter_mase_ratio=[float(np.mean([row['lead_quarters'][i]['mase']/max(row['mase'],1e-30) for row in selected])) for i in range(4)]) +result=dict(checkpoint_sha256=report['checkpoint_sha256'],groups=groups,configs=rows,seconds=time.monotonic()-start,optimizer_updates=0,new_inference=False,note='Validation-only descriptive analysis. Absolute per-window mean error is a Jensen lower bound on MAE, not a recoverable correction or attributable causal component. Groups average configurations equally; lead ratios are descriptive, not the benchmark metric. No parameter fitting or forecast modification.') +Path(a.out).write_text(json.dumps(result,indent=2));print(json.dumps({k:v for k,v in result.items() if k!='configs'})) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/pack_composition.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/pack_composition.py new file mode 100644 index 0000000000000000000000000000000000000000..0a023de983f7c0860043b58def56406e3fd27eb9 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/pack_composition.py @@ -0,0 +1,32 @@ +"""Read-only comparison of source/length composition in the two allowed packs.""" +import json,time +from pathlib import Path +import numpy as np +R=Path('/workspace/research');started=time.monotonic();old=R/'packed_sample';new=R/'packed_stratified_full' +a=json.loads((old/'meta.json').read_text());b=json.loads((new/'meta.json').read_text());assert a['dirs']==b['dirs'];names=a['dirs'] +weights=[] +for n in names: + w=min((old/(n+'.bin')).stat().st_size//4,20000000)**.25 + if n.startswith(('era5_','cmip6_')):w*=.35 + if n.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) +weights=np.array(weights)/sum(weights);bins=np.array([16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131073]) +rows=[];aggregate={k:np.zeros(len(bins)-1) for k in ['old','full']} +for n,w in zip(names,weights): + row={'source':n,'conditional_real_source_probability':float(w)} + for k,root in [('old',old),('full',new)]: + lengths=np.diff(np.load(root/(n+'.offsets.npy'),mmap_mode='r')) + hist=np.histogram(lengths,bins=bins)[0]/len(lengths);aggregate[k]+=w*hist + row[k]={'series':len(lengths),'points':int(lengths.sum()),'mean_length':float(lengths.mean()),'median_length':float(np.median(lengths)), + 'fraction_below64':float(np.mean(lengths<64)),'fraction_below256':float(np.mean(lengths<256)), + 'fraction_at_least20480':float(np.mean(lengths>=20480)),'length_bin_probabilities':hist.tolist()} + row['weighted_length_distribution_l1']=float(w*np.abs(np.array(row['old']['length_bin_probabilities'])-row['full']['length_bin_probabilities']).sum()) + row['mixed_frequency_rows_in_full']=b['receipts'][n]['mixed_frequency_rows_in_candidates'];row['full_frequencies']=b['receipts'][n]['kept_frequencies'];rows.append(row) +result=dict(kind='per-source uniform-series sampling composition; no series values or validation labels read', + length_bins=bins.tolist(),conditional_real_length_bin_probabilities={k:v.tolist() for k,v in aggregate.items()}, + source_probabilities_unchanged=True,min_length_both=16,max_crop_length_both=131072, + mixed_frequency_sources=[r['source'] for r in rows if r['mixed_frequency_rows_in_full']],sources=rows, + seconds=time.monotonic()-started,optimizer_updates=0) +(R/'pack_composition_comparison.json').write_text(json.dumps(result,indent=2)) +print(json.dumps({k:v for k,v in result.items() if k!='sources'})) +for row in sorted(rows,key=lambda r:-r['weighted_length_distribution_l1'])[:12]:print(json.dumps({k:v for k,v in row.items() if k not in ['old','full']},separators=(',',':')), 'mean_length',row['old']['mean_length'],row['full']['mean_length']) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/pack_exposure.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/pack_exposure.py new file mode 100644 index 0000000000000000000000000000000000000000..055a8c72cbff23c87dcb4d2fd3198d7a2a0d9f65 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/pack_exposure.py @@ -0,0 +1,30 @@ +"""Measure observation presentations under the two unchanged fresh-model samplers.""" +import datetime,json,sys,time +from pathlib import Path +import numpy as np +R=Path('/workspace/research');sys.path.insert(0,str(R/'random_capacity')) +from data import Sampler +started=time.monotonic();seed=943;results=[] +for pack in ['packed_sample','packed_stratified_full']: + sampler=Sampler(R/pack,seed=seed,source_weights_from=R/'packed_sample') + shape_rng=np.random.default_rng(seed);context_counts=[];target_counts=[];batch_means=[] + for _ in range(384): + c=int(shape_rng.choice([512,1024,2048,4096],p=[.1,.15,.35,.4])) + h=int(shape_rng.choice([32,128,512,1024],p=[.1,.2,.2,.5])) + x,y,periods=sampler.sample(64,c,h) + nc=np.isfinite(x).sum(-1);nh=np.isfinite(y).sum(-1) + context_counts.extend(nc.tolist());target_counts.extend(nh.tolist()) + batch_means.append(float((nc+nh).mean())) + nc=np.array(context_counts);nh=np.array(target_counts);total=nc+nh + result=dict(pack=pack,sampled_rows=len(total),mean_finite_context=float(nc.mean()), + mean_finite_target=float(nh.mean()),mean_finite_total=float(total.mean()), + batch_mean_monte_carlo_standard_error=float(np.std(batch_means,ddof=1)/np.sqrt(len(batch_means))), + fraction_target_le32=float(np.mean(nh<=32)),fraction_target_ge480=float(np.mean(nh>=480)), + fraction_target_ge720=float(np.mean(nh>=720)),fraction_target_ge900=float(np.mean(nh>=900)), + finite_target_length_quantiles=np.quantile(nh,[0,.1,.25,.5,.75,.9,1]).tolist(), + estimated_presentations_at96000_B48=float(96000*48*total.mean())) + results.append(result);print(json.dumps(result),flush=True);del sampler +receipt=dict(utc=datetime.datetime.now(datetime.timezone.utc).isoformat(),seed=seed, + rows=results,seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False, + note='Read-only Monte Carlo exposure under unchanged source probabilities and20percent own synthetic data. Counts are gross finite observation presentations before sign pairing, with overlap/resampling; not unique observations. Same shape draws but source streams can diverge with pack-dependent length and aggregation decisions. Standard errors describe batch-shape Monte Carlo variability, not forecasting uncertainty. No training or allocation change.') +(R/'pack_exposure_comparison.json').write_text(json.dumps(receipt,indent=2)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/quantile_coverage.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/quantile_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..d7f4958ae772a15c4a580eed59bb9257b065154d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/quantile_coverage.py @@ -0,0 +1,59 @@ +"""Validation-only quantile coverage, with separate strict/inclusive coverage at atoms.""" +import argparse +import json +import sys +import time +from pathlib import Path + +import numpy as np + +sys.path.insert(0,'/workspace/evaluation') +from ts_io import read_prediction_file, read_truth_file + +parser = argparse.ArgumentParser() +parser.add_argument('--valid',required=True) +parser.add_argument('--pred',required=True) +parser.add_argument('--report',required=True) +parser.add_argument('--out',required=True) +args = parser.parse_args() +started = time.monotonic() +root = Path(args.valid) +index = json.loads((root/'input/index.json').read_text()) +report = json.loads(Path(args.report).read_text()) +levels = np.arange(1,10)/10 +rows = [] +for cfg in index['configs']: + relative = Path('cases')/(cfg['config_id']+'.h5') + y,scale,_ = read_truth_file(root/'truth'/relative) + _,q = read_prediction_file(Path(args.pred)/relative) + valid = np.isfinite(y) + assert q.shape==(*y.shape[:2],9,y.shape[-1]) and np.isfinite(q).all() + count = int(valid.sum()) + assert count>0 + strict = ((y[:,:,None,:] 200*2**30 +old = {n:json.loads((R/f'{n}_queue.json').read_text()) for n in ACTIVE+list(DEPENDENCIES)} +backup = R/'incidents/storage_recovery_20261023' +backup.mkdir(parents=True, exist_ok=True) +for name in old: + shutil.copy2(R/f'{name}_queue.json', backup/f'{name}_queue.json') + config = R/'runs'/name/'config.json' + if config.exists(): shutil.copy2(config, backup/f'{name}_config.json') + for temporary in (R/'runs'/name).glob('*.tmp'): + destination = backup/name/temporary.name + destination.parent.mkdir(exist_ok=True) + shutil.move(str(temporary), str(destination)) + +receipt = dict(utc=datetime.datetime.now(datetime.timezone.utc).isoformat(), + reason='operator storage recovery; all old processes ended', + checkpoint_audit=str(R/'recovery4_checkpoint_audit.json'), + budget='Externally enforced original budget preserved; operator downtime excluded, no new allowance inferred.', + jobs={}, controllers={}) +children = {} + +def persist(): + temporary = receipt_path.with_suffix('.tmp') + temporary.write_text(json.dumps(receipt, indent=2)) + os.replace(temporary, receipt_path) + +def launch(name, command, kind): + log = R/f'{name}_{TAG}.log' + assert not log.exists(), log + with log.open('w') as handle: + child = subprocess.Popen(command, stdout=handle, stderr=subprocess.STDOUT, env=env) + children[name] = child + item = dict(pid=child.pid, command=command, log=str(log), started_monotonic=time.monotonic()) + receipt[kind][name] = item + persist() + print(json.dumps(dict(name=name, pid=child.pid, kind=kind)), flush=True) + return child + +for name in ACTIVE+list(DEPENDENCIES): + command = list(old[name]['command']) + assert command[command.index('--out')+1] == str(R/'runs'/name) + assert '--resume' not in command and '--compile-teacher' not in command + assert not Path(command[command.index('--stop-file')+1]).exists() + if name in ACTIVE: + command += ['--resume', str(R/'runs'/name/'recovery.pt')] + required = [str(R/'runs'/name/'recovery.pt')] + else: + assert not (R/'runs'/name/'recovery.pt').exists() + required = old[name]['required_checkpoints'] + args = ['python3', str(R/'queued_train.py'), '--label', old[name]['label']+' storage recovery', + '--log', str(R/f'{name}_train_{TAG}.log'), '--receipt', str(R/f'{name}_queue.json')] + for dependency in DEPENDENCIES.get(name, []): + args += ['--wait-pid', str(children[dependency].pid)] + for path in required: args += ['--require-checkpoint', path] + launch(name, args+['--']+command, 'jobs') + +wide_steps = '4000,8000,16000,24000,48000,72000,96000' +short_steps = '1000,3000,6000,12000' +for name in old: + runtime = 'random_capacity_inference' + steps = wide_steps + if name == 'random_capacity_long_seasonal': runtime = name+'_inference' + if name == 'ensemble_gate': runtime = name; steps = short_steps + if name.startswith('capacity_patch8_'): steps = short_steps + if name == 'lowfreq_age': runtime = 'postloss_inference'; steps = short_steps + if name == 'direct_trend_replication': runtime = 'direct_trend_head_inference'; steps = short_steps + if name == 'visibility_curriculum': steps = '16000,32000,48000,72000,96000' + command = old[name]['command'] + packed = command[command.index('--packed')+1] + launch(name+'_watch', ['python3', str(R/'watch_evaluate.py'), '--run', str(R/'runs'/name), + '--evaluator', str(R/runtime/'evaluate.py'), '--name', name, + '--expected-packed', packed, '--steps', steps], 'controllers') + +matched = [ + ('random_capacity_full','random_capacity_1024_halflr','random_capacity_inference','random_capacity_inference','E110','48000,96000'), + ('random_capacity_original_ar','random_capacity_1024','random_capacity_inference','random_capacity_inference','E122','48000,96000'), + ('random_capacity_long_seasonal','random_capacity_1024','random_capacity_long_seasonal_inference','random_capacity_inference','E131','48000,96000'), + ('capacity_patch8_candidate','capacity_patch8_control','random_capacity_inference','random_capacity_inference','E141','6000,12000'), + ('visibility_curriculum','random_capacity_1024','random_capacity_inference','random_capacity_inference','E134','48000,96000'), + ('random_capacity_deep','random_capacity_1024','random_capacity_inference','random_capacity_inference','E137','48000,96000'), + ('lowfreq_age','lowfreq_windows','postloss_inference','postloss_inference','E143','6000,12000'), + ('random_capacity_buildings','random_capacity_full','random_capacity_inference','random_capacity_inference','E145','48000,96000'), + ('direct_trend_replication','long_seasonal_replication','direct_trend_head_inference','long_seasonal_inference','E146','6000,12000'), + ('random_capacity_full_highlr','random_capacity_full','random_capacity_inference','random_capacity_inference','E147','48000,96000'), +] +for name,control,runtime,control_runtime,label,steps in matched: + launch(name+'_matched', ['python3',str(R/'recovery/watch_matched_cutoffs.py'), + '--run',name,'--control',control,'--evaluator',str(R/runtime/'evaluate.py'), + '--control-evaluator',str(R/control_runtime/'evaluate.py'), + '--label',label,'--steps',steps], 'controllers') +for name,script in [('gate_selection','ensemble_gate/watch_selection.py'), + ('distilled_fourth_selection','distilled_fourth_member/run.py'), + ('lowfreq_age_reference','lowfreq_age/watch_reference.py')]: + launch(name, ['python3',str(R/script)], 'controllers') + +with (R/'direct_v1/EXPERIMENTS.md').open('a') as f: + f.write('\n'+receipt['utc']+': Storage recovery4: six complete optimizer/EMA/RNG/prefetch states restored; original recipes and endpoint schedules unchanged. Checkpoint audit '+json.dumps(audit)+'. Queued dependencies rewired to new live queue PIDs. Incomplete .tmp files quarantined; no model state inferred from them. All selected weights preserved. Original externally enforced research budget remains authoritative; operator downtime is not research compute.\n') +while any(child.poll() is None for child in children.values()): + for kind in ['jobs','controllers']: + for name,item in receipt[kind].items(): + code = children[name].poll() + if code is not None and 'returncode' not in item: + item.update(returncode=code, phase_seconds=time.monotonic()-item['started_monotonic']) + persist() + print(json.dumps(dict(name=name,returncode=code)),flush=True) + time.sleep(5) +persist() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/schedules.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/schedules.py new file mode 100644 index 0000000000000000000000000000000000000000..4c8378f374144b802d2cd5a98afd71efc1ba0a4c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/schedules.py @@ -0,0 +1,13 @@ +"""Explicit training-only learning-rate schedules; default arithmetic unchanged.""" +import math + + +def learning_rate(step, steps, peak, reset_at=-1, anneal_from_step=None, + anneal_from_lr=None, anneal_final_lr=None): + if anneal_from_step is not None: + assert steps > anneal_from_step + assert 0 < anneal_final_lr <= anneal_from_lr + progress=max(0.,min(1.,(step-anneal_from_step)/(steps-anneal_from_step))) + return anneal_final_lr+.5*(anneal_from_lr-anneal_final_lr)*(1+math.cos(math.pi*progress)) + warm_step=step-reset_at if reset_at>=0 and step>reset_at else step + return peak*min(1,warm_step/400)*(.2+.4*(1+math.cos(math.pi*step/steps))) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/seasonal_history_support.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/seasonal_history_support.py new file mode 100644 index 0000000000000000000000000000000000000000..84314b30b22a4a761447fc5ee1cffb9301e725b9 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/seasonal_history_support.py @@ -0,0 +1,23 @@ +"""Context-metadata diagnostic of potential 8-cycle support, with no targets read.""" +import importlib.util,json,time +from pathlib import Path +import h5py,numpy as np +R=Path('/workspace/research');started=time.monotonic() +spec=importlib.util.spec_from_file_location('support_model',R/'long_seasonal/model.py');m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m) +root=Path('/workspace/data/valid/input');index=json.loads((root/'index.json').read_text());rows=[] +for cfg in index['configs']: + with h5py.File(root/'cases'/(cfg['config_id']+'.h5'),'r') as f:lengths=np.asarray(f['context_length']) + h=cfg['prediction_length'];periods=m.periods_for_freq(cfg['freq']);row={k:cfg[k] for k in ['config_id','freq','term','domain']};row['periods']=periods;row['n_instances']=len(lengths) + for cap in [4096,16384]: + support=[];cycles=[] + for p in periods: + count=np.clip(1+(np.minimum(lengths,cap)[:,None]-p+np.arange(h)[None,:]%p)//p,0,16) + support.append(float(np.mean((count>=8)&(p>=2))));cycles.append(float(np.mean(np.where(p>=2,count,0)))) + row[str(cap)]={'phase_support_fraction':support,'mean_available_cycles':cycles} + row['support_gain_sum']=sum(row['16384']['phase_support_fraction'])-sum(row['4096']['phase_support_fraction']);rows.append(row) +changed=[r for r in rows if r['support_gain_sum']>0] +result=dict(kind='optimistic potential support before missing-value masks; not measured forecast improvement',input_metadata_only=True,validation_targets_read=False,optimizer_updates=0,configs=rows, + changed_configurations=len(changed),changed_domains=sorted(set(r['domain'] for r in changed)),seconds=time.monotonic()-started) +(R/'seasonal_history_support.json').write_text(json.dumps(result,indent=2)) +print(json.dumps({k:v for k,v in result.items() if k!='configs'})) +for r in sorted(changed,key=lambda x:x['support_gain_sum'],reverse=True)[:20]:print(json.dumps(r)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/snapshot.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/snapshot.py new file mode 100644 index 0000000000000000000000000000000000000000..b488ad815b323f842244d70c04226dddc320caa5 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/snapshot.py @@ -0,0 +1,99 @@ +"""Write a compact authoritative research recovery index without touching training state.""" +import datetime +import json +import os +from pathlib import Path + +R=Path('/workspace/research');p=R/'CURRENT_RESEARCH_STATE.json' +s=json.loads(p.read_text()) +s['snapshot_utc']=datetime.datetime.now(datetime.timezone.utc).isoformat() +receipt=json.loads((R/'recovery3_launch_receipt.json').read_text()) +s['runs']={} +for name,job in receipt['jobs'].items(): + run=R/'runs'/name + log=Path(job['log']) + records=[] + for line in log.read_text().splitlines(): + try: + record=json.loads(line) + if 'step' in record or 'completed_step' in record:records.append(record) + except json.JSONDecodeError:pass + s['runs'][name]={'config':json.loads((run/'config.json').read_text()) if (run/'config.json').exists() else None, + 'last_phase_record':records[-1] if records else None, + 'phase_log':str(log),'supervisor_receipt':str(R/'recovery3_launch_receipt.json'), + 'latest_saved_ema':str(max(run.glob('ema*.pt'))) if list(run.glob('ema*.pt')) else None, + 'complete_recovery_checkpoint':str(run/'recovery.pt') if (run/'recovery.pt').exists() else None, + 'pid_at_snapshot':job['pid'],'returncode':job.get('returncode'), + 'note':'Check actual live process and checkpoint state before resuming; this is only a snapshot.'} +s['queues']={name:{'status':q['status'],'dependency':q['dependency'],'command':q['command'], + 'required_checkpoints':q['required_checkpoints']} + for name,q in receipt['queues'].items()} +s.pop('prepared_not_launched',None) +s['deferred_unqueued']={'E72':'temporal_mixup, prepared and checked but not queued','ideas':'RESEARCH_IDEAS.md, no jobs attached'} +s['completed_since_previous_recovery']={ + 'E67_control12000':{'skill':.37724286394256845,'training_loop_seconds':2794.8358458959847}, + 'E67_paired12000':{'skill':.377427077277383,'training_loop_seconds':2794.867385860998}, + 'E63_expanded146M':'Stopped8501, complete recovery retained; allocation moved to E73; inconclusive data scaling', + 'E61_slowAR':'Complete12000; E76 used6000 correction, final transfer rejected', + 'E65_recent_normalization':'Complete12000; E81 equal ensemble rejected', + 'E58_small_control':'Complete32000', + 'E58_wide146M':'Complete32000; no gain over37Mcontrol; do not resume', + 'E71_patch8':'Complete12000; selected6000 used in E87/E96/E102 ensembles', + 'E69_volatility':'Complete12000; final below matched control; no transfer', + 'E89_patch8_control':'Complete12000; final0.380847096,loop2729.052105s; selected starting E71parent remains stronger', + 'E89_fullpatch4':'Complete12000,main0.381640078; E96 used6000, E103final cached alternative mixed; loop5066.016522s', + 'E93_split_patch':'Complete12000,main0.381711986; selected final is E102 published thirdmember; loop3153.565149s', + 'E92_robust_normalization':'Complete12000,final0.377099312 belowcontrol; rejected;E97started', + 'E90_metric_scale':'Complete12000; final0.377373344 ties/slightly trailsE80; no selection; loop2702.166704s', + 'E84_coarse':'Complete12000; daily gain but weekly regression; not selected', + 'E88_late_patch8_slowAR':'Complete12000; small9k gain lost atfinal; rejected', + 'E80_overflow':'Complete12000; finaltiesoriginal; selected3k compositeE91rejected', + 'E78_multiscaleAR':'Complete12000; no gain over single slowAR', + 'E86_protected_graft':'Complete8000; below own initialization; no publication', + 'E75_postloss':'Stopped3653 deliberately; immutable snapshot retained; E98 separately declared completion active in another output, original stopfile remains', + 'E73_independent_graft':'Stopped8683 after negative8000; replaced by E86; stopfile remains', + 'E95_stratified_corpus':'Complete12000,final0.377983250,earliermixed; E105collision destroyed only1000weights and optimizer recovery;2k..12k preserved; do not resume', + 'E97_weekly_synth':'Complete12000,final0.380439539; E112final weekly correction now published; loop2600.472750s', + 'E105_stratified_volume':'Complete12000,final0.377529200,earlier0.336713522/0.359535697/0.390349158 mixed; corrected continuationloop2013.982814s plus original incident phase', + 'E106_spectral_synth':'Complete12000,final0.377641399,earlier0.337647555/0.361626447/0.385497870, average matched gap negligible; loop2206.272278s; E114fixed6000transfers in selection', + 'E98_postloss_completion':'Complete12000,final0.376034254 below3000 andcontrol; rejected,loop1995.386513s', + 'E99_early_cooldown':'Complete36000,final0.363306598 trails original36k0.364859034; rejected,loop1603.635706s', + 'E77_pairedslowAR':'Complete12000;6000 strongest main/earlier comparison'} +s['external_receipts']=[str(R/'postloss_recovery3_receipt.json'),str(R/'random_capacity_512_queue.json'),str(R/'random_capacity_1024_queue.json'),str(R/'multiscale_ar_queue.json'),str(R/'overflow_control_queue.json'),str(R/'coarse_aggregate_queue.json'),str(R/'patch8_long_memory_queue.json'),str(R/'wide_graft_frozen_queue.json'),str(R/'patch4_candidate_queue.json'),str(R/'patch4_control_queue.json'),str(R/'metric_scale_queue.json'),str(R/'robust_normalization_queue.json'),str(R/'split_patch_queue.json'),str(R/'random_capacity_1024_halflr_queue.json'),str(R/'stratified_corpus_queue.json'),str(R/'weekly_synth_queue.json'),str(R/'postloss_completion_queue.json'),str(R/'random_capacity_512_anneal_queue.json'),str(R/'distill_ensemble_queue.json'),str(R/'stratified_volume_queue.json'),str(R/'spectral_synth_queue.json'),str(R/'long_seasonal_queue.json'),str(R/'random_capacity_full_queue.json'),str(R/'weekly_replication_control_queue.json'),str(R/'weekly_replication_candidate_queue.json'),str(R/'lowfreq_windows_queue.json'),str(R/'phase_joint_queue.json'),str(R/'long_seasonal_replication_queue.json'),str(R/'seasonal_dispersion_queue.json'),str(R/'seasonal_history_queue.json'),str(R/'random_capacity_original_ar_queue.json'),str(R/'log_horizon_queue.json'),str(R/'compiled_teacher_trial_queue.json'),str(R/'seasonal_width_queue.json'),str(R/'random_capacity_long_seasonal_queue.json'),str(R/'visibility_curriculum_queue.json'),str(R/'direct_trend_head_queue.json'),str(R/'random_capacity_deep_queue.json'),str(R/'ensemble_gate_queue.json'),str(R/'capacity_patch8_control_queue.json'),str(R/'capacity_patch8_candidate_queue.json'),str(R/'lowfreq_age_queue.json'),str(R/'random_capacity_buildings_queue.json'),str(R/'direct_trend_replication_queue.json'),str(R/'random_capacity_full_highlr_queue.json'),str(R/'integrated_level_queue.json'),str(R/'ensemble_gate_refresh_queue.json'),str(R/'ensemble_gate_full_queue.json'),str(R/'ensemble_gate_refresh_full_queue.json'),str(R/'random_capacity_1536_queue.json'),str(R/'random_capacity_long_seasonal_halflr_queue.json'),str(R/'random_capacity_long_seasonal_distill_queue.json'),str(R/'random_capacity_seasonal_width_queue.json')] +queue_pids={'random_capacity_512_queue.json':965,'random_capacity_1024_queue.json':967, + 'multiscale_ar_queue.json':1678,'overflow_control_queue.json':1676, + 'coarse_aggregate_queue.json':3086,'patch8_long_memory_queue.json':3739, + 'wide_graft_frozen_queue.json':3931,'patch4_candidate_queue.json':4078, + 'patch4_control_queue.json':4080} +s['external_jobs']={} +for receipt_name in s['external_receipts']: + receipt_path=Path(receipt_name) + if not receipt_path.exists():continue + item=json.loads(receipt_path.read_text());command=item.get('command',[]) + if '--out' not in command:continue + run=Path(command[command.index('--out')+1]);log=Path(item.get('log',str(receipt_path).replace('_queue.json','_train.log'))) + last=None + if log.exists(): + for line in log.read_text().splitlines(): + try: + record=json.loads(line) + if isinstance(record,dict) and ('step' in record or 'completed_step' in record):last=record + except json.JSONDecodeError:pass + queue_pid=item.get('launcher_pid',queue_pids.get(receipt_path.name)) + children_file=Path(f'/proc/{queue_pid}/task/{queue_pid}/children') if queue_pid else None + children=list(map(int,children_file.read_text().split())) if children_file and children_file.exists() else [] + checkpoints=list(run.glob('ema*.pt')) + s['external_jobs'][run.name]={'receipt':str(receipt_path),'status':item.get('status'), + 'queue_pid_at_snapshot':queue_pid,'child_pids_at_snapshot':children, + 'last_phase_record':last,'log':str(log), + 'latest_saved_ema':str(max(checkpoints)) if checkpoints else None, + 'complete_recovery_checkpoint':str(run/'recovery.pt') if (run/'recovery.pt').exists() else None, + 'command':command,'note':'PIDs are only a snapshot; check actual processes and serialized state before recovery.'} +s['compiler_environment']={'OPENBLAS_NUM_THREADS':'1','OMP_NUM_THREADS':'1','TORCHINDUCTOR_COMPILE_THREADS':'2','MAX_JOBS':'2','PYTHONPATH':str(R/'compiler_support'),'TRITON_CACHE_MANAGER':'sibling_cache:SiblingFileCacheManager','TRITON_CACHE_DIR':'/tmp/timeseries-triton-cache','TORCHINDUCTOR_CACHE_DIR':'/tmp/timeseries-inductor-cache'} +for job in s['external_jobs'].values(): + job['environment']=s['compiler_environment'] if '--compile-loss' in job['command'] else {'OPENBLAS_NUM_THREADS':'1','OMP_NUM_THREADS':'1'} +s['compiler_cache_backup']=str(R/'compiler_cache_backup') +for stale in ['pending','pending_actions','active_experiments','next_experiments','prepared_experiments']: + s.pop(stale,None) +tmp=p.with_suffix('.tmp');tmp.write_text(json.dumps(s,indent=2));os.replace(tmp,p) +print(s['snapshot_utc']) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/synthetic_window_audit.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/synthetic_window_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..5a6455bbd9926f9d342ee1a24ca825328a9e7e1f --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/synthetic_window_audit.py @@ -0,0 +1,63 @@ +"""Compare actual allowed/synthetic training-window dynamics without validation data.""" +import datetime +import json +from pathlib import Path +import sys +import time +import types +import numpy as np + +R=Path('/workspace/research') +sys.path.insert(0,str(R/'overflow_control')) +source=(R/'overflow_control/data.py').read_text() +needle='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)' +assert source.count(needle)==1 +instrumented=source.replace(needle,needle+';self.audit_synthetic=np.zeros(batch,bool)') +needle='if r.random()=16 and len(target)>=4: + k=min(16,n//4,len(target)) + # Descriptive finite-observation means, not a proposed inference feature. + scale=max(float(np.std(values)),float(np.mean(np.abs(values)))*1e-4,1e-4) + past=(float(np.mean(values[-k:]))-float(np.mean(values[-2*k:-k])))/scale + future=(float(np.mean(target[:k].astype(np.float64)))-float(np.mean(values[-k:])))/scale + item.update(past_change=float(np.clip(past,-20,20)),future_change=float(np.clip(future,-20,20))) + groups.setdefault(frequency+'_'+kind,[]).append(item);counts+=1 +summary={} +for name,rows in groups.items(): + c=np.array([x['context'] for x in rows]);h=np.array([x['target'] for x in rows]) + valid=[x for x in rows if x['past_change'] is not None] + past=np.array([x['past_change'] for x in valid]);future=np.array([x['future_change'] for x in valid]) + summary[name]=dict(rows=len(rows),median_finite_context=float(np.median(c)), + context_at_most128=float(np.mean(c<=128)),context_above512=float(np.mean(c>512)), + median_finite_target=float(np.median(h)),dynamic_rows=len(valid), + median_abs_recent_change=float(np.median(np.abs(past))), + median_abs_future_change=float(np.median(np.abs(future))), + recent_future_change_correlation=float(np.corrcoef(past,future)[0,1])) +result=dict(seed=seed,rows=counts,batches=160,groups=summary,seconds=time.monotonic()-started, + generated_utc=datetime.datetime.now(datetime.timezone.utc).isoformat(), + instrumentation_first640_rows_and_rng_bitwise=True,optimizer_updates=0, + validation_data_read=False,decision='Descriptive audit only. E113 remains unchanged; no new generator selected.') +(R/'synthetic_window_audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/train.py new file mode 100644 index 0000000000000000000000000000000000000000..04d49e22ac7242f74d2d89ea9b7d30353f1d02a9 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/train.py @@ -0,0 +1,306 @@ +"""Resumable continuation of our existing permitted-corpus experiments.""" +import argparse,copy,fcntl,inspect,json,math,os,sys,time +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +# Future queued jobs may inherit only the shell's minimal environment. Keep the +# audited compilation/cache setup explicit before torch or its workers import it. +if '--compile-loss' in sys.argv: + _compiler_environment = dict( + TORCHINDUCTOR_COMPILE_THREADS='2', MAX_JOBS='2', + PYTHONPATH=str(Path(__file__).parent.parent/'compiler_support'), + TRITON_CACHE_MANAGER='sibling_cache:SiblingFileCacheManager', + TRITON_CACHE_DIR='/tmp/timeseries-triton-cache', + TORCHINDUCTOR_CACHE_DIR='/tmp/timeseries-inductor-cache') + os.environ.update(_compiler_environment) + sys.path.insert(0, _compiler_environment['PYTHONPATH']) +import numpy as np +import torch + +ap=argparse.ArgumentParser() +ap.add_argument('--code-dir',required=True);ap.add_argument('--packed',required=True) +ap.add_argument('--source-weights-from');ap.add_argument('--out',required=True) +ap.add_argument('--initialize-from',required=True);ap.add_argument('--initialize-ema') +ap.add_argument('--start-step',type=int,default=0);ap.add_argument('--resume') +ap.add_argument('--steps',type=int,required=True);ap.add_argument('--batch',type=int,required=True) +ap.add_argument('--lr',type=float,required=True);ap.add_argument('--seed',type=int,required=True) +ap.add_argument('--context',type=int);ap.add_argument('--sample-context',type=int,default=4096) +ap.add_argument('--save-every',type=int,default=1000);ap.add_argument('--stop-file') +ap.add_argument('--recovery-every',type=int,default=250) +ap.add_argument('--halt-after',type=int) +ap.add_argument('--loss-mode',choices=['individual','paired']) +ap.add_argument('--compile-loss',action='store_true') +ap.add_argument('--reset-at',type=int,default=-1);ap.add_argument('--reset-seed',type=int,default=179) +ap.add_argument('--anneal-from-step',type=int);ap.add_argument('--anneal-from-lr',type=float) +ap.add_argument('--anneal-final-lr',type=float) +ap.add_argument('--teacher-package');ap.add_argument('--teacher-coefficient',type=float) +ap.add_argument('--compile-teacher',action='store_true') +ap.add_argument('--visibility-curriculum',action='store_true') +ap.add_argument('--gate-package') +ap.add_argument('--micro-batch',type=int) +a=ap.parse_args() +# Hold a process-lifetime lock before loading a model or touching GPU state. +_run_out=Path(a.out);_run_out.mkdir(parents=True,exist_ok=True) +_run_lock=open(_run_out/'.training.lock','a') +try:fcntl.flock(_run_lock,fcntl.LOCK_EX|fcntl.LOCK_NB) +except BlockingIOError:raise SystemExit('Another trainer already owns this output directory: '+str(_run_out)) +if not a.resume: + _saved=list(_run_out.glob('ema*.pt'))+list(_run_out.glob('step*.pt')) + if (_run_out/'recovery.pt').exists():_saved.append(_run_out/'recovery.pt') + if _saved: + raise SystemExit('Refusing fresh training into an output with saved checkpoints; use a new directory or explicit --resume: '+str(_run_out)) +sys.path.insert(0,a.code_dir) +from model import DirectForecaster,loss_fn +from data import Sampler +from schedules import learning_rate +torch.set_num_threads(2);torch.manual_seed(a.seed);torch.backends.cuda.matmul.allow_tf32=True +out=Path(a.out);out.mkdir(parents=True,exist_ok=True);a.trainable_scope='all' +if Path(a.code_dir).name in ('long_memory_synth','paired_long_memory','multiscale_ar','random_capacity','patch8_long_memory','distill_ensemble','random_capacity_long_seasonal','random_capacity_long_seasonal_distill','random_capacity_seasonal_width','visibility_curriculum','random_capacity_deep'):a.synthetic_ar_time_constants=[1,10000] +if Path(a.code_dir).name in ('full_paired','patch8','temporal_mixup','postloss','paired_long_memory','multiscale_ar','random_capacity','overflow_control','coarse_aggregate','patch8_long_memory','patch4','metric_scale','robust_normalization','split_patch','weekly_synth','distill_ensemble'):a.requested_horizon_seed=a.seed+300003 +if Path(a.code_dir).name=='multiscale_ar': + a.synthetic_ar_components=4;a.multiscale_ar_seed=a.seed+700003 +if Path(a.code_dir).name=='volatility_synth':a.stochastic_volatility_seed=a.seed+500003 +if Path(a.code_dir).name=='coarse_aggregate': + a.coarse_aggregation_seed=a.seed+900003;a.coarse_aggregation_probability=.2;a.coarse_aggregation_frequencies=['D','W'] +if Path(a.code_dir).name=='temporal_mixup':a.temporal_mixup_seed=a.seed+600003 +if Path(a.code_dir).name=='postloss': + a.fixed_postprocessing_loss=True;a.normalization_overflow_fallback=True +if Path(a.code_dir).name in ('overflow_control','metric_scale','random_capacity','weekly_synth','distill_ensemble'):a.normalization_overflow_fallback=True +if Path(a.code_dir).name=='weekly_synth': + a.weekly_synthetic_seed=a.seed+1000003;a.weekly_replacement_probability=1/11 +if Path(a.code_dir).name=='spectral_synth': + a.spectral_synthetic_seed=a.seed+1100003;a.spectral_replacement_probability=.5 + a.spectral_length_scale=[1,10000];a.spectral_families=['Matern0.5','Matern1.5','Matern2.5','RBF'] + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True +if Path(a.code_dir).name in ('long_seasonal','phase_joint','seasonal_dispersion','seasonal_history','seasonal_width','direct_trend_head','random_capacity_long_seasonal','random_capacity_long_seasonal_distill','random_capacity_seasonal_width','visibility_curriculum','random_capacity_deep','ensemble_gate','ensemble_gate_factorial'): + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True +if Path(a.code_dir).name=='random_capacity_buildings': + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True + a.synthetic_ar_time_constants=[1,10000] + a.source_probability_multipliers={'buildings_900k':4.} + a.source_probability_rule='original packed_sample capped-point temperature0.25, climate0.35, low-frequency3, then buildings_900k x4 and renormalize; same20percent synthetic' +if Path(a.code_dir).name=='random_capacity_original_ar': + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True + a.synthetic_ar_coefficient_law='uniform(0.2,0.995), original generator; unchanged AR branch probability and asymptotic variance scaling' +if Path(a.code_dir).name=='log_horizon': + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True + a.requested_horizon_law='half full; half geometric quantile remap of the original uniform integer endpoint draw from min(16,max(1,H//4)) to H, then patch16 rounding; identical RNG consumption' +if Path(a.code_dir).name=='seasonal_history': + a.learned_seasonal_history_context=16384;a.recent_encoder_and_rule_context=4096 + a.history_extension_rule='extend originally full4096 real contexts before the same cutoff, preserving original recent contexts, targets, aggregation, sampler RNG and horizon RNG; synthetic extra prefix missing' +if Path(a.code_dir).name in ('lowfreq_windows','lowfreq_age'): + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True + a.lowfreq_window_seed=a.seed+1200003;a.lowfreq_window_probability=.5 + a.lowfreq_window_rule='period2=1,period1<=52;finite-target endpoint;log-uniform horizon4..min(H,max(8,2p),span-8) with available-length fallback;context cap min(C,max(64,32p));at least4finite history' +if Path(a.code_dir).name=='lowfreq_age': + a.synthetic_generation_origin='For successfully shortened selected low-frequency synthetic rows only, use the first nc+nh observations of the same generated path, split at nc; unchanged masks, lengths, periods, real/unselected rows and all RNG streams; no regeneration or extra draws' +if Path(a.code_dir).name=='integrated_level': + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True + a.integrated_level_seed=a.seed+1300003;a.integrated_level_probability=.25 + a.integrated_level_rule='Add zero-initialized Gaussian random-walk levels to one quarter of synthetic paths before intermittent/positivity transforms; per-path innovation sigma10**Uniform(-3,-1); original generator, real windows and their RNGs unchanged' + a.synthetic_ar_coefficient_law='uniform(0.2,0.995), original generator; unchanged AR branch probability and asymptotic variance scaling' +if Path(a.code_dir).name=='metric_scale':a.loss_seasonality='lag1 for exact daily[7,365] and weekly[52,1] period pairs; unchanged otherwise' +if Path(a.code_dir).name=='robust_normalization':a.normalization_kind='finite median plus/minus6 mean absolute deviations winsorized mean/RMS, float64; original normalized history clipped30' +if Path(a.code_dir).name=='wide_graft_frozen':a.trainable_scope='new feature stream and cross-stream blocks; inherited parameter blocks frozen' +if a.visibility_curriculum: + assert Path(a.code_dir).name=='visibility_curriculum' and not a.teacher_package and not a.gate_package + from visibility import visible_batch + a.visibility_curriculum_rule='steps1..16000:lastC/4,firstmax(16,H/4);16001..32000:lastC/2,firstmax(16,H/2);32001..96000:unchanged; sample/prefetch full original windows and crop only current loss arrays' +if a.micro_batch is not None: + assert 0=0 and start_step>=a.reset_at else a.seed +sampler,rng=make_sampler(stream_seed) +def next_batch(): + c=int(rng.choice([512,1024,2048,a.sample_context],p=[.1,.15,.35,.4])) + h=int(rng.choice([32,128,512,1024],p=[.1,.2,.2,.5])) + x,y,p=sampler.sample(a.batch,c,h) + return x[:,-model.max_context:].copy(),y,p +pool=ThreadPoolExecutor(1) +if a.resume: + recovery=torch.load(a.resume,map_location='cpu',weights_only=False) + rng.bit_generator.state=recovery['batch_rng_state'];sampler.rng.bit_generator.state=recovery['sampler_rng_state'] + for name,state in recovery.get('sampler_rng_states',{}).items():getattr(sampler,name).bit_generator.state=state + torch.set_rng_state(recovery['torch_rng_state']);torch.cuda.set_rng_state_all(recovery['cuda_rng_state']) + pending=recovery['prefetched_batch'];del recovery + future=pool.submit(lambda:pending) +else:future=pool.submit(next_batch) +parameters=sum(p.numel() for p in model.parameters()) +(out/'config.json').write_text(json.dumps({**vars(a),'model':model.config,'parameters':parameters},indent=2)) +print(json.dumps({'parameters':parameters,'starting_step':start_step,'stream_seed':stream_seed,'restored_complete_training_state':bool(a.resume)}),flush=True) +started=time.monotonic();losses=[] +def atomic_save(obj,path): + torch.save(obj,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) +def save(step,include_selection_weights=True): + global future + pending_batch=future.result() + common={'config':model.config,'step':step,'args':vars(a),'lr_multipliers':multipliers, + 'parent_checkpoints':list(dict.fromkeys(lineage_parents+(teacher.checkpoints if teacher else [])+(experts.checkpoints if experts else [])))} + if include_selection_weights: + for prefix,state in [('step',model.state_dict()),('ema',ema)]: + atomic_save({**common,'model':state,'ema':prefix=='ema'},out/f'{prefix}{step:06d}.pt') + atomic_save({**common,'model':model.state_dict(),'optimizer':opt.state_dict(),'ema_state':ema, + 'prefetched_batch':pending_batch,'batch_rng_state':copy.deepcopy(rng.bit_generator.state), + 'sampler_rng_state':copy.deepcopy(sampler.rng.bit_generator.state), + 'sampler_rng_states':{name:copy.deepcopy(value.bit_generator.state) for name,value in vars(sampler).items() if isinstance(value,np.random.Generator)}, + 'torch_rng_state':torch.get_rng_state(),'cuda_rng_state':torch.cuda.get_rng_state_all()},out/'recovery.pt') + future=pool.submit(lambda:pending_batch) +for step in range(start_step+1,a.steps+1): + if a.reset_at>=0 and step==a.reset_at+1 and start_step=a.halt_after) + selection_checkpoint=step%a.save_every==0 or step==a.steps or stop + # Persist a complete state before a fresh/resumed job warms its remaining compiled shapes. + if selection_checkpoint or step%a.recovery_every==0 or step==start_step+1: + save(step,include_selection_weights=selection_checkpoint) + if stop:break +pool.shutdown() +print(json.dumps({'completed_step':step,'training_process_loop_seconds':time.monotonic()-started}),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/watch_matched_cutoffs.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/watch_matched_cutoffs.py new file mode 100644 index 0000000000000000000000000000000000000000..3bd2f95022f87dbe1c349575c0ec77662a2d4d6e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/provenance/member5/training/recovery/watch_matched_cutoffs.py @@ -0,0 +1,34 @@ +"""Complete declared primary/durability comparisons; never select a model automatically.""" +import argparse,datetime,json,os,subprocess,time +from pathlib import Path +R=Path('/workspace/research');ap=argparse.ArgumentParser() +for key in ['run','control','evaluator','label']:ap.add_argument('--'+key,required=True) +ap.add_argument('--control-evaluator');ap.add_argument('--steps',default='6000,12000');a=ap.parse_args();start=time.monotonic() +receipt=R/(a.run+'_matched_cutoffs_receipt.json') +state=dict(pid=os.getpid(),status='running',run=a.run,control=a.control,steps=[],started_utc=datetime.datetime.now(datetime.timezone.utc).isoformat()) +def save(): + state['seconds']=time.monotonic()-start;tmp=receipt.with_suffix('.tmp');tmp.write_text(json.dumps(state,indent=2));os.replace(tmp,receipt) +def call(label,command): + state['status']=label;save();t=time.monotonic();result=subprocess.run(command);state['steps'].append(dict(label=label,returncode=result.returncode,seconds=time.monotonic()-t));save() + if result.returncode:state['status']='failed';save();raise SystemExit(result.returncode) +for step in map(int,a.steps.split(',')): + name=a.run+'_ema'+str(step);report=R/'evals'/name/'report.json';state['status']='waiting for main'+str(step);save() + while not report.exists(): + queue=R/(a.run+'_queue.json') + if queue.exists() and json.loads(queue.read_text()).get('status')=='failed':state['status']='training failed';save();raise SystemExit(1) + time.sleep(3) + time.sleep(1) + call('earlier cutoffs'+str(step),['python3',str(R/'evaluate_cutoffs.py'),'--name',name,'--weights',str(R/'runs'/a.run/f'ema{step:06d}.pt'),'--evaluator',a.evaluator,'--cutoffs','1,2,3']) + control_name=a.control+'_ema'+str(step) + if any(not (R/folder/control_name/'report.json').exists() for folder in ['evals','backcast_evals','backcast2_evals','backcast3_evals']): + assert a.control_evaluator,'Missing matched control reports; pass --control-evaluator for their declared evaluation' + call('control cutoffs'+str(step),['python3',str(R/'evaluate_cutoffs.py'),'--name',control_name,'--weights',str(R/'runs'/a.control/f'ema{step:06d}.pt'),'--evaluator',a.control_evaluator]) + out=R/(a.run+str(step//1000)+'k_four_cutoff_comparison.json') + if out.exists(): + cached=json.loads(out.read_text());assert cached['candidate']==name and cached['control']==a.control+'_ema'+str(step) and len(cached['rows'])==4 + for row,folder in zip(cached['rows'],['evals','backcast_evals','backcast2_evals','backcast3_evals']): + assert row['candidate_checkpoint']==json.loads((R/folder/name/'report.json').read_text())['checkpoint_sha256'] + assert row['control_checkpoint']==json.loads((R/folder/(a.control+'_ema'+str(step))/'report.json').read_text())['checkpoint_sha256'] + state['steps'].append(dict(label='reused verified matched comparison'+str(step),returncode=0,seconds=0));save();continue + call('matched comparison'+str(step),['python3',str(R/'recovery/matched_report.py'),'--candidate',name,'--control',a.control+'_ema'+str(step),'--label',a.label+' '+str(step)+' four-cutoff comparison','--cutoffs','0,1,2,3','--out',str(out),'--outcome',f'Declared comparison checkpoints {a.steps}. No transfer formula or automatic publication is selected by this controller.']) +state['status']='complete; research review required';save();print(json.dumps(state),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/requirements.txt b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..ca733199990e5dc8e6a90509cc691f00ab8e9f5d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/requirements.txt @@ -0,0 +1,12 @@ +# Runtime pins recorded from the contributor's working environment on 2026-09-17 (Python 3.11). +# torch comes from the pytorch/pytorch:2.14.0-cuda12.6-cudnn9-runtime base image (cu130 needs driver >= 580). +torch==2.14.0 +numpy==2.4.6 +h5py==3.16.0 +pandas==2.3.3 +scipy==1.17.1 +pyarrow==25.0.1 +huggingface-hub==0.36.2 +einops==0.8.2 +safetensors==0.8.0 +pytest==9.1.1 diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/seasonal.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/seasonal.py new file mode 100644 index 0000000000000000000000000000000000000000..cd8d8ebbf65c59c69f3d1c537e8cd5cb024d0330 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/seasonal.py @@ -0,0 +1,51 @@ +"""A fixed confidence gate for highly repeatable history; no fitted parameters.""" +import numpy as np + +def apply_gate(ctx,periods,quant,threshold=.25,strength=1.,cycles=4,mode='aligned'): + # Each row uses only its own context. Quantile blending preserves ordering. + b,_,h=quant.shape + out=quant.copy() + for i in range(b): + x=ctx[i];valid=np.isfinite(x) + if not valid.any():continue + x=x[np.flatnonzero(valid)[0]:] + best=None + for p in periods[i]: + p=int(p) + if p<2 or len(x)<3*p:continue + k=min(len(x)//p,8);history=x[-k*p:] + pairs=np.isfinite(history[p:])&np.isfinite(history[:-p]) + if pairs.sum()0) + if mode in ('centered','aligned'): + mu=mu+np.nanmean(seasons[-1])-np.nanmean(mu) + if mode=='aligned' and np.isfinite(seasons[-1]).sum()>=max(2,.75*p): + noise=float(np.mean(err.astype(np.float64)**2)/2) + target_var=max(0.,float(np.nanvar(seasons[-1]))-noise) + template_var=max(0.,float(np.nanvar(mu))-noise/min(k,cycles)) + ratio=float(np.clip(np.sqrt(target_var/max(template_var,1e-12)),.5,2.)) + center=float(np.nanmean(mu));mu=center+(mu-center)*ratio + if mode=='exponential': + w=.5**np.arange(len(recent)-1,-1,-1,dtype=np.float32) + den=(w[:,None]*np.isfinite(recent)).sum(0) + mu=np.divide((w[:,None]*np.nan_to_num(recent)).sum(0),den,out=np.full(p,np.nan,np.float32),where=den>0) + # Error of a season relative to the previous one, corrected for averaging. + sigma=float(np.sqrt(np.mean(err.astype(np.float64)**2)/2*(1+1/min(k,cycles)))) + idx=np.arange(h)%p;median=mu[idx] + z=np.array([-1.2815515655,-.8416212336,-.5244005127,-.2533471031,0,.2533471031,.5244005127,.8416212336,1.2815515655]) + sq=median[None]+z[:,None]*sigma + sq=np.where(np.isfinite(sq),sq,quant[i]) + if np.nanmin(x)>=0:sq=np.maximum(0,sq) + best=(weight,sq) + if best is not None:out[i]=(1-best[0])*quant[i]+best[0]*best[1] + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/validation_report.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/validation_report.json new file mode 100644 index 0000000000000000000000000000000000000000..f49c9b6987c785f9ffd45de112d67403979d7651 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/validation_report.json @@ -0,0 +1,4892 @@ +{ + "contract": "timeseries-forecast/v1", + "split": "valid", + "reward": 0.385663741697722, + "skill_score": 0.385663741697722, + "rel_mase_gmean": 0.7347721085312826, + "rel_wql_gmean": 0.5136409423858462, + "n_configs": 97, + "n_failed": 0, + "n_instances": 151170, + "n_instances_scored": 151170, + "n_partial": 0, + "failures": [], + "groups": { + "term": { + "long": { + "n_configs": 21, + "rel_mase_gmean": 0.7363937350269439, + "rel_wql_gmean": 0.4856248722285082 + }, + "medium": { + "n_configs": 21, + "rel_mase_gmean": 0.7012053081143462, + "rel_wql_gmean": 0.4946801588294994 + }, + "short": { + "n_configs": 55, + "rel_mase_gmean": 0.7473789492783708, + "rel_wql_gmean": 0.5323500359779126 + } + }, + "domain": { + "Econ/Fin": { + "n_configs": 6, + "rel_mase_gmean": 0.8914261529528209, + "rel_wql_gmean": 0.8453614537023862 + }, + "Energy": { + "n_configs": 32, + "rel_mase_gmean": 0.8930076902076908, + "rel_wql_gmean": 0.6443355221940194 + }, + "Healthcare": { + "n_configs": 5, + "rel_mase_gmean": 0.5401400332323313, + "rel_wql_gmean": 0.47489822113141217 + }, + "Nature": { + "n_configs": 15, + "rel_mase_gmean": 0.795745414864363, + "rel_wql_gmean": 0.3882480453666182 + }, + "Sales": { + "n_configs": 4, + "rel_mase_gmean": 0.8196550609198848, + "rel_wql_gmean": 0.5017766420595158 + }, + "Transport": { + "n_configs": 15, + "rel_mase_gmean": 0.6357812400994254, + "rel_wql_gmean": 0.43225483648706525 + }, + "Web/CloudOps": { + "n_configs": 20, + "rel_mase_gmean": 0.5630309592471917, + "rel_wql_gmean": 0.442708739373228 + } + }, + "frequency": { + "A": { + "n_configs": 1, + "rel_mase_gmean": 0.6772447180252334, + "rel_wql_gmean": 0.7210219050943136 + }, + "D": { + "n_configs": 15, + "rel_mase_gmean": 0.7532813772291723, + "rel_wql_gmean": 0.5107513200485395 + }, + "H": { + "n_configs": 31, + "rel_mase_gmean": 0.7295720955479685, + "rel_wql_gmean": 0.49368620072706776 + }, + "M": { + "n_configs": 5, + "rel_mase_gmean": 0.9371128734328216, + "rel_wql_gmean": 0.7785325548959801 + }, + "Q": { + "n_configs": 1, + "rel_mase_gmean": 0.7904447266124541, + "rel_wql_gmean": 0.8256442503351462 + }, + "S": { + "n_configs": 6, + "rel_mase_gmean": 0.6570003218333406, + "rel_wql_gmean": 0.5031001069132773 + }, + "T": { + "n_configs": 30, + "rel_mase_gmean": 0.6844366503964201, + "rel_wql_gmean": 0.4583886010430004 + }, + "W": { + "n_configs": 8, + "rel_mase_gmean": 0.8796216466607845, + "rel_wql_gmean": 0.6561066210537424 + } + }, + "variates": { + "multivariate": { + "n_configs": 43, + "rel_mase_gmean": 0.7094387976499908, + "rel_wql_gmean": 0.5116875764567451 + }, + "univariate": { + "n_configs": 54, + "rel_mase_gmean": 0.7555903592076821, + "rel_wql_gmean": 0.5152017322246427 + } + } + }, + "quantile_crossing_fraction_mean": 0.0, + "configs": [ + { + "config_id": "m4_yearly__A__short", + "leaderboard_key": "m4_yearly/A/short", + "dataset": "m4_yearly", + "term": "short", + "freq": "A-DEC", + "prediction_length": 6, + "seasonality": 1, + "n_variates": 1, + "n_instances": 22728, + "domain": "Econ/Fin", + "n_cohorts": 3, + "skipped_series": 235, + "dropped_containers": 11, + "status": "ok", + "baseline": { + "mase": 4.730803330645802, + "wql": 0.15602350647819704 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 22728, + "instances": 22728, + "fraction": 1.0 + }, + "metrics": { + "mase": 3.2039115676960517, + "wql": 0.11249636588040463, + "wsql_by_level": [ + 0.06302427701985164, + 0.09719396420187057, + 0.11919705570437779, + 0.13221109423902153, + 0.13783190655719776, + 0.13766651073744463, + 0.12996012896641132, + 0.11302281001292339, + 0.08235954548454293 + ], + "n_valid_labels": 136368, + "n_masked_labels": 0, + "mae_median": 715.4727670097647, + "n_mase_elements": 136356, + "n_seasonal_error_zero": 2, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6772447180252334, + "wql": 0.7210219050943136 + } + }, + { + "config_id": "m4_quarterly__Q__short", + "leaderboard_key": "m4_quarterly/Q/short", + "dataset": "m4_quarterly", + "term": "short", + "freq": "Q-DEC", + "prediction_length": 8, + "seasonality": 4, + "n_variates": 1, + "n_instances": 23905, + "domain": "Econ/Fin", + "n_cohorts": 3, + "dropped_containers": 95, + "status": "ok", + "baseline": { + "mase": 1.5909093331240343, + "wql": 0.0995990835037221 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 23905, + "instances": 23905, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.257525892886429, + "wql": 0.08223341063349826, + "wsql_by_level": [ + 0.04788440688736821, + 0.0729868009559222, + 0.0884276610209738, + 0.0975328527456831, + 0.10140068864732722, + 0.10015228120987113, + 0.09376039953713786, + 0.08052321283729814, + 0.057432391859902614 + ], + "n_valid_labels": 191240, + "n_masked_labels": 0, + "mae_median": 577.4049519869204, + "n_mase_elements": 191232, + "n_seasonal_error_zero": 1, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7904447266124541, + "wql": 0.8256442503351462 + } + }, + { + "config_id": "m4_monthly__M__short", + "leaderboard_key": "m4_monthly/M/short", + "dataset": "m4_monthly", + "term": "short", + "freq": "M", + "prediction_length": 18, + "seasonality": 12, + "n_variates": 1, + "n_instances": 47501, + "domain": "Econ/Fin", + "n_cohorts": 3, + "dropped_containers": 499, + "status": "ok", + "baseline": { + "mase": 1.2366691185612824, + "wql": 0.11781121192744513 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 47501, + "instances": 47501, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9859180890256141, + "wql": 0.09178963437995141, + "wsql_by_level": [ + 0.05319972453697606, + 0.08119566664816284, + 0.09888127299194115, + 0.10937141902060242, + 0.11401761592979012, + 0.11258530273874644, + 0.10465681873211899, + 0.08921095079355916, + 0.0629879380276655 + ], + "n_valid_labels": 855018, + "n_masked_labels": 0, + "mae_median": 540.6358499557427, + "n_mase_elements": 855018, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7972367662682582, + "wql": 0.7791247783486066 + } + }, + { + "config_id": "m4_weekly__W__short", + "leaderboard_key": "m4_weekly/W/short", + "dataset": "m4_weekly", + "term": "short", + "freq": "W-SUN", + "prediction_length": 13, + "seasonality": 1, + "n_variates": 1, + "n_instances": 355, + "domain": "Econ/Fin", + "n_cohorts": 2, + "dropped_containers": 4, + "status": "ok", + "baseline": { + "mase": 2.895128591740639, + "wql": 0.06508715280630521 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 355, + "instances": 355, + "fraction": 1.0 + }, + "metrics": { + "mase": 3.187062897254108, + "wql": 0.04947101761344423, + "wsql_by_level": [ + 0.02563029448046274, + 0.040164583613244695, + 0.050827546126387506, + 0.05773234690644501, + 0.06183944496772066, + 0.06318406893351634, + 0.05983992885471431, + 0.05088038262938194, + 0.03514056200912493 + ], + "n_valid_labels": 4615, + "n_masked_labels": 0, + "mae_median": 321.8654304215089, + "n_mase_elements": 4615, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.1008363864549275, + "wql": 0.7600734627410497 + } + }, + { + "config_id": "m4_daily__D__short", + "leaderboard_key": "m4_daily/D/short", + "dataset": "m4_daily", + "term": "short", + "freq": "D", + "prediction_length": 14, + "seasonality": 1, + "n_variates": 1, + "n_instances": 4204, + "domain": "Econ/Fin", + "n_cohorts": 2, + "dropped_containers": 23, + "status": "ok", + "baseline": { + "mase": 3.2161164077095057, + "wql": 0.02310161661155265 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 4204, + "instances": 4204, + "fraction": 1.0 + }, + "metrics": { + "mase": 3.2849508671071455, + "wql": 0.021805350485497105, + "wsql_by_level": [ + 0.01372362826270619, + 0.019852994166843423, + 0.02360902720534817, + 0.025792030074990827, + 0.026697456745237554, + 0.026393103424785607, + 0.024608333280437582, + 0.020883682207621636, + 0.01468789900150298 + ], + "n_valid_labels": 58856, + "n_masked_labels": 0, + "mae_median": 171.05723251595808, + "n_mase_elements": 58842, + "n_seasonal_error_zero": 1, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.0214029751014713, + "wql": 0.943888510148363 + } + }, + { + "config_id": "m4_hourly__H__short", + "leaderboard_key": "m4_hourly/H/short", + "dataset": "m4_hourly", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 414, + "domain": "Econ/Fin", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.22836124915778, + "wql": 0.034474947608819397 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 414, + "instances": 414, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.284440495313698, + "wql": 0.03781234020631507, + "wsql_by_level": [ + 0.01908384285142586, + 0.031852853373059, + 0.040608050045972045, + 0.04566846136189118, + 0.04803358362653032, + 0.04785531504470845, + 0.0445361284955977, + 0.037230349409698126, + 0.025442477647952978 + ], + "n_valid_labels": 19872, + "n_masked_labels": 0, + "mae_median": 361.83701398099464, + "n_mase_elements": 19872, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.045653708299874, + "wql": 1.0968063138301014 + } + }, + { + "config_id": "electricity__T__short", + "leaderboard_key": "electricity/15T/short", + "dataset": "electricity/15T", + "term": "short", + "freq": "15T", + "prediction_length": 48, + "seasonality": 96, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0916823579221513, + "wql": 0.06198863606457304 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9736423463597397, + "wql": 0.04839597398533557, + "wsql_by_level": [ + 0.030630053944195948, + 0.046686162178625874, + 0.05662014530432425, + 0.061816301845367176, + 0.06287053252761476, + 0.05951787469902951, + 0.05148544779854726, + 0.039639932999389955, + 0.02629731457092543 + ], + "n_valid_labels": 17712, + "n_masked_labels": 48, + "mae_median": 63.860906308527795, + "n_mase_elements": 17712, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 0.8918732993110903, + "wql": 0.7807233237866679 + } + }, + { + "config_id": "electricity__T__medium", + "leaderboard_key": "electricity/15T/medium", + "dataset": "electricity/15T", + "term": "medium", + "freq": "15T", + "prediction_length": 480, + "seasonality": 96, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.5099936923797364, + "wql": 0.12054261982000446 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9559241593582876, + "wql": 0.08949868633192877, + "wsql_by_level": [ + 0.04179454964475057, + 0.06678985315413528, + 0.08498615144430069, + 0.09904943701699147, + 0.10938804018527858, + 0.11408645569304195, + 0.1120000246759131, + 0.10108208658572415, + 0.07631157858722315 + ], + "n_valid_labels": 177120, + "n_masked_labels": 480, + "mae_median": 78.67420276286119, + "n_mase_elements": 177120, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 0.6330650016502782, + "wql": 0.7424650838480961 + } + }, + { + "config_id": "electricity__T__long", + "leaderboard_key": "electricity/15T/long", + "dataset": "electricity/15T", + "term": "long", + "freq": "15T", + "prediction_length": 720, + "seasonality": 96, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0941077605435365, + "wql": 0.107564338522276 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8796069352981507, + "wql": 0.08608508764210426, + "wsql_by_level": [ + 0.04013600848540478, + 0.06448244392747436, + 0.0816454349318847, + 0.09394866296372147, + 0.10338201122587518, + 0.10802004992225261, + 0.10733097921929205, + 0.09853013096246305, + 0.0772900671405701 + ], + "n_valid_labels": 265680, + "n_masked_labels": 720, + "mae_median": 74.543233976202, + "n_mase_elements": 265680, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 0.8039490871184161, + "wql": 0.8003125275973924 + } + }, + { + "config_id": "electricity__H__short", + "leaderboard_key": "electricity/H/short", + "dataset": "electricity/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9861593153062442, + "wql": 0.06763119078713985 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0305243492691778, + "wql": 0.07444648393903623, + "wsql_by_level": [ + 0.046633928073906844, + 0.06751111419253623, + 0.08172123809832314, + 0.08975578112154456, + 0.0929383315482665, + 0.09153164095243989, + 0.08483911887423684, + 0.07049229865334668, + 0.044594903936725404 + ], + "n_valid_labels": 17712, + "n_masked_labels": 48, + "mae_median": 282.2565500852875, + "n_mase_elements": 17712, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 1.044987694457012, + "wql": 1.1007714498676595 + } + }, + { + "config_id": "electricity__H__medium", + "leaderboard_key": "electricity/H/medium", + "dataset": "electricity/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.2478422873379948, + "wql": 0.12311153060577013 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9677603429550744, + "wql": 0.07821212249087273, + "wsql_by_level": [ + 0.04236967134216156, + 0.06420394544461798, + 0.0778599486422614, + 0.08688552397957848, + 0.09429913224857668, + 0.09720188254688802, + 0.094390823842129, + 0.08428017302053172, + 0.06241800135110975 + ], + "n_valid_labels": 177120, + "n_masked_labels": 480, + "mae_median": 253.77461650244953, + "n_mase_elements": 177120, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 0.7755470004303064, + "wql": 0.6352948591088916 + } + }, + { + "config_id": "electricity__H__long", + "leaderboard_key": "electricity/H/long", + "dataset": "electricity/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.356699671272273, + "wql": 0.14674885232557194 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.1940750435105756, + "wql": 0.0921458280687208, + "wsql_by_level": [ + 0.04329779161743468, + 0.0691410352386601, + 0.08759972449034967, + 0.1006754754940454, + 0.10922272389273174, + 0.11317409459381209, + 0.1124611013052604, + 0.10607623563598916, + 0.08766427035020403 + ], + "n_valid_labels": 265680, + "n_masked_labels": 720, + "mae_median": 299.3573126873418, + "n_mase_elements": 265680, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 0.8801321831167005, + "wql": 0.6279151530554341 + } + }, + { + "config_id": "electricity__D__short", + "leaderboard_key": "electricity/D/short", + "dataset": "electricity/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.6456666278884469, + "wql": 0.09261378216375024 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.4754016662857206, + "wql": 0.06718781976312659, + "wsql_by_level": [ + 0.028584818844481698, + 0.04827814562839972, + 0.06422129875567062, + 0.07560136868961155, + 0.08342948003156325, + 0.08643295306955186, + 0.08415516304148275, + 0.07598229303973086, + 0.058004856767646946 + ], + "n_valid_labels": 11070, + "n_masked_labels": 30, + "mae_median": 5487.918422998172, + "n_mase_elements": 11070, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 0.8965373917673757, + "wql": 0.7254624332729651 + } + }, + { + "config_id": "electricity__W__short", + "leaderboard_key": "electricity/W/short", + "dataset": "electricity/W", + "term": "short", + "freq": "W-FRI", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.316880865245498, + "wql": 0.06523927951573125 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.4354933539349073, + "wql": 0.06602339964405128, + "wsql_by_level": [ + 0.027022893770446758, + 0.04725422593255974, + 0.06502685935334421, + 0.07632315443725943, + 0.08372791392092091, + 0.08591832797186905, + 0.08215525919878273, + 0.07260237718072757, + 0.05417958503055111 + ], + "n_valid_labels": 2952, + "n_masked_labels": 8, + "mae_median": 36056.423056284584, + "n_mase_elements": 2952, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 1.0900707815108979, + "wql": 1.012019141445775 + } + }, + { + "config_id": "solar__T__short", + "leaderboard_key": "solar/10T/short", + "dataset": "solar/10T", + "term": "short", + "freq": "10T", + "prediction_length": 48, + "seasonality": 144, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.016018364778558773, + "wql": 12.118563297136966 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.017898065124161623, + "wql": 0.43061252551085855, + "wsql_by_level": [ + 0.1955366737519917, + 0.3517534964413349, + 0.4418725803852744, + 0.4912409723355752, + 0.5159186764650792, + 0.517334563799399, + 0.5122621435527657, + 0.47575243736117256, + 0.37384118550513373 + ], + "n_valid_labels": 6576, + "n_masked_labels": 0, + "mae_median": 0.0498580167397467, + "n_mase_elements": 6576, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.1173465813513566, + "wql": 0.035533298374782724 + } + }, + { + "config_id": "solar__T__medium", + "leaderboard_key": "solar/10T/medium", + "dataset": "solar/10T", + "term": "medium", + "freq": "10T", + "prediction_length": 480, + "seasonality": 144, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.8331425981399365, + "wql": 0.5650432034501303 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6753301657048053, + "wql": 0.2763252401644553, + "wsql_by_level": [ + 0.20531881352487535, + 0.3092798518411076, + 0.3469969794672026, + 0.34702481436373994, + 0.3266509198057868, + 0.3011995353478143, + 0.27049843289938136, + 0.22446877579450455, + 0.15548903843568543 + ], + "n_valid_labels": 65760, + "n_masked_labels": 0, + "mae_median": 1.5608030173949639, + "n_mase_elements": 65760, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8105817266006309, + "wql": 0.4890338269307991 + } + }, + { + "config_id": "solar__T__long", + "leaderboard_key": "solar/10T/long", + "dataset": "solar/10T", + "term": "long", + "freq": "10T", + "prediction_length": 720, + "seasonality": 144, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 2.1421153816960863, + "wql": 0.9032285592107642 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7011085805554843, + "wql": 0.22375373492187667, + "wsql_by_level": [ + 0.1657188035008133, + 0.25874623895636395, + 0.29744714607646233, + 0.3009823630859898, + 0.2799820375832269, + 0.24106400099333514, + 0.19452938635141415, + 0.15452197868733245, + 0.12079165906195209 + ], + "n_valid_labels": 98640, + "n_masked_labels": 0, + "mae_median": 1.6450969919106875, + "n_mase_elements": 98640, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.32729729992432055, + "wql": 0.247726594382037 + } + }, + { + "config_id": "solar__H__short", + "leaderboard_key": "solar/H/short", + "dataset": "solar/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0569321595099215, + "wql": 0.602297355940449 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8723681257740087, + "wql": 0.3339553653223836, + "wsql_by_level": [ + 0.24430360351447972, + 0.38559583693686006, + 0.44015126357677054, + 0.4415950469119877, + 0.41260930883194463, + 0.3678053540244724, + 0.3091960366021708, + 0.24254674498834505, + 0.16179509251442162 + ], + "n_valid_labels": 6576, + "n_masked_labels": 0, + "mae_median": 11.380484420179057, + "n_mase_elements": 6576, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8253775967783102, + "wql": 0.5544692534818347 + } + }, + { + "config_id": "solar__H__medium", + "leaderboard_key": "solar/H/medium", + "dataset": "solar/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.3782698364748944, + "wql": 0.9679824737641872 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.196309272828307, + "wql": 0.44640641819601484, + "wsql_by_level": [ + 0.47132017232172524, + 0.576565062423654, + 0.5934544458618686, + 0.5687829591087544, + 0.5211993699902583, + 0.4573350064533543, + 0.3777099504874969, + 0.2812286000971524, + 0.17006219701986958 + ], + "n_valid_labels": 65760, + "n_masked_labels": 0, + "mae_median": 15.618796820479497, + "n_mase_elements": 65760, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.867978998864275, + "wql": 0.46117200496417776 + } + }, + { + "config_id": "solar__H__long", + "leaderboard_key": "solar/H/long", + "dataset": "solar/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0723400769109404, + "wql": 0.9027882643891623 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0400944625718676, + "wql": 0.3571120779953731, + "wsql_by_level": [ + 0.4300480146405542, + 0.4676361507079845, + 0.46500677522831, + 0.4418290649705207, + 0.405469096274176, + 0.35743364360841556, + 0.29667560006920535, + 0.2208364010571471, + 0.1290739554020447 + ], + "n_valid_labels": 98640, + "n_masked_labels": 0, + "mae_median": 13.66875230410863, + "n_mase_elements": 98640, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9699296752649944, + "wql": 0.3955657069124614 + } + }, + { + "config_id": "solar__D__short", + "leaderboard_key": "solar/D/short", + "dataset": "solar/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.1670584568457976, + "wql": 0.4714212933677157 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.140979598914499, + "wql": 0.28830959313031324, + "wsql_by_level": [ + 0.2499271196837385, + 0.3512331090338666, + 0.3844844530045928, + 0.3826985850041637, + 0.35668372236648854, + 0.31440939607749113, + 0.2570978167646911, + 0.18852426569460695, + 0.10972787054317981 + ], + "n_valid_labels": 4110, + "n_masked_labels": 0, + "mae_median": 288.57961303683095, + "n_mase_elements": 4110, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9776541973726135, + "wql": 0.6115752452985347 + } + }, + { + "config_id": "solar__W__short", + "leaderboard_key": "solar/W/short", + "dataset": "solar/W", + "term": "short", + "freq": "W-FRI", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0078578333938706, + "wql": 0.13890951079671932 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0233101652580825, + "wql": 0.12057840405730436, + "wsql_by_level": [ + 0.05837864738549708, + 0.11725546450825304, + 0.14677135034370525, + 0.15521272536365602, + 0.15301975769914486, + 0.14357096403674308, + 0.12843806287797468, + 0.10702672525725132, + 0.07553193904351378 + ], + "n_valid_labels": 1096, + "n_masked_labels": 0, + "mae_median": 939.654172020237, + "n_mase_elements": 1096, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.015331856688733, + "wql": 0.8680356252478582 + } + }, + { + "config_id": "hospital__M__short", + "leaderboard_key": "hospital/M/short", + "dataset": "hospital", + "term": "short", + "freq": "M", + "prediction_length": 12, + "seasonality": 12, + "n_variates": 1, + "n_instances": 767, + "domain": "Healthcare", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9326829101839614, + "wql": 0.0633931064425068 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 767, + "instances": 767, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.793111332779551, + "wql": 0.05521563746538194, + "wsql_by_level": [ + 0.030155563783164693, + 0.04654516273308011, + 0.057271359784070726, + 0.06512067629264028, + 0.06934946873760123, + 0.06917150764377705, + 0.06478660988356388, + 0.05534892200536832, + 0.03919146632517115 + ], + "n_valid_labels": 9204, + "n_masked_labels": 0, + "mae_median": 19.25427269738739, + "n_mase_elements": 9204, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8503547391289914, + "wql": 0.8710038135685737 + } + }, + { + "config_id": "covid_deaths__D__short", + "leaderboard_key": "covid_deaths/D/short", + "dataset": "covid_deaths", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 266, + "domain": "Healthcare", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 50.55549046119792, + "wql": 0.12549070850235644 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 266, + "instances": 266, + "fraction": 1.0 + }, + "metrics": { + "mase": 42.88283022188918, + "wql": 0.07107209075112365, + "wsql_by_level": [ + 0.061934817848204086, + 0.08832079803303988, + 0.1018907690181748, + 0.09737465641395143, + 0.08175896732381932, + 0.04961697479588584, + 0.040144564484174285, + 0.05629508317426792, + 0.062312185668595324 + ], + "n_valid_labels": 7980, + "n_masked_labels": 0, + "mae_median": 166.09803455029814, + "n_mase_elements": 6810, + "n_seasonal_error_zero": 39, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8482328987551289, + "wql": 0.5663534105378732 + } + }, + { + "config_id": "us_births__D__short", + "leaderboard_key": "us_births/D/short", + "dataset": "us_births/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 1, + "domain": "Healthcare", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 2.328105874599355, + "wql": 0.13056664093780335 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.4447673459668758, + "wql": 0.023956992488659574, + "wsql_by_level": [ + 0.009843628252369903, + 0.01548792867449318, + 0.020441577438811673, + 0.0234494981873614, + 0.028864114315996097, + 0.03301301060559408, + 0.03415025054804987, + 0.03017223598204312, + 0.020190688393216874 + ], + "n_valid_labels": 30, + "n_masked_labels": 0, + "mae_median": 293.72796223958335, + "n_mase_elements": 30, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.19104257706639569, + "wql": 0.1834847884313093 + } + }, + { + "config_id": "us_births__M__short", + "leaderboard_key": "us_births/M/short", + "dataset": "us_births/M", + "term": "short", + "freq": "M", + "prediction_length": 12, + "seasonality": 12, + "n_variates": 1, + "n_instances": 1, + "domain": "Healthcare", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.3023112362005141, + "wql": 0.011101802850788281 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.2718281902520417, + "wql": 0.007635159612017758, + "wsql_by_level": [ + 0.005223768447145481, + 0.005879019721728623, + 0.005531017909200518, + 0.007551019162149062, + 0.008122091274646852, + 0.008261224640401113, + 0.0099511655341463, + 0.010182260876628631, + 0.008014868942113245 + ], + "n_valid_labels": 12, + "n_masked_labels": 0, + "mae_median": 2549.7369791666665, + "n_mase_elements": 12, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8991666789114848, + "wql": 0.6877405151790842 + } + }, + { + "config_id": "us_births__W__short", + "leaderboard_key": "us_births/W/short", + "dataset": "us_births/W", + "term": "short", + "freq": "W-TUE", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 1, + "n_instances": 1, + "domain": "Healthcare", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 3.858436986096576, + "wql": 0.04221704717157443 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.4317184599560224, + "wql": 0.016381675394087535, + "wsql_by_level": [ + 0.007697794195485638, + 0.01604874643561079, + 0.020053120846446868, + 0.021171516224377147, + 0.020944134132775915, + 0.019976091076970643, + 0.017875091577707468, + 0.014845912105564732, + 0.008822671951848608 + ], + "n_valid_labels": 8, + "n_masked_labels": 0, + "mae_median": 1558.0419921875, + "n_mase_elements": 8, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.3710617706379686, + "wql": 0.3880346090410047 + } + }, + { + "config_id": "saugeenday__D__short", + "leaderboard_key": "saugeen/D/short", + "dataset": "saugeenday/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 3.898466092444523, + "wql": 0.5418638069109889 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 3.1337054398207322, + "wql": 0.3140464953615681, + "wsql_by_level": [ + 0.1446249072517199, + 0.2560371392865447, + 0.34454743318615855, + 0.41017347009272614, + 0.4434866760888256, + 0.4229110523760294, + 0.34765260369627443, + 0.22268096003024188, + 0.23430421624559242 + ], + "n_valid_labels": 30, + "n_masked_labels": 0, + "mae_median": 13.777652835845947, + "n_mase_elements": 30, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8038303695635711, + "wql": 0.5795672110891806 + } + }, + { + "config_id": "saugeenday__M__short", + "leaderboard_key": "saugeen/M/short", + "dataset": "saugeenday/M", + "term": "short", + "freq": "M", + "prediction_length": 12, + "seasonality": 12, + "n_variates": 1, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.33228103391864, + "wql": 0.2615013833629034 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.43325813713274774, + "wql": 0.23131417601200527, + "wsql_by_level": [ + 0.12327849145705932, + 0.20629868859718392, + 0.25232721374355466, + 0.26618265624979376, + 0.2582525368052157, + 0.24409545919839692, + 0.2608607411169737, + 0.2701385887804674, + 0.20039320815940215 + ], + "n_valid_labels": 12, + "n_masked_labels": 0, + "mae_median": 7.5105671882629395, + "n_mase_elements": 12, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.3038906615381252, + "wql": 0.8845619592420845 + } + }, + { + "config_id": "saugeenday__W__short", + "leaderboard_key": "saugeen/W/short", + "dataset": "saugeenday/W", + "term": "short", + "freq": "W-THU", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 1, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.5685710422753978, + "wql": 0.5994091721735982 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7130817367828284, + "wql": 0.2333939770028418, + "wsql_by_level": [ + 0.10048456203611476, + 0.1668669260876721, + 0.24377609762888447, + 0.30970546526165327, + 0.34948829365845135, + 0.35144791249266577, + 0.2829811179148306, + 0.13742892818522492, + 0.15836648976007928 + ], + "n_valid_labels": 8, + "n_masked_labels": 0, + "mae_median": 8.546236872673035, + "n_mase_elements": 8, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.2541647107617453, + "wql": 0.3893733827203553 + } + }, + { + "config_id": "temperature_rain_with_missing__D__short", + "leaderboard_key": "temperature_rain/D/short", + "dataset": "temperature_rain_with_missing", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 32072, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 3.2912255413171745, + "wql": 1.099183165150044 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 32072, + "instances": 32072, + "fraction": 1.0 + }, + "metrics": { + "mase": 2.1044545626312336, + "wql": 0.5239996864852147, + "wsql_by_level": [ + 0.17799731445248101, + 0.33462915670771176, + 0.46967755361951613, + 0.5787385076011927, + 0.6570587359783677, + 0.7025132058201673, + 0.7014965066098224, + 0.6330640287667667, + 0.46082216881090565 + ], + "n_valid_labels": 961756, + "n_masked_labels": 404, + "mae_median": 6.601444413422356, + "n_mase_elements": 960736, + "n_seasonal_error_zero": 34, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6394136579862024, + "wql": 0.4767173507553548 + } + }, + { + "config_id": "kdd_cup_2018_with_missing__H__short", + "leaderboard_key": "kdd_cup_2018/H/short", + "dataset": "kdd_cup_2018_with_missing/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 270, + "domain": "Nature", + "n_cohorts": 2, + "status": "ok", + "baseline": { + "mase": 0.6811227593500775, + "wql": 0.6266148384878599 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 270, + "instances": 270, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.5363157065616022, + "wql": 0.38130881422098745, + "wsql_by_level": [ + 0.14733289940444172, + 0.24938843205113387, + 0.3414469788256929, + 0.42113866000669, + 0.47898252978802974, + 0.5038101762154877, + 0.49748379970158857, + 0.45550198567292016, + 0.3366938663229022 + ], + "n_valid_labels": 11685, + "n_masked_labels": 1275, + "mae_median": 12.311039762440583, + "n_mase_elements": 11685, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7873994800487226, + "wql": 0.6085218395739841 + } + }, + { + "config_id": "kdd_cup_2018_with_missing__H__medium", + "leaderboard_key": "kdd_cup_2018/H/medium", + "dataset": "kdd_cup_2018_with_missing/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 1, + "n_instances": 270, + "domain": "Nature", + "n_cohorts": 2, + "status": "ok", + "baseline": { + "mase": 1.2781450805103305, + "wql": 1.049898934007083 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 270, + "instances": 270, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9244552793057486, + "wql": 0.4597102800811919, + "wsql_by_level": [ + 0.18125015729018457, + 0.33088081786155776, + 0.45075692099752435, + 0.5404146590893146, + 0.5964966791543509, + 0.6109839604232127, + 0.579839193471045, + 0.4972743142469726, + 0.34949581819656406 + ], + "n_valid_labels": 116458, + "n_masked_labels": 13142, + "mae_median": 19.992383337566633, + "n_mase_elements": 116458, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7232788307072601, + "wql": 0.43786145998514797 + } + }, + { + "config_id": "kdd_cup_2018_with_missing__H__long", + "leaderboard_key": "kdd_cup_2018/H/long", + "dataset": "kdd_cup_2018_with_missing/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 1, + "n_instances": 270, + "domain": "Nature", + "n_cohorts": 2, + "status": "ok", + "baseline": { + "mase": 0.981050679806651, + "wql": 1.2362237298155803 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 270, + "instances": 270, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8697296168580941, + "wql": 0.47235489903851224, + "wsql_by_level": [ + 0.18217119413526806, + 0.3299750461595686, + 0.45256442781184886, + 0.5462539807637596, + 0.6072090701248772, + 0.6307155353537107, + 0.6111618731112031, + 0.5331963248643956, + 0.3579466390219788 + ], + "n_valid_labels": 175906, + "n_masked_labels": 18494, + "mae_median": 18.518758225221646, + "n_mase_elements": 175906, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8865287336934558, + "wql": 0.3820949943332491 + } + }, + { + "config_id": "kdd_cup_2018_with_missing__D__short", + "leaderboard_key": "kdd_cup_2018/D/short", + "dataset": "kdd_cup_2018_with_missing/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 270, + "domain": "Nature", + "n_cohorts": 2, + "status": "ok", + "baseline": { + "mase": 1.2132840958596942, + "wql": 0.8994855622016019 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 270, + "instances": 270, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0130145774644743, + "wql": 0.3912236968368214, + "wsql_by_level": [ + 0.16404993944677732, + 0.28859483359283616, + 0.38106537089793135, + 0.44793503671903073, + 0.4896749384111183, + 0.5064991090440979, + 0.495821992144037, + 0.44166143218046666, + 0.30571061909509695 + ], + "n_valid_labels": 7581, + "n_masked_labels": 519, + "mae_median": 15.19778592884344, + "n_mase_elements": 7581, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8349360062670933, + "wql": 0.4349416080445506 + } + }, + { + "config_id": "car_parts_with_missing__M__short", + "leaderboard_key": "car_parts/M/short", + "dataset": "car_parts_with_missing", + "term": "short", + "freq": "M", + "prediction_length": 12, + "seasonality": 12, + "n_variates": 1, + "n_instances": 2674, + "domain": "Sales", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.556811831303017, + "wql": 1.6139130745452677 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 2674, + "instances": 2674, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.4155551967681201, + "wql": 1.118108855112371, + "wsql_by_level": [ + 0.2778815766896747, + 0.547669663952511, + 0.8176337148191007, + 1.0808617225044093, + 1.3148027127105963, + 1.502707443785314, + 1.6152594938680935, + 1.5875853161193496, + 1.3185780515622907 + ], + "n_valid_labels": 30108, + "n_masked_labels": 1980, + "mae_median": 0.6221600321505203, + "n_mase_elements": 28068, + "n_seasonal_error_zero": 215, + "n_seasonal_error_nan": 7 + }, + "relative": { + "mase": 0.9092654412725858, + "wql": 0.6927937277089143 + } + }, + { + "config_id": "restaurant__D__short", + "leaderboard_key": "restaurant/D/short", + "dataset": "restaurant", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 806, + "domain": "Sales", + "n_cohorts": 13, + "skipped_series": 1, + "status": "ok", + "baseline": { + "mase": 1.0028179898604987, + "wql": 0.6760963195065456 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 806, + "instances": 806, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6905320198927023, + "wql": 0.26055133784586915, + "wsql_by_level": [ + 0.13078829295142438, + 0.2136872538044907, + 0.27252309732010177, + 0.31134949326622874, + 0.33127669726788206, + 0.3314331312874844, + 0.3098142874544372, + 0.263170194905399, + 0.1809195923553741 + ], + "n_valid_labels": 21222, + "n_masked_labels": 2958, + "mae_median": 7.085468758678764, + "n_mase_elements": 21222, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6885915758140335, + "wql": 0.3853760630379332 + } + }, + { + "config_id": "hierarchical_sales__D__short", + "leaderboard_key": "hierarchical_sales/D/short", + "dataset": "hierarchical_sales/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 118, + "domain": "Sales", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0956340453936162, + "wql": 1.4587792906606432 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 118, + "instances": 118, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9574520454904624, + "wql": 0.6303896050429117, + "wsql_by_level": [ + 0.19785576315999648, + 0.37139813308846653, + 0.5232490619533112, + 0.6561768174629168, + 0.7619993815596313, + 0.8346181318650341, + 0.8690943507543912, + 0.8232001068553982, + 0.6359146986870594 + ], + "n_valid_labels": 3304, + "n_masked_labels": 236, + "mae_median": 2.9882645238705035, + "n_mase_elements": 3304, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8738794212500847, + "wql": 0.43213501115540565 + } + }, + { + "config_id": "hierarchical_sales__W__short", + "leaderboard_key": "hierarchical_sales/W/short", + "dataset": "hierarchical_sales/W", + "term": "short", + "freq": "W-WED", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 1, + "n_instances": 118, + "domain": "Sales", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9952062817493519, + "wql": 0.7382990422957836 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 118, + "instances": 118, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8209821315995173, + "wql": 0.40566349850024663, + "wsql_by_level": [ + 0.14647538902444074, + 0.26468127996876933, + 0.3574435254118189, + 0.4293661450936324, + 0.48580089415231653, + 0.524027400301232, + 0.538242565443614, + 0.5096744659200407, + 0.3952598211863552 + ], + "n_valid_labels": 944, + "n_masked_labels": 0, + "mae_median": 11.861981578613237, + "n_mase_elements": 944, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8249366454524512, + "wql": 0.5494568938337134 + } + }, + { + "config_id": "LOOP_SEATTLE__T__short", + "leaderboard_key": "loop_seattle/5T/short", + "dataset": "LOOP_SEATTLE/5T", + "term": "short", + "freq": "5T", + "prediction_length": 48, + "seasonality": 288, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.6088421384511257, + "wql": 0.05736115508602545 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.4008364819821966, + "wql": 0.029342468062227567, + "wsql_by_level": [ + 0.019338778552747567, + 0.027440604250331593, + 0.032432539138087704, + 0.03534513293646989, + 0.036479291410320025, + 0.03577272280542379, + 0.032841710038383945, + 0.027056010307505422, + 0.017375423120778173 + ], + "n_valid_labels": 15504, + "n_masked_labels": 0, + "mae_median": 2.3659941658023955, + "n_mase_elements": 15504, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6583586395677399, + "wql": 0.511539002626816 + } + }, + { + "config_id": "LOOP_SEATTLE__T__medium", + "leaderboard_key": "loop_seattle/5T/medium", + "dataset": "LOOP_SEATTLE/5T", + "term": "medium", + "freq": "5T", + "prediction_length": 480, + "seasonality": 288, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.5924843577520822, + "wql": 0.14109820582939464 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.607891303625201, + "wql": 0.05055660265777104, + "wsql_by_level": [ + 0.04055673811878439, + 0.053882744247365305, + 0.06059504138989078, + 0.06313637070825319, + 0.06233848558212144, + 0.058266774384296484, + 0.051004800513263025, + 0.04023710792156556, + 0.024991361054399207 + ], + "n_valid_labels": 155040, + "n_masked_labels": 0, + "mae_median": 3.787305234414136, + "n_mase_elements": 155040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.38172513322723484, + "wql": 0.35830790590562356 + } + }, + { + "config_id": "LOOP_SEATTLE__T__long", + "leaderboard_key": "loop_seattle/5T/long", + "dataset": "LOOP_SEATTLE/5T", + "term": "long", + "freq": "5T", + "prediction_length": 720, + "seasonality": 288, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.5910237866124803, + "wql": 0.14753926773607257 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6766890101256708, + "wql": 0.05737986781358119, + "wsql_by_level": [ + 0.04495692314727478, + 0.061409992930315606, + 0.0695533720679864, + 0.07235348191828281, + 0.07094777193096968, + 0.06595652936702728, + 0.05754346745868062, + 0.045336356821332045, + 0.028360914680361532 + ], + "n_valid_labels": 232560, + "n_masked_labels": 0, + "mae_median": 4.173649010840339, + "n_mase_elements": 232560, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.42531671482199496, + "wql": 0.38891251592915504 + } + }, + { + "config_id": "LOOP_SEATTLE__H__short", + "leaderboard_key": "loop_seattle/H/short", + "dataset": "LOOP_SEATTLE/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 2.0101473993616685, + "wql": 0.13665681786039896 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.663853341158673, + "wql": 0.042439125279203876, + "wsql_by_level": [ + 0.03438033807624863, + 0.04579249098571066, + 0.050853776255581594, + 0.052649413006537985, + 0.05178197770272819, + 0.04893084566072258, + 0.04326668248254378, + 0.03382041728317858, + 0.02047618605958293 + ], + "n_valid_labels": 15504, + "n_masked_labels": 0, + "mae_median": 3.136538739082614, + "n_mase_elements": 15504, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.3302510758014475, + "wql": 0.3105525647652453 + } + }, + { + "config_id": "LOOP_SEATTLE__H__medium", + "leaderboard_key": "loop_seattle/H/medium", + "dataset": "LOOP_SEATTLE/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.1535310881157237, + "wql": 0.14911283164622935 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7149418049012978, + "wql": 0.05045906824431083, + "wsql_by_level": [ + 0.04195978949424067, + 0.05557728360880456, + 0.061302854983506835, + 0.06252227630102558, + 0.0606635300240805, + 0.05620188556231993, + 0.04941738677444621, + 0.04008108055883765, + 0.02640552689153559 + ], + "n_valid_labels": 155040, + "n_masked_labels": 0, + "mae_median": 3.38446725695418, + "n_mase_elements": 155040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6197854676540576, + "wql": 0.3383952117818078 + } + }, + { + "config_id": "LOOP_SEATTLE__H__long", + "leaderboard_key": "loop_seattle/H/long", + "dataset": "LOOP_SEATTLE/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.2448539713840052, + "wql": 0.17526380961630228 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7183417393310476, + "wql": 0.050328371259461796, + "wsql_by_level": [ + 0.04189216939536884, + 0.054862694486169074, + 0.060347459053312215, + 0.06164401413725547, + 0.060105979312465405, + 0.05613940618382516, + 0.04983893829556884, + 0.04080682878513156, + 0.02731785168605956 + ], + "n_valid_labels": 232560, + "n_masked_labels": 0, + "mae_median": 3.3735578591399356, + "n_mase_elements": 232560, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.5770489999982961, + "wql": 0.2871578072486476 + } + }, + { + "config_id": "LOOP_SEATTLE__D__short", + "leaderboard_key": "loop_seattle/D/short", + "dataset": "LOOP_SEATTLE/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.1854124643746355, + "wql": 0.09281728785965133 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.5963383160853242, + "wql": 0.027575572940337852, + "wsql_by_level": [ + 0.020162473416847966, + 0.02861757494448661, + 0.03289448515217786, + 0.0345960092741511, + 0.0342249949150675, + 0.032014591487160377, + 0.028174597535446676, + 0.022705986910460742, + 0.014789442827241832 + ], + "n_valid_labels": 9690, + "n_masked_labels": 0, + "mae_median": 1.920940343661943, + "n_mase_elements": 9690, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.5030639832186364, + "wql": 0.2970952241357749 + } + }, + { + "config_id": "SZ_TAXI__T__short", + "leaderboard_key": "sz_taxi/15T/short", + "dataset": "SZ_TAXI/15T", + "term": "short", + "freq": "15T", + "prediction_length": 48, + "seasonality": 96, + "n_variates": 1, + "n_instances": 156, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7251090475210906, + "wql": 0.3023498132057821 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 156, + "instances": 156, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.5180784954171882, + "wql": 0.19545453524203177, + "wsql_by_level": [ + 0.10146191591765988, + 0.165717895010934, + 0.20899500091228737, + 0.23654808984156772, + 0.2487551461466013, + 0.2461166789863302, + 0.2284801488587304, + 0.19214152078865573, + 0.13087442071551927 + ], + "n_valid_labels": 7488, + "n_masked_labels": 0, + "mae_median": 2.784177254093046, + "n_mase_elements": 7488, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7144835624218567, + "wql": 0.6464516487364377 + } + }, + { + "config_id": "SZ_TAXI__T__medium", + "leaderboard_key": "sz_taxi/15T/medium", + "dataset": "SZ_TAXI/15T", + "term": "medium", + "freq": "15T", + "prediction_length": 480, + "seasonality": 96, + "n_variates": 1, + "n_instances": 156, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.6350051480164337, + "wql": 0.3916041859838231 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 156, + "instances": 156, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.4660369015744524, + "wql": 0.1941758154279861, + "wsql_by_level": [ + 0.10055335543313826, + 0.16000830781477135, + 0.20071871019561152, + 0.22713098529648756, + 0.24079657895020376, + 0.24152270950801616, + 0.22895398487771612, + 0.20066991804277617, + 0.14722778873315398 + ], + "n_valid_labels": 74880, + "n_masked_labels": 0, + "mae_median": 2.664961304780348, + "n_mase_elements": 74880, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7339104305377876, + "wql": 0.49584713947875764 + } + }, + { + "config_id": "SZ_TAXI__T__long", + "leaderboard_key": "sz_taxi/15T/long", + "dataset": "SZ_TAXI/15T", + "term": "long", + "freq": "15T", + "prediction_length": 720, + "seasonality": 96, + "n_variates": 1, + "n_instances": 156, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.6084219160390921, + "wql": 0.45522272202116565 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 156, + "instances": 156, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.4892366407143923, + "wql": 0.21701409859296375, + "wsql_by_level": [ + 0.11407537096076763, + 0.17827920673460831, + 0.22033045760660042, + 0.24641461462677927, + 0.25955744852971335, + 0.26259371830874245, + 0.25578967741663144, + 0.2348748703439048, + 0.18121152280892616 + ], + "n_valid_labels": 112320, + "n_masked_labels": 0, + "mae_median": 2.882572438454463, + "n_mase_elements": 112320, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8041075244287519, + "wql": 0.47672070855653303 + } + }, + { + "config_id": "SZ_TAXI__H__short", + "leaderboard_key": "sz_taxi/H/short", + "dataset": "SZ_TAXI/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 156, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.6087142479652129, + "wql": 0.20653078520030457 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 156, + "instances": 156, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.4789992860618626, + "wql": 0.12996334853427044, + "wsql_by_level": [ + 0.06897198767616773, + 0.10811110647871544, + 0.13440078893858362, + 0.1510252292457409, + 0.15887704234808575, + 0.15847626487312882, + 0.15037392827919754, + 0.13501819989614502, + 0.10441558907266896 + ], + "n_valid_labels": 7488, + "n_masked_labels": 0, + "mae_median": 1.7564086338699672, + "n_mase_elements": 7488, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7869033584527443, + "wql": 0.6292686507158003 + } + }, + { + "config_id": "M_DENSE__H__short", + "leaderboard_key": "m_dense/H/short", + "dataset": "M_DENSE/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 30, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.8744657675879529, + "wql": 0.18983266370122717 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 30, + "instances": 30, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7014272657128245, + "wql": 0.12547303211745137, + "wsql_by_level": [ + 0.09076715750820089, + 0.12403264808872966, + 0.14223727948956985, + 0.15174729777855234, + 0.15382610619902243, + 0.14732894848411826, + 0.1337582122715589, + 0.11135431428008001, + 0.07420532495722992 + ], + "n_valid_labels": 1440, + "n_masked_labels": 0, + "mae_median": 96.88854859603777, + "n_mase_elements": 1440, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8021208967934536, + "wql": 0.6609665042414945 + } + }, + { + "config_id": "M_DENSE__H__medium", + "leaderboard_key": "m_dense/H/medium", + "dataset": "M_DENSE/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 1, + "n_instances": 30, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.171624112893389, + "wql": 0.3497462745339787 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 30, + "instances": 30, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7775496376298014, + "wql": 0.13770890981219047, + "wsql_by_level": [ + 0.08204668691771637, + 0.12007674757078524, + 0.14243985481448357, + 0.15670371908640082, + 0.16572163390407646, + 0.16774559562691696, + 0.16028005075015336, + 0.14097074386535807, + 0.10339515577382362 + ], + "n_valid_labels": 14400, + "n_masked_labels": 0, + "mae_median": 97.27205640249782, + "n_mase_elements": 14400, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6636511053955697, + "wql": 0.3937394615444623 + } + }, + { + "config_id": "M_DENSE__H__long", + "leaderboard_key": "m_dense/H/long", + "dataset": "M_DENSE/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 1, + "n_instances": 30, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0805183298420056, + "wql": 0.3841191250034235 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 30, + "instances": 30, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0659757214112402, + "wql": 0.17578245870779574, + "wsql_by_level": [ + 0.08714367062852217, + 0.1387357446550322, + 0.1758661313617176, + 0.202787435628029, + 0.22097494624793582, + 0.2268418482327608, + 0.21715056806147148, + 0.1859829462248472, + 0.1265588373298455 + ], + "n_valid_labels": 21600, + "n_masked_labels": 0, + "mae_median": 129.5058030966476, + "n_mase_elements": 21600, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9865410812300687, + "wql": 0.45762485454539414 + } + }, + { + "config_id": "M_DENSE__D__short", + "leaderboard_key": "m_dense/D/short", + "dataset": "M_DENSE/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 30, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.007688577826318, + "wql": 0.1992117768924222 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 30, + "instances": 30, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.020772649604558, + "wql": 0.09353373242442393, + "wsql_by_level": [ + 0.06210835856201228, + 0.09293344583047891, + 0.11234203988628903, + 0.12272842854587768, + 0.12428271470489424, + 0.11522050047973129, + 0.09829267160634772, + 0.07101965078797506, + 0.042875781416209256 + ], + "n_valid_labels": 900, + "n_masked_labels": 0, + "mae_median": 72.83781740400526, + "n_mase_elements": 900, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.0129842414275088, + "wql": 0.46951909110741863 + } + }, + { + "config_id": "ett1__T__short", + "leaderboard_key": "ett1/15T/short", + "dataset": "ett1/15T", + "term": "short", + "freq": "15T", + "prediction_length": 48, + "seasonality": 96, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.2054822899524387, + "wql": 0.48104386522982623 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7888027261660692, + "wql": 0.2779277805509223, + "wsql_by_level": [ + 0.1632527006379988, + 0.26009080233427695, + 0.31534388767115573, + 0.3481663140076227, + 0.3588455903451864, + 0.3564490414485593, + 0.32297570145786136, + 0.24664648505732994, + 0.1295795019983098 + ], + "n_valid_labels": 336, + "n_masked_labels": 0, + "mae_median": 1.31150373487409, + "n_mase_elements": 336, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6543461755852015, + "wql": 0.5777597442556262 + } + }, + { + "config_id": "ett1__T__medium", + "leaderboard_key": "ett1/15T/medium", + "dataset": "ett1/15T", + "term": "medium", + "freq": "15T", + "prediction_length": 480, + "seasonality": 96, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7745679584044315, + "wql": 0.4386794376669185 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9576580655972651, + "wql": 0.37217155263221297, + "wsql_by_level": [ + 0.18194706894013163, + 0.323666323388698, + 0.4363212137235599, + 0.49290442241015436, + 0.5032129460576568, + 0.4772645313762181, + 0.4155401477341095, + 0.3216510106651255, + 0.19703630939426278 + ], + "n_valid_labels": 3360, + "n_masked_labels": 0, + "mae_median": 1.6409324871697686, + "n_mase_elements": 3360, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.236377073446195, + "wql": 0.8483906941514687 + } + }, + { + "config_id": "ett1__T__long", + "leaderboard_key": "ett1/15T/long", + "dataset": "ett1/15T", + "term": "long", + "freq": "15T", + "prediction_length": 720, + "seasonality": 96, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.327073089604087, + "wql": 0.5796800252115644 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.3127405405944583, + "wql": 0.483379010035574, + "wsql_by_level": [ + 0.3078153895509886, + 0.46978004596580863, + 0.5886489822550586, + 0.6421527048724694, + 0.6392517323368793, + 0.5893501887504228, + 0.502346131875338, + 0.38290990779659806, + 0.22815600691660148 + ], + "n_valid_labels": 5040, + "n_masked_labels": 0, + "mae_median": 2.191577408295716, + "n_mase_elements": 5040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9891998797037588, + "wql": 0.8338721173964143 + } + }, + { + "config_id": "ett1__H__short", + "leaderboard_key": "ett1/H/short", + "dataset": "ett1/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0441605493380515, + "wql": 0.5044116168241106 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7654501769606005, + "wql": 0.34053169979813425, + "wsql_by_level": [ + 0.20037034854411692, + 0.30316871331808887, + 0.37017950049127557, + 0.42291502409286347, + 0.4429189138614952, + 0.43710670560916753, + 0.3978868394210596, + 0.3156682513726157, + 0.17457100147252488 + ], + "n_valid_labels": 336, + "n_masked_labels": 0, + "mae_median": 5.352632882694404, + "n_mase_elements": 336, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7330770899607917, + "wql": 0.6751067747848447 + } + }, + { + "config_id": "ett1__H__medium", + "leaderboard_key": "ett1/H/medium", + "dataset": "ett1/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.2235872159229322, + "wql": 0.5499353323396741 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.4022989534753352, + "wql": 0.4319749682309617, + "wsql_by_level": [ + 0.3000068869182399, + 0.4663812509025683, + 0.5371312546986372, + 0.5571379415948766, + 0.5436509599686682, + 0.5014055205792357, + 0.4318165181598977, + 0.33924090288806963, + 0.21100347836846237 + ], + "n_valid_labels": 3360, + "n_masked_labels": 0, + "mae_median": 8.318978862825869, + "n_mase_elements": 3360, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.1460555775892147, + "wql": 0.7855013904873951 + } + }, + { + "config_id": "ett1__H__long", + "leaderboard_key": "ett1/H/long", + "dataset": "ett1/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.4320631719624162, + "wql": 0.5783242328839591 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.4341623979171871, + "wql": 0.41533553139419976, + "wsql_by_level": [ + 0.296067143156552, + 0.4614648416445946, + 0.5373650011308173, + 0.555914249846608, + 0.5333389479970474, + 0.4787589319400418, + 0.39802179109721897, + 0.2976126748253297, + 0.17947620090958835 + ], + "n_valid_labels": 5040, + "n_masked_labels": 0, + "mae_median": 8.980181941728565, + "n_mase_elements": 5040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.0014658752461976, + "wql": 0.7181707211593483 + } + }, + { + "config_id": "ett1__D__short", + "leaderboard_key": "ett1/D/short", + "dataset": "ett1/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.8181967261759215, + "wql": 0.48528320354978605 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.7456136770525101, + "wql": 0.3393430367121849, + "wsql_by_level": [ + 0.16708577358467294, + 0.2997150295904145, + 0.39917852201229204, + 0.4519025297550269, + 0.45539698029069536, + 0.4277025930791805, + 0.36680828532276766, + 0.2910698922459105, + 0.19522772452870363 + ], + "n_valid_labels": 210, + "n_masked_labels": 0, + "mae_median": 144.55405639012653, + "n_mase_elements": 210, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9600796503049096, + "wql": 0.699268044370654 + } + }, + { + "config_id": "ett1__W__short", + "leaderboard_key": "ett1/W/short", + "dataset": "ett1/W", + "term": "short", + "freq": "W-THU", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.2444126904903803, + "wql": 0.25814356436755426 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0334112657864771, + "wql": 0.19511192833784727, + "wsql_by_level": [ + 0.1365188758418962, + 0.18646994125276536, + 0.22316416384526258, + 0.22993695395103583, + 0.2202101710901306, + 0.21808642311212637, + 0.2149915695143658, + 0.18686156370679977, + 0.1397676927262427 + ], + "n_valid_labels": 56, + "n_masked_labels": 0, + "mae_median": 549.5869876316616, + "n_mase_elements": 56, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8304409571548529, + "wql": 0.7558272034240596 + } + }, + { + "config_id": "ett2__T__short", + "leaderboard_key": "ett2/15T/short", + "dataset": "ett2/15T", + "term": "short", + "freq": "15T", + "prediction_length": 48, + "seasonality": 96, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7618250880337474, + "wql": 0.093929612604377 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0691243391575238, + "wql": 0.1295726029068693, + "wsql_by_level": [ + 0.06644418386726221, + 0.1067616972759831, + 0.13528223615705812, + 0.1546639558347286, + 0.16553469594257797, + 0.1663172894863691, + 0.15587054477125467, + 0.13096141961792904, + 0.08431740320866113 + ], + "n_valid_labels": 336, + "n_masked_labels": 0, + "mae_median": 2.6414159536361694, + "n_mase_elements": 336, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.4033724485457792, + "wql": 1.3794648919996866 + } + }, + { + "config_id": "ett2__T__medium", + "leaderboard_key": "ett2/15T/medium", + "dataset": "ett2/15T", + "term": "medium", + "freq": "15T", + "prediction_length": 480, + "seasonality": 96, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9027189688220486, + "wql": 0.13649095157039726 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8030640989173616, + "wql": 0.09670679843924947, + "wsql_by_level": [ + 0.06423399081615234, + 0.09773339603130497, + 0.1160715699239957, + 0.12396794767773354, + 0.12310439892818535, + 0.11494362613911933, + 0.09991111725495232, + 0.07847273090617496, + 0.051922408275626636 + ], + "n_valid_labels": 3360, + "n_masked_labels": 0, + "mae_median": 1.873439379278127, + "n_mase_elements": 3360, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.889605875863309, + "wql": 0.7085216809362742 + } + }, + { + "config_id": "ett2__T__long", + "leaderboard_key": "ett2/15T/long", + "dataset": "ett2/15T", + "term": "long", + "freq": "15T", + "prediction_length": 720, + "seasonality": 96, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0565955316162643, + "wql": 0.16755935574924186 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9938672674714087, + "wql": 0.12456376988713752, + "wsql_by_level": [ + 0.08527561190589036, + 0.12546567532034486, + 0.14975026644755463, + 0.16168713233533752, + 0.16064147179341953, + 0.14850093562939737, + 0.1268578533946899, + 0.09806682822372582, + 0.06482815393387781 + ], + "n_valid_labels": 5040, + "n_masked_labels": 0, + "mae_median": 2.422793034392054, + "n_mase_elements": 5040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9406317154787691, + "wql": 0.7434008643095485 + } + }, + { + "config_id": "ett2__H__short", + "leaderboard_key": "ett2/H/short", + "dataset": "ett2/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9915624508458626, + "wql": 0.11931409133707109 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6943185000477098, + "wql": 0.07507031452215547, + "wsql_by_level": [ + 0.051966561099286435, + 0.0783054159108081, + 0.0922368257128093, + 0.09720809991651266, + 0.09383656679801608, + 0.08475224083632193, + 0.0718227199477591, + 0.060697238468776116, + 0.044807162009109516 + ], + "n_valid_labels": 336, + "n_masked_labels": 0, + "mae_median": 5.75332183213461, + "n_mase_elements": 336, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7002266972245815, + "wql": 0.6291823009411043 + } + }, + { + "config_id": "ett2__H__medium", + "leaderboard_key": "ett2/H/medium", + "dataset": "ett2/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 2.649073318865916, + "wql": 0.345818716053239 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 2.643226247889965, + "wql": 0.25499835535886245, + "wsql_by_level": [ + 0.10348474273426601, + 0.18325284283172472, + 0.2529445791022333, + 0.3098671776865626, + 0.3470869060181208, + 0.3549721240377209, + 0.32658787607058887, + 0.2616246626183188, + 0.15516428713022637 + ], + "n_valid_labels": 3360, + "n_masked_labels": 0, + "mae_median": 19.740981749795555, + "n_mase_elements": 3360, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9977927862795227, + "wql": 0.7373758085424309 + } + }, + { + "config_id": "ett2__H__long", + "leaderboard_key": "ett2/H/long", + "dataset": "ett2/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 3.171779953228176, + "wql": 0.3702966971424018 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 3.217239770926907, + "wql": 0.35600119816470155, + "wsql_by_level": [ + 0.2809147204738615, + 0.38389533259145425, + 0.43415973517745615, + 0.45461485933452783, + 0.44840415044406406, + 0.4160020325858058, + 0.3579736890495912, + 0.2736002718598844, + 0.15444599196566866 + ], + "n_valid_labels": 5040, + "n_masked_labels": 0, + "mae_median": 25.3020006441526, + "n_mase_elements": 5040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.0143325887574461, + "wql": 0.9613944734370591 + } + }, + { + "config_id": "ett2__D__short", + "leaderboard_key": "ett2/D/short", + "dataset": "ett2/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 4.704440132303346, + "wql": 0.31867490583739955 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 4.718784169842204, + "wql": 0.32862479868423805, + "wsql_by_level": [ + 0.2956310287086753, + 0.3947372900651827, + 0.4289702815002787, + 0.4299851973326122, + 0.4060653666235278, + 0.3608669013916777, + 0.2975913674352013, + 0.22032624874389406, + 0.12344950635709277 + ], + "n_valid_labels": 210, + "n_masked_labels": 0, + "mae_median": 549.1008515312558, + "n_mase_elements": 210, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.0030490424227876, + "wql": 1.0312227058503167 + } + }, + { + "config_id": "ett2__W__short", + "leaderboard_key": "ett2/W/short", + "dataset": "ett2/W", + "term": "short", + "freq": "W-THU", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.7680609986327813, + "wql": 0.21133928538207686 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.6313565009180029, + "wql": 0.17322113657906751, + "wsql_by_level": [ + 0.10089677558653946, + 0.17398282375947882, + 0.2083974824745306, + 0.2234487794602776, + 0.22346405839179256, + 0.2093078165956131, + 0.17599014999065443, + 0.14286772277568716, + 0.10063462017703387 + ], + "n_valid_labels": 56, + "n_masked_labels": 0, + "mae_median": 2174.867308616638, + "n_mase_elements": 56, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9226811191353181, + "wql": 0.8196352905514175 + } + }, + { + "config_id": "jena_weather__T__short", + "leaderboard_key": "jena_weather/10T/short", + "dataset": "jena_weather/10T", + "term": "short", + "freq": "10T", + "prediction_length": 48, + "seasonality": 144, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7621672521709891, + "wql": 0.1366740261223883 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.42506368754986684, + "wql": 0.01856981955599099, + "wsql_by_level": [ + 0.007210905273582506, + 0.012423901112800778, + 0.016066930338628688, + 0.019033032306161542, + 0.021718176319193327, + 0.023349326117566085, + 0.024230490419067028, + 0.023394581555368596, + 0.019701032561550366 + ], + "n_valid_labels": 1008, + "n_masked_labels": 0, + "mae_median": 3.422445672785952, + "n_mase_elements": 1008, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.5577039505949615, + "wql": 0.13586941193465804 + } + }, + { + "config_id": "jena_weather__T__medium", + "leaderboard_key": "jena_weather/10T/medium", + "dataset": "jena_weather/10T", + "term": "medium", + "freq": "10T", + "prediction_length": 480, + "seasonality": 144, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9778443284819783, + "wql": 0.22790411536869984 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8079915133639377, + "wql": 0.08243620174562746, + "wsql_by_level": [ + 0.024199141342453847, + 0.05066583238074013, + 0.07333295014835434, + 0.08985432298659302, + 0.10085726873401463, + 0.10705035839467147, + 0.107216627961412, + 0.10127509005089305, + 0.08747422371151467 + ], + "n_valid_labels": 10080, + "n_masked_labels": 0, + "mae_median": 17.05647369928174, + "n_mase_elements": 10080, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8262987162979991, + "wql": 0.3617144061319973 + } + }, + { + "config_id": "jena_weather__T__long", + "leaderboard_key": "jena_weather/10T/long", + "dataset": "jena_weather/10T", + "term": "long", + "freq": "10T", + "prediction_length": 720, + "seasonality": 144, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9055523182794231, + "wql": 0.2428907683297211 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.69887923255016, + "wql": 0.0772771080783682, + "wsql_by_level": [ + 0.028675612389215108, + 0.05400446463754374, + 0.07294564382227264, + 0.0862915234783594, + 0.09450648850722657, + 0.0971135339819431, + 0.09550598457597362, + 0.08955202752579457, + 0.07689869378698508 + ], + "n_valid_labels": 15120, + "n_masked_labels": 0, + "mae_median": 16.15627516671971, + "n_mase_elements": 15120, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7717712366725005, + "wql": 0.31815580563138374 + } + }, + { + "config_id": "jena_weather__H__short", + "leaderboard_key": "jena_weather/H/short", + "dataset": "jena_weather/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7591774901189448, + "wql": 0.1835169108215369 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.5002520077647185, + "wql": 0.056982976211166374, + "wsql_by_level": [ + 0.023208251512531666, + 0.04844288895513428, + 0.062300807152033136, + 0.0682714738130302, + 0.06912554920231563, + 0.06755988074280572, + 0.06508043892811148, + 0.06077953099702597, + 0.048077964597509196 + ], + "n_valid_labels": 1008, + "n_masked_labels": 0, + "mae_median": 11.550758148245107, + "n_mase_elements": 1008, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6589394631370604, + "wql": 0.310505315047397 + } + }, + { + "config_id": "jena_weather__H__medium", + "leaderboard_key": "jena_weather/H/medium", + "dataset": "jena_weather/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0707310989927863, + "wql": 0.3640989806826866 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8106400277339745, + "wql": 0.09203220889910835, + "wsql_by_level": [ + 0.04511680030274742, + 0.07748143624017623, + 0.09504830841635248, + 0.10403444955384998, + 0.10728704551802766, + 0.10871356648286296, + 0.1072589968987072, + 0.10054001690361468, + 0.08280925977563643 + ], + "n_valid_labels": 10080, + "n_masked_labels": 0, + "mae_median": 18.479673240783196, + "n_mase_elements": 10080, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7570902054647765, + "wql": 0.252767005077981 + } + }, + { + "config_id": "jena_weather__H__long", + "leaderboard_key": "jena_weather/H/long", + "dataset": "jena_weather/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.4925574952113163, + "wql": 0.44387827099252614 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9936591614865578, + "wql": 0.12293836482452841, + "wsql_by_level": [ + 0.06773000931618454, + 0.1183062743636303, + 0.1432374702909704, + 0.15124615423622176, + 0.14850504514336735, + 0.1410347517377777, + 0.13000713279839415, + 0.11462971729041116, + 0.09174872824379843 + ], + "n_valid_labels": 15120, + "n_masked_labels": 0, + "mae_median": 25.88518233129651, + "n_mase_elements": 15120, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6657426361628203, + "wql": 0.2769641427809347 + } + }, + { + "config_id": "jena_weather__D__short", + "leaderboard_key": "jena_weather/D/short", + "dataset": "jena_weather/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.8578467510262653, + "wql": 0.23138296558762514 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.441797277412675, + "wql": 0.11090618102250316, + "wsql_by_level": [ + 0.04983800841726463, + 0.09498550187076114, + 0.12306687765766727, + 0.13737180893923062, + 0.14256235446742488, + 0.13993490043035214, + 0.1283747773341587, + 0.10764005662659314, + 0.07438134345907588 + ], + "n_valid_labels": 630, + "n_masked_labels": 0, + "mae_median": 24.84934110080182, + "n_mase_elements": 630, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7760582387197617, + "wql": 0.47931869461886895 + } + }, + { + "config_id": "bitbrains_fast_storage__T__short", + "leaderboard_key": "bitbrains_fast_storage/5T/short", + "dataset": "bitbrains_fast_storage/5T", + "term": "short", + "freq": "5T", + "prediction_length": 48, + "seasonality": 288, + "n_variates": 2, + "n_instances": 1250, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.9726733005020567, + "wql": 1.8982594024982165 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1250, + "instances": 1250, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0595609193434588, + "wql": 0.4735970284814896, + "wsql_by_level": [ + 0.18545247827032663, + 0.3234091952837677, + 0.43417279635503137, + 0.5177733700533527, + 0.5790663531358169, + 0.6151994400466224, + 0.615615652158664, + 0.5613730184089916, + 0.43031095262083374 + ], + "n_valid_labels": 107692, + "n_masked_labels": 12308, + "mae_median": 170.11299293368194, + "n_mase_elements": 104420, + "n_seasonal_error_zero": 56, + "n_seasonal_error_nan": 52 + }, + "relative": { + "mase": 0.5371193086426396, + "wql": 0.2494901528517173 + } + }, + { + "config_id": "bitbrains_fast_storage__T__medium", + "leaderboard_key": "bitbrains_fast_storage/5T/medium", + "dataset": "bitbrains_fast_storage/5T", + "term": "medium", + "freq": "5T", + "prediction_length": 480, + "seasonality": 288, + "n_variates": 2, + "n_instances": 1250, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.332305698225943, + "wql": 0.7965658755181099 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1250, + "instances": 1250, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.1132358234524542, + "wql": 0.6717320801494656, + "wsql_by_level": [ + 0.49431387258202136, + 0.859257425799887, + 0.9337474985411677, + 0.9059732847144202, + 0.829176900689834, + 0.720842382844964, + 0.5920364620548688, + 0.44217361934296495, + 0.2680672747750615 + ], + "n_valid_labels": 1151890, + "n_masked_labels": 48110, + "mae_median": 515.3793875426326, + "n_mase_elements": 1112970, + "n_seasonal_error_zero": 58, + "n_seasonal_error_nan": 66 + }, + "relative": { + "mase": 0.8355708640553025, + "wql": 0.8432850324055764 + } + }, + { + "config_id": "bitbrains_fast_storage__T__long", + "leaderboard_key": "bitbrains_fast_storage/5T/long", + "dataset": "bitbrains_fast_storage/5T", + "term": "long", + "freq": "5T", + "prediction_length": 720, + "seasonality": 288, + "n_variates": 2, + "n_instances": 1250, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.5068539886984111, + "wql": 0.6979053733746295 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1250, + "instances": 1250, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.2531731191602986, + "wql": 0.5009270179457473, + "wsql_by_level": [ + 0.3427343299570727, + 0.5608441799505401, + 0.6412828975356554, + 0.6615356147436766, + 0.6394838295095088, + 0.5778928149037375, + 0.4884984279169134, + 0.37155792987725644, + 0.22451313711736565 + ], + "n_valid_labels": 1732080, + "n_masked_labels": 67920, + "mae_median": 466.8335167766776, + "n_mase_elements": 1677544, + "n_seasonal_error_zero": 58, + "n_seasonal_error_nan": 66 + }, + "relative": { + "mase": 0.831648672372539, + "wql": 0.7177577893168822 + } + }, + { + "config_id": "bitbrains_fast_storage__H__short", + "leaderboard_key": "bitbrains_fast_storage/H/short", + "dataset": "bitbrains_fast_storage/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 2, + "n_instances": 1250, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.5571822067903167, + "wql": 0.6231221387021137 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1250, + "instances": 1250, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.3557457081025746, + "wql": 0.48595747274395884, + "wsql_by_level": [ + 0.3395306809010071, + 0.5564362247068594, + 0.6392798547759958, + 0.6482509373112609, + 0.6091982324628099, + 0.5402189626925754, + 0.45852189170273, + 0.3589025995874317, + 0.22327787055495957 + ], + "n_valid_labels": 116442, + "n_masked_labels": 3558, + "mae_median": 430.0970133095566, + "n_mase_elements": 112610, + "n_seasonal_error_zero": 58, + "n_seasonal_error_nan": 66 + }, + "relative": { + "mase": 0.870640379905865, + "wql": 0.7798751521750584 + } + }, + { + "config_id": "bitbrains_rnd__T__short", + "leaderboard_key": "bitbrains_rnd/5T/short", + "dataset": "bitbrains_rnd/5T", + "term": "short", + "freq": "5T", + "prediction_length": 48, + "seasonality": 288, + "n_variates": 2, + "n_instances": 500, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.8369702659182979, + "wql": 0.895586111036325 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 500, + "instances": 500, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.5522592884480294, + "wql": 0.22164335933353876, + "wsql_by_level": [ + 0.1127926369438007, + 0.1721274488040864, + 0.21275590923414522, + 0.24047438818106, + 0.2549710648085543, + 0.2615183730568679, + 0.25961441659941636, + 0.2579719938712616, + 0.22256400250265626 + ], + "n_valid_labels": 46368, + "n_masked_labels": 1632, + "mae_median": 136.6330288343557, + "n_mase_elements": 45888, + "n_seasonal_error_zero": 10, + "n_seasonal_error_nan": 34 + }, + "relative": { + "mase": 0.6598314312182973, + "wql": 0.24748414094660842 + } + }, + { + "config_id": "bitbrains_rnd__T__medium", + "leaderboard_key": "bitbrains_rnd/5T/medium", + "dataset": "bitbrains_rnd/5T", + "term": "medium", + "freq": "5T", + "prediction_length": 480, + "seasonality": 288, + "n_variates": 2, + "n_instances": 500, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9740075110165132, + "wql": 1.1044931903333195 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 500, + "instances": 500, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8228904574251987, + "wql": 0.8692852543548634, + "wsql_by_level": [ + 0.34550572402105717, + 0.6964839259462611, + 0.8793455732716832, + 0.983288536296222, + 1.0380928253203479, + 1.0514956605141206, + 1.0257743776136368, + 0.9599799553618625, + 0.843600710848579 + ], + "n_valid_labels": 455110, + "n_masked_labels": 24890, + "mae_median": 311.7584897692069, + "n_mase_elements": 441864, + "n_seasonal_error_zero": 10, + "n_seasonal_error_nan": 54 + }, + "relative": { + "mase": 0.8448502173934956, + "wql": 0.7870444670578061 + } + }, + { + "config_id": "bitbrains_rnd__T__long", + "leaderboard_key": "bitbrains_rnd/5T/long", + "dataset": "bitbrains_rnd/5T", + "term": "long", + "freq": "5T", + "prediction_length": 720, + "seasonality": 288, + "n_variates": 2, + "n_instances": 500, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.1660081104198932, + "wql": 0.9977535818816068 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 500, + "instances": 500, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9668616409502403, + "wql": 0.736896502924739, + "wsql_by_level": [ + 0.27097678982512374, + 0.434307750966378, + 0.573621461688675, + 0.7022924541317032, + 0.8193812194072506, + 0.9248933808921609, + 1.0057299988876078, + 1.03666225287697, + 0.8642032176467815 + ], + "n_valid_labels": 684238, + "n_masked_labels": 35762, + "mae_median": 268.03903531242247, + "n_mase_elements": 657984, + "n_seasonal_error_zero": 12, + "n_seasonal_error_nan": 64 + }, + "relative": { + "mase": 0.8292066172696364, + "wql": 0.7385556076231445 + } + }, + { + "config_id": "bitbrains_rnd__H__short", + "leaderboard_key": "bitbrains_rnd/H/short", + "dataset": "bitbrains_rnd/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 2, + "n_instances": 500, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.1175347302132743, + "wql": 0.9314629241561541 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 500, + "instances": 500, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9118106715409983, + "wql": 0.6115213461722179, + "wsql_by_level": [ + 0.16972897853361957, + 0.3324894608094526, + 0.5053670080316758, + 0.6553233850789794, + 0.7832094653145414, + 0.8429954901609238, + 0.8340238041183313, + 0.7678665080767836, + 0.6126880154256532 + ], + "n_valid_labels": 46216, + "n_masked_labels": 1784, + "mae_median": 253.71041264381097, + "n_mase_elements": 44928, + "n_seasonal_error_zero": 10, + "n_seasonal_error_nan": 54 + }, + "relative": { + "mase": 0.815912603778305, + "wql": 0.6565171090692817 + } + }, + { + "config_id": "bizitobs_application__S__short", + "leaderboard_key": "bizitobs_application/10S/short", + "dataset": "bizitobs_application", + "term": "short", + "freq": "10S", + "prediction_length": 60, + "seasonality": 360, + "n_variates": 2, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.3935671590031806, + "wql": 0.01840457246049758 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.5359989052382924, + "wql": 0.009643967851615436, + "wsql_by_level": [ + 0.0057046977116642405, + 0.00918306764940154, + 0.011440299765165139, + 0.012639381068455857, + 0.012936762256220116, + 0.012309326682358672, + 0.010549458097500459, + 0.0077678531723878765, + 0.004264864261385011 + ], + "n_valid_labels": 120, + "n_masked_labels": 0, + "mae_median": 334.7438988367716, + "n_mase_elements": 120, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.3846236629325369, + "wql": 0.5239984722445818 + } + }, + { + "config_id": "bizitobs_application__S__medium", + "leaderboard_key": "bizitobs_application/10S/medium", + "dataset": "bizitobs_application", + "term": "medium", + "freq": "10S", + "prediction_length": 600, + "seasonality": 360, + "n_variates": 2, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9183336447716528, + "wql": 0.013742470259025481 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6711713421669759, + "wql": 0.008984027603928727, + "wsql_by_level": [ + 0.005323190393375884, + 0.008029034394828672, + 0.009898785909355872, + 0.01104337519240538, + 0.01153132037303162, + 0.011264348936130692, + 0.010239338572766061, + 0.008322097295636486, + 0.005204757367827888 + ], + "n_valid_labels": 1200, + "n_masked_labels": 0, + "mae_median": 276.0610501797994, + "n_mase_elements": 1200, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7308578379853058, + "wql": 0.6537418262214096 + } + }, + { + "config_id": "bizitobs_application__S__long", + "leaderboard_key": "bizitobs_application/10S/long", + "dataset": "bizitobs_application", + "term": "long", + "freq": "10S", + "prediction_length": 900, + "seasonality": 360, + "n_variates": 2, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7487259254586917, + "wql": 0.012942679940654697 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.71128597190969, + "wql": 0.009394690839900417, + "wsql_by_level": [ + 0.005612042508326105, + 0.008793518944893426, + 0.010770634280137324, + 0.011789195115689547, + 0.011960157637268301, + 0.011505332485897062, + 0.010371745400463168, + 0.008418516388620628, + 0.0053310747978081935 + ], + "n_valid_labels": 1800, + "n_masked_labels": 0, + "mae_median": 291.41366638819375, + "n_mase_elements": 1800, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9499951153340058, + "wql": 0.7258690536254729 + } + }, + { + "config_id": "bizitobs_service__S__short", + "leaderboard_key": "bizitobs_service/10S/short", + "dataset": "bizitobs_service", + "term": "short", + "freq": "10S", + "prediction_length": 60, + "seasonality": 360, + "n_variates": 2, + "n_instances": 21, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0559084960397855, + "wql": 0.025515037101462117 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 21, + "instances": 21, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.5077099706750252, + "wql": 0.008998604087554901, + "wsql_by_level": [ + 0.005521335415721979, + 0.008705402679087404, + 0.010756049978742677, + 0.011821542409289839, + 0.01200833840927016, + 0.011394726621548175, + 0.009866809918407785, + 0.007258289637673805, + 0.0036549417182522867 + ], + "n_valid_labels": 2520, + "n_masked_labels": 0, + "mae_median": 16.101720323165257, + "n_mase_elements": 2520, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.48082762150243674, + "wql": 0.35267846375340933 + } + }, + { + "config_id": "bizitobs_service__S__medium", + "leaderboard_key": "bizitobs_service/10S/medium", + "dataset": "bizitobs_service", + "term": "medium", + "freq": "10S", + "prediction_length": 600, + "seasonality": 360, + "n_variates": 2, + "n_instances": 21, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9546641394188339, + "wql": 0.023513421962609537 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 21, + "instances": 21, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6728693930665967, + "wql": 0.00978390371798002, + "wsql_by_level": [ + 0.006068202426554646, + 0.00920465658248177, + 0.01115294366803445, + 0.01218973604158093, + 0.012438689978171371, + 0.011970879660823497, + 0.010784043114237314, + 0.008750642374627044, + 0.005495339615309152 + ], + "n_valid_labels": 25200, + "n_masked_labels": 0, + "mae_median": 15.689066439990013, + "n_mase_elements": 25200, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7048231574679406, + "wql": 0.416098674771292 + } + }, + { + "config_id": "bizitobs_service__S__long", + "leaderboard_key": "bizitobs_service/10S/long", + "dataset": "bizitobs_service", + "term": "long", + "freq": "10S", + "prediction_length": 900, + "seasonality": 360, + "n_variates": 2, + "n_instances": 21, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.8316933390369606, + "wql": 0.023678985220657325 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 21, + "instances": 21, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7390892127768683, + "wql": 0.01052251848226473, + "wsql_by_level": [ + 0.006303620927835894, + 0.00982751677559253, + 0.011985547948049943, + 0.013160362682732437, + 0.01348667829420396, + 0.013045781149310024, + 0.011695384116351916, + 0.009326074157188098, + 0.005871700289117752 + ], + "n_valid_labels": 37800, + "n_masked_labels": 0, + "mae_median": 17.23375119488209, + "n_mase_elements": 37800, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8886559241086132, + "wql": 0.4443821550716195 + } + }, + { + "config_id": "bizitobs_l2c__T__short", + "leaderboard_key": "bizitobs_l2c/5T/short", + "dataset": "bizitobs_l2c/5T", + "term": "short", + "freq": "5T", + "prediction_length": 48, + "seasonality": 288, + "n_variates": 7, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7721410982041648, + "wql": 0.22094461659341424 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.17679616231949047, + "wql": 0.05225718698172213, + "wsql_by_level": [ + 0.03925643911138059, + 0.05755099597711412, + 0.06674067187613171, + 0.0687314436555529, + 0.06519111341698927, + 0.059236544091580766, + 0.04875850804598447, + 0.038104701100191034, + 0.026744265560574357 + ], + "n_valid_labels": 336, + "n_masked_labels": 0, + "mae_median": 1.6747112047104609, + "n_mase_elements": 336, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.2289687244088944, + "wql": 0.23651713170222485 + } + }, + { + "config_id": "bizitobs_l2c__T__medium", + "leaderboard_key": "bizitobs_l2c/5T/medium", + "dataset": "bizitobs_l2c/5T", + "term": "medium", + "freq": "5T", + "prediction_length": 480, + "seasonality": 288, + "n_variates": 7, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.4416925389331963, + "wql": 0.47091183801289255 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.46848404473560407, + "wql": 0.1510172398993052, + "wsql_by_level": [ + 0.12003583258648982, + 0.16682856296646262, + 0.18847655856915066, + 0.1876916692386434, + 0.17985512032859494, + 0.168195183951577, + 0.14845650350944847, + 0.11613928886734283, + 0.08347643907603738 + ], + "n_valid_labels": 3360, + "n_masked_labels": 0, + "mae_median": 4.002788110964355, + "n_mase_elements": 3360, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.32495419937614883, + "wql": 0.32069110969168435 + } + }, + { + "config_id": "bizitobs_l2c__T__long", + "leaderboard_key": "bizitobs_l2c/5T/long", + "dataset": "bizitobs_l2c/5T", + "term": "long", + "freq": "5T", + "prediction_length": 720, + "seasonality": 288, + "n_variates": 7, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.6820288964143004, + "wql": 0.6755692567838184 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7421965593882325, + "wql": 0.2788864625769831, + "wsql_by_level": [ + 0.14417182326227415, + 0.2344585383837265, + 0.29881530334355294, + 0.34112690104663096, + 0.3736436645100047, + 0.3781571177115724, + 0.34965911923901455, + 0.2586206627433235, + 0.13132503295274797 + ], + "n_valid_labels": 5040, + "n_masked_labels": 0, + "mae_median": 6.835290412347586, + "n_mase_elements": 5040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.441250778134921, + "wql": 0.4128169832722665 + } + }, + { + "config_id": "bizitobs_l2c__H__short", + "leaderboard_key": "bizitobs_l2c/H/short", + "dataset": "bizitobs_l2c/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.5845833438972332, + "wql": 0.5573763030242874 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6928768481477755, + "wql": 0.20797742641030625, + "wsql_by_level": [ + 0.12240721840931813, + 0.21155459265322296, + 0.276819768510729, + 0.2995546365621544, + 0.2987066970386158, + 0.26213493967517326, + 0.19558968891391904, + 0.1280950347684782, + 0.07693426116114559 + ], + "n_valid_labels": 336, + "n_masked_labels": 0, + "mae_median": 6.249616025348327, + "n_mase_elements": 336, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.4372612212644281, + "wql": 0.3731364704273115 + } + }, + { + "config_id": "bizitobs_l2c__H__medium", + "leaderboard_key": "bizitobs_l2c/H/medium", + "dataset": "bizitobs_l2c/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.6159633796006725, + "wql": 1.1167911109559348 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.34959065141955087, + "wql": 0.20932674631009585, + "wsql_by_level": [ + 0.11318268696774314, + 0.17738185335623746, + 0.21450388411946306, + 0.23874350880480108, + 0.2516653252604674, + 0.2509916166094093, + 0.2410669874465027, + 0.22251480120544667, + 0.17389005302079177 + ], + "n_valid_labels": 3360, + "n_masked_labels": 0, + "mae_median": 3.4444815153743895, + "n_mase_elements": 3360, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.21633575106506417, + "wql": 0.18743589938759395 + } + }, + { + "config_id": "bizitobs_l2c__H__long", + "leaderboard_key": "bizitobs_l2c/H/long", + "dataset": "bizitobs_l2c/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.280223980485366, + "wql": 1.0134048622912797 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.4285811280591097, + "wql": 0.21457750329396427, + "wsql_by_level": [ + 0.11710240939381998, + 0.18733237010655004, + 0.23211276443108572, + 0.2552425854797665, + 0.2615435194229197, + 0.2541150976118119, + 0.24252335521671514, + 0.21681865546301984, + 0.16440677251998959 + ], + "n_valid_labels": 5040, + "n_masked_labels": 0, + "mae_median": 3.951614459914466, + "n_mase_elements": 5040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.33477042657537437, + "wql": 0.21173916889327984 + } + } + ], + "checkpoint_sha256": "a75fdfcbb4d8e38dd6e7cded3c097ff0a129976fa63277bfd277a6031ccc6140", + "inference_seconds": 784.6361561322119, + "minimum_free_before_replay_mib": 16000.0, + "observed_free_before_replay_mib": 17572.0, + "memory_guard_and_lock_wait_seconds": 675.3585297530517 +} diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/zero_mass.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/zero_mass.py new file mode 100644 index 0000000000000000000000000000000000000000..7e9c7067950c67da130e2c2538ffb42f34537402 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S126/zero_mass.py @@ -0,0 +1,12 @@ +"""Fixed zero-mass projection from the supplied history only.""" +import numpy as np + +def project(ctx,q,threshold=.4): + finite=np.isfinite(ctx);n=finite.sum(-1).clip(min=1) + x=np.where(finite,ctx,0.) + mean=x.sum(-1)/n + scale=np.sqrt((np.where(finite,ctx-mean[...,None],0.)**2).sum(-1)/n) + zero=((ctx==0)&finite).sum(-1) + active=((ctx>=0)|~finite).all(-1)&(zero>=4)&(zero/n>=.1) + cutoff=np.where(active,threshold*scale,0.) + return np.where((q>=0)&(q=720 else 3])/4; A2=(F0+F1+F2+F5)/4; A=(A1+A2)/2; output=(A+G)/2. G is the unchanged frozen gate evaluated on the new F0 and unchanged F1/F2/F3. Each member retains its own normalization and fixed output rules. + +All runtime assets and pins are included. No pretrained weights, external data, per-dataset fitting or inference-time optimization are used. Provenance records source lineage and fixed transfer. EXPERIMENTS.md includes negative results. Validation skill is not the held-out reward scale. diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/config.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/config.json new file mode 100644 index 0000000000000000000000000000000000000000..d631f5970b552fde4286914e3207cb02f561f0ac --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/config.json @@ -0,0 +1,163 @@ +{ + "members": [ + { + "weights": "member0.pt", + "weights_sha256": "0d4f90210ec38a1256db86115b600ba839a299594174d9da5fcf822aa82c7c55", + "parameters": 36997536, + "config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true, + "seasonal_dispersion_features": true, + "seasonal_width_features": true, + "spectral_phase_features": true, + "individual_spectral_spans": true + }, + "model_code": "model0.py" + }, + { + "weights": "member1.pt", + "weights_sha256": "308389b7217c080af9eb185559d4ee3cafa0f3e0f8c4dd8f5526b68198c89988", + "parameters": 36665488, + "config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "model_code": "model1.py" + }, + { + "weights": "member2.pt", + "weights_sha256": "1a2fb20a9fb5cae6526f2e36ea47559626bece78fd9c284899836505030ae9fe", + "parameters": 36601928, + "config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 4, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "input_patch": 8 + }, + "model_code": "model2.py" + }, + { + "weights": "member3.pt", + "weights_sha256": "d7cfcd72c3cb84aa69e447b76c4c3ab98c21b7c600a463f0b805f4b4300baf33", + "parameters": 146477344, + "config": { + "d": 1024, + "heads": 16, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "model_code": "model3.py" + }, + { + "weights": "member4.pt", + "weights_sha256": "2877a38b94a7d77a53a9df410349cecc2f6ab134c83a76744924543bbe73eb17", + "parameters": 146206864, + "config": { + "d": 1024, + "heads": 16, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "model_code": "model4.py" + }, + { + "weights": "member5.pt", + "weights_sha256": "4b309f0721378f97db815dd511b8b54711348270c48e9eae0103dba506f66708", + "parameters": 146575680, + "config": { + "d": 1024, + "heads": 16, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true + }, + "model_code": "model5.py" + } + ], + "horizon_threshold": 720, + "blend_coefficient": 0.5, + "weights_below_threshold": [ + 0.25, + 0.25, + 0.25, + 0.125, + 0, + 0.125 + ], + "weights_at_or_above_threshold": [ + 0.25, + 0.25, + 0.25, + 0, + 0.125, + 0.125 + ], + "composition": "Every six-expert and fixed gate executes everyinstance. Preserve orderedE159 two-quartermeans asA; G is orderedFP32E152primary6k boundedgate on F0/F1/F2/F3 with cumulative-maximum guard. Final(A+G)/2 inFP32.", + "parent_descriptor_sha256": "20f014ca61a9cfa4f275d9d7abfd297561ac37fddcdae9ba2ef60d3fca106cf8", + "gate_blend_coefficient": 0.5, + "gate": { + "weights": "gate.pt", + "weights_sha256": "a7d0ee6866ea787f29eac043531aad3613674f159fd00b3491fd87fab8388fd1", + "parameters": 6340, + "config": { + "input_dim": 29, + "hidden": 64, + "members": 4, + "mixing": 0.5, + "max_context": 4096 + }, + "model_code": "gate_model.py", + "expert_member_indices": [ + 0, + 1, + 2, + 3 + ] + }, + "replacement_parent_descriptor_sha256": "a75fdfcbb4d8e38dd6e7cded3c097ff0a129976fa63277bfd277a6031ccc6140", + "replacement_member_index": 0, + "replacement_study": "E192", + "replacement_step": 6000 +} diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/continuity.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/continuity.py new file mode 100644 index 0000000000000000000000000000000000000000..bebb06b9c20f322b9d5564650889e2236ae94494 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/continuity.py @@ -0,0 +1,18 @@ +"""Fixed continuity prior for histories whose adjacent samples change slowly.""" +import numpy as np + +def apply_continuity(ctx,quant,tau=24.): + b,_,h=quant.shape + bias=np.zeros(b,np.float32) + positive=((ctx>=0)|~np.isfinite(ctx)).all(-1) + for i in range(b): + x=ctx[i,-512:].astype(np.float64) + if len(x)<8 or not np.isfinite(x[-1]):continue + diff=np.diff(x) + if np.isfinite(diff).sum()<8 or not np.isfinite(diff[-8:]).any():continue + ratio=np.nanmean(diff*diff)/(np.nanvar(x)+1e-12) + weight=float(np.clip(1-ratio/.5,0,.95)) + bias[i]=weight*(x[-1]+np.nanmedian(diff[-8:])-quant[i,4,0]) + out=quant+bias[:,None,None]*np.exp(-np.arange(h)/tau)[None,None,:] + out=np.where(positive[:,None,None],np.maximum(0,out),out) + return out.astype(np.float32) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/gate_frequency.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/gate_frequency.py new file mode 100644 index 0000000000000000000000000000000000000000..bdeffd8b2d20972fa082c6875d5e16e0a9e21f1f --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/gate_frequency.py @@ -0,0 +1,14 @@ +"""Frequency mapping copied verbatim from our own E80 model.""" +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/gate_model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/gate_model.py new file mode 100644 index 0000000000000000000000000000000000000000..0264c4248ea232da87371714e27db47f2e968bb4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/gate_model.py @@ -0,0 +1,97 @@ +"""A small fixed-parameter gate over four frozen scratch-trained forecasting experts.""" +import torch +from torch import nn +from torch.nn import functional as F +from gate_normalization import standardize as original_standardize +from gate_frequency import periods_for_freq + +FEATURE_NAMES=['log_finite_count','log_period0','log_period1','log_horizon','lead_fraction','log_lead','finite_fraction','log_absdiff_lag1','log_absdiff_period0','log_absdiff_period1','adjacent_mean4','adjacent_mean16','adjacent_mean128']+[f'{kind}_expert{i}' for kind in ['median_from_consensus','log_width80','median_from_last','median_from_mean32'] for i in range(4)] +assert len(FEATURE_NAMES)==29 + +def statistics(ctx): + ctx=ctx[:,-4096:];ctx=F.pad(ctx,((-ctx.shape[1])%16,0),value=float('nan')) + z,valid,mu,scale=original_standardize(ctx) + # Preserve ordinary arithmetic, and keep gate inputs defined at float32 extremes. + z=torch.nan_to_num(z,nan=0.,posinf=30.,neginf=-30.) + mu=torch.nan_to_num(mu,nan=0.,posinf=0.,neginf=0.) + scale=torch.where(torch.isfinite(scale)&(scale>0),scale,torch.ones_like(scale)) + return z,valid,mu,scale + +def gate_features(ctx,periods,expert_quantiles,lengths): + """Expert quantiles are final raw-scale (batch,4,horizon,9) forecasts.""" + assert expert_quantiles.shape[1]==4 and expert_quantiles.shape[-1]==9 + z,valid,mu,scale=statistics(ctx);b,c=z.shape;h=expert_quantiles.shape[2] + lengths=lengths.clamp(min=1,max=h);position=torch.arange(c,device=z.device)[None,:] + count=valid.sum(-1);first=torch.where(valid,position,c).min(-1).values;span=c-first + context=[count.float().log1p()/8,periods[:,0].float().log1p()/8,periods[:,1].float().log1p()/8] + context.append(lengths.float().log1p()/8) + lead=torch.arange(h,device=z.device).float()[None,:] + pieces=[torch.stack(context,-1)[:,None,:].expand(-1,h,-1),((lead+.5)/lengths[:,None]).clamp(max=1)[:,:,None],(lead+1).log1p().expand(b,-1)[:,:,None]/8,(count/span.clamp(min=1)).float()[:,None,None].expand(-1,h,-1)] + differences=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + index=position-lag;safe=index.clamp(min=0,max=c-1) + pairs=(index>=0)&(position>=c-window)&valid&valid.gather(1,safe) + n=pairs.sum(-1);absolute=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/n.clamp(min=1) + absolute=torch.where(n>=8,absolute,1.) + differences.append(absolute.clamp(max=10).log1p()) + adjacent=[] + for k in (4,16,128): + vr=valid[:,-k:];vo=valid[:,-2*k:-k];nr=vr.sum(-1);no=vo.sum(-1) + recent=(z[:,-k:]*vr).sum(-1)/nr.clamp(min=1) + older=(z[:,-2*k:-k]*vo).sum(-1)/no.clamp(min=1) + active=(nr>=max(2,k//2))&(no>=max(2,k//2)) + adjacent.append(torch.where(active,(recent-older).abs().clamp(max=30),0.)) + pieces.extend([torch.stack(differences,-1)[:,None,:].expand(-1,h,-1),torch.stack(adjacent,-1)[:,None,:].expand(-1,h,-1)]) + # Expert disagreement can subtract large, nearly equal normalized medians. + # Compute these fixed features in float64, then feed the small gate float32. + normalized=(expert_quantiles.double()-mu.double()[:,None,None,:])/scale.double()[:,None,None,:] + median=normalized[:,:,:,4].transpose(1,2) + consensus=(median[:,:,0]+median[:,:,1]+median[:,:,2]+median[:,:,3])/4 + last_index=torch.where(valid,position,-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_index[:,None])[:,0] + mean32=(z[:,-32:]*valid[:,-32:]).sum(-1)/valid[:,-32:].sum(-1).clamp(min=1) + pieces.extend([(median-consensus[:,:,None]).abs().clamp(max=30),(normalized[:,:,:,8]-normalized[:,:,:,0]).transpose(1,2).clamp(0,60).log1p(),(median-last[:,None,None]).abs().clamp(max=30),(median-mean32[:,None,None]).abs().clamp(max=30)]) + features=torch.cat(pieces,-1).float();assert features.shape==(b,h,29) + return torch.nan_to_num(features,nan=0.,posinf=30.,neginf=0.).clamp(0,30) + +def combine(expert_quantiles,weights): + """Same positive weight across all quantiles at each lead; fixed ordered accumulation.""" + q=expert_quantiles[:,0]*weights[:,:,0,None] + for i in range(1,4):q=q+expert_quantiles[:,i]*weights[:,:,i,None] + q=torch.nan_to_num(q,nan=0.,posinf=1e20,neginf=-1e20) + return q.cummax(-1).values + +class DirectForecaster(nn.Module): + def __init__(self,input_dim=29,hidden=64,members=4,mixing=.5,max_context=4096): + super().__init__();assert input_dim==29 and members==4 and mixing==.5 and max_context==4096 + self.max_context=max_context;self.mixing=mixing + self.config=dict(input_dim=input_dim,hidden=hidden,members=members,mixing=mixing,max_context=max_context) + self.net=nn.Sequential(nn.Linear(input_dim,hidden),nn.GELU(),nn.Linear(hidden,hidden),nn.GELU(),nn.Linear(hidden,members)) + nn.init.zeros_(self.net[-1].weight);nn.init.zeros_(self.net[-1].bias) + def forward(self,ctx,periods,expert_quantiles,lengths): + with torch.autocast(device_type=ctx.device.type,enabled=False): + features=gate_features(ctx.float(),periods,expert_quantiles.float(),lengths) + return .125+.5*self.net(features).softmax(-1) + +def loss_fn(model,ctx,target,periods,expert_quantiles,paired=True): + assert paired + with torch.autocast(device_type=ctx.device.type,enabled=False): + valid=torch.isfinite(target);pos=torch.arange(target.shape[-1],device=ctx.device)[None,:]+1 + lengths=torch.where(valid,pos,0).max(-1).values.clamp(min=1) + weights=model(ctx,periods,expert_quantiles,lengths) + prediction=combine(expert_quantiles.float(),weights) + z,seen,mu,scale=statistics(ctx) + q=(prediction-mu[:,:,None])/scale[:,:,None] + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + error=y[:,:,None]-q;levels=torch.arange(1,10,device=q.device)/10 + pin=.5*torch.maximum(levels*error,(levels-1)*error).mean(-1)+.25*error[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + with torch.no_grad(): + c=z.shape[-1];position=torch.arange(c,device=z.device)[None,:];lag=periods[:,0:1].clamp(min=1);index=position-lag;safe=index.clamp(min=0) + pairs=(index>=0)&seen&seen.gather(1,safe);count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/gate_normalization.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/gate_normalization.py new file mode 100644 index 0000000000000000000000000000000000000000..f1cfec8685b97bc4c979e1daf9c9a3013a136d6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/gate_normalization.py @@ -0,0 +1,21 @@ +"""Canonical normalization copied from our own E79 model; no learned statistics.""" +import torch + +def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/infer.sh b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/infer.sh new file mode 100644 index 0000000000000000000000000000000000000000..725d90e5f2b609f06c4859c24b159192052d0b14 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/infer.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +export NUMPY_MADVISE_HUGEPAGE=0 +export OMP_NUM_THREADS=4 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=4 +exec python3 "$(dirname "$(readlink -f "$0")")/predict.py" "$1" "$2" diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/model.py new file mode 100644 index 0000000000000000000000000000000000000000..dedcdff4698028a8ba655865f8425d0dc3ef0dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/model.py @@ -0,0 +1,204 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/model0.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/model0.py new file mode 100644 index 0000000000000000000000000000000000000000..3fe3080070ae4e2fb33129b66305ca3558a28dcd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/model0.py @@ -0,0 +1,347 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + + +def centered_seasonal_difference(z, valid, periods, horizon): + b, c = z.shape + time = torch.arange(horizon, device=z.device)[None, :] + sums = F.pad((z * valid).cumsum(-1), (1, 0)) + counts = F.pad(valid.float().cumsum(-1), (1, 0)) + deltas, extras, dispersion, width_deltas = [], [], [], [] + for j in range(2): + period = periods[:, j:j+1].clamp(min=1) + anchor = c - period + time % period + centered, masks = [], [] + for cycle in range(16): + end = (c - cycle * period).clamp(min=0, max=c) + start = (c - (cycle + 1) * period).clamp(min=0, max=c) + count = counts.gather(1, end) - counts.gather(1, start) + mean = (sums.gather(1, end) - sums.gather(1, start)) / count.clamp(min=1) + index = anchor - cycle * period + safe = index.clamp(min=0, max=c-1) + present = (index >= 0) & valid.gather(1, safe) + centered.append(z.gather(1, safe) - mean) + masks.append(present) + values = torch.stack(centered) + seen = torch.stack(masks) + n4 = seen[:4].sum(0) + n16 = seen.sum(0) + mean4 = (values[:4] * seen[:4]).sum(0) / n4.clamp(min=1) + mean16 = (values * seen).sum(0) / n16.clamp(min=1) + active = (period >= 2) & (n4 >= 2) & (n16 >= 8) + delta = torch.where(active, mean16 - mean4, 0.) + support = torch.where(active, n16.float() / 16, 0.) + deltas.append(delta) + extras.extend([delta, support]) + variance4 = (((values[:4] - mean4).square() * seen[:4]).sum(0) / (n4 - 1).clamp(min=1)) + variance16 = (((values - mean16).square() * seen).sum(0) / (n16 - 1).clamp(min=1)) + width_deltas.append(torch.where(active, variance16.sqrt().log1p() - math.log(2.), 0.)) + dispersion.extend([torch.where(active, variance4.sqrt().log1p(), 0.), + torch.where(active, variance16.sqrt().log1p(), 0.)]) + return torch.stack(deltas, -1), torch.stack(extras, -1), torch.stack(dispersion, -1), torch.stack(width_deltas, -1) + + + +def seasonal_width_multiplier(raw, delta): + return ((raw.float().tanh() * delta).sum(-1).clamp(-math.log(4.), math.log(4.))).exp() + +@torch.no_grad() +def _spectral_window(z, valid, horizon): + """Fixed windowed Fourier projections; no optimization or fitted model state.""" + z=z[:,-4096:].float();valid=valid[:,-4096:] + b,c=z.shape;nfft=8*(1 << (c-1).bit_length()) + window=torch.hann_window(c,periodic=False,device=z.device,dtype=torch.float32) + weight=valid.float()*window[None,:] + total=weight.sum(-1,keepdim=True).clamp(min=1e-8) + mean=(z*weight).sum(-1,keepdim=True)/total + centered=z-mean + variance=(centered.square()*weight).sum(-1,keepdim=True)/total + spectrum=torch.fft.rfft(centered*weight,n=nfft,dim=-1) + power=spectrum.real.square()+spectrum.imag.square() + frequencies=torch.arange(power.shape[-1],device=z.device).float()/nfft + local=F.max_pool1d(power[:,None,:],kernel_size=17,stride=1,padding=8)[:,0] + eligible=(frequencies>=4/c)&(frequencies<.5) + peaks=torch.where((power==local)&eligible[None,:],power,-torch.inf) + scores,indices=torch.topk(peaks,4,dim=-1,sorted=True) + coefficient=spectrum.gather(1,indices) + magnitude=coefficient.abs() + amplitude=(2*magnitude/total).clamp(max=30.) + active=(c>=128)&(valid.float().mean(-1,keepdim=True)>=.9)&torch.isfinite(scores)&(scores>0) + real=amplitude*coefficient.real/magnitude.clamp(min=1e-20) + imaginary=amplitude*coefficient.imag/magnitude.clamp(min=1e-20) + # Double precision phase avoids accumulated argument rounding at long leads. + future=torch.arange(c,c+horizon,device=z.device,dtype=torch.float64) + angle=indices.double()[:,None,:]*(2*math.pi/nfft)*future[None,:,None] + harmonic=(real[:,None,:]*angle.cos()+(-imaginary[:,None,:])*angle.sin()).float() + harmonic=torch.where(active[:,None,:],harmonic,0.) + confidence=(.5*amplitude.square()/variance.clamp(min=1e-8)).clamp(0.,1.) + confidence=torch.where(active,confidence,0.)[:,None,:].expand(-1,horizon,-1) + extra=torch.stack((harmonic,confidence),-1).flatten(-2) + return harmonic,extra + + +@torch.no_grad() +def spectral_phase_summaries(z, valid, horizon): + """Choose a Fourier span from each row's finite observations, independently of padding.""" + z=z[:,-4096:].float();valid=valid[:,-4096:] + b,c=z.shape + padded=F.pad(z,(4096-c,0));seen=F.pad(valid,(4096-c,0),value=False) + harmonic=torch.zeros((b,horizon,4),device=z.device,dtype=torch.float32) + extra=torch.zeros((b,horizon,8),device=z.device,dtype=torch.float32) + for span in (128,256,512,1024,2048,4096): + # Larger windows cannot pass coverage when the entire supplied width is too short. + # Skipping them changes compute only; missing prefix padding cannot activate them. + if c=.9 + candidate,candidate_extra=_spectral_window(window_z,window_valid,horizon) + harmonic=torch.where(active[:,None,None],candidate,harmonic) + extra=torch.where(active[:,None,None],candidate_extra,extra) + return harmonic,extra + + + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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,long_seasonal_features=True,seasonal_dispersion_features=True,seasonal_width_features=True,spectral_phase_features=True,individual_spectral_spans=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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,long_seasonal_features=long_seasonal_features,seasonal_dispersion_features=seasonal_dispersion_features,seasonal_width_features=seasonal_width_features,spectral_phase_features=spectral_phase_features,individual_spectral_spans=individual_spectral_spans) + assert individual_spectral_spans + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + self.long_query=nn.Linear(patch*4,d,bias=False) if long_seasonal_features else None + self.long_head=nn.Linear(d,patch*2) if long_seasonal_features else None + if long_seasonal_features: + nn.init.zeros_(self.long_query.weight) + nn.init.zeros_(self.long_head.weight);nn.init.zeros_(self.long_head.bias) + assert long_seasonal_features or not seasonal_dispersion_features + self.dispersion_query=nn.Linear(patch*4,d,bias=False) if seasonal_dispersion_features else None + if self.dispersion_query is not None:nn.init.zeros_(self.dispersion_query.weight) + assert seasonal_dispersion_features or not seasonal_width_features + self.width_head=nn.Linear(d,patch*2) if seasonal_width_features else None + if self.width_head is not None: + nn.init.zeros_(self.width_head.weight);nn.init.zeros_(self.width_head.bias) + + self.spectral_query=nn.Linear(patch*8,d,bias=False) if spectral_phase_features else None + self.spectral_head=nn.Linear(d,patch*4) if spectral_phase_features else None + if spectral_phase_features: + nn.init.zeros_(self.spectral_query.weight) + nn.init.zeros_(self.spectral_head.weight);nn.init.zeros_(self.spectral_head.bias) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + if self.long_query is not None:long_delta,long_extra,dispersion_extra,width_delta=centered_seasonal_difference(z,valid,periods,h) + if self.spectral_query is not None:spectral_delta,spectral_extra=spectral_phase_summaries(z,valid,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + hidden=self.norm(q) + out=self.head(hidden).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + if self.long_head is not None: + gates=self.long_head(hidden).view(b,h,2).float().tanh() + median=median+(gates*long_delta).sum(-1) + if self.spectral_head is not None: + spectral_gates=self.spectral_head(hidden).view(b,h,4).float().tanh() + median=median+(spectral_gates*spectral_delta).sum(-1) + widths=F.softplus(out[:,:,10:]).clamp(max=20) + if self.width_head is not None: + multiplier=seasonal_width_multiplier(self.width_head(hidden).view(b,h,2),width_delta) + widths=widths*multiplier[:,:,None] + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/model1.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/model1.py new file mode 100644 index 0000000000000000000000000000000000000000..dedcdff4698028a8ba655865f8425d0dc3ef0dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/model1.py @@ -0,0 +1,204 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/model2.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/model2.py new file mode 100644 index 0000000000000000000000000000000000000000..af1af318784c94a1d9ee75ed377582745bd30136 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/model2.py @@ -0,0 +1,204 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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,input_patch=None): + super().__init__();self.patch=patch;self.input_patch=patch if input_patch is None else input_patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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,input_patch=self.input_patch) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(self.input_patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;ip=self.input_patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%ip,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//ip + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,ip),valid.view(b,nt,ip).float()),-1)) + pmask=valid.view(b,nt,ip).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/model3.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/model3.py new file mode 100644 index 0000000000000000000000000000000000000000..3532e5063bd8b5013f6b6e35703707ffef66e00b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/model3.py @@ -0,0 +1,213 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/model4.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/model4.py new file mode 100644 index 0000000000000000000000000000000000000000..3532e5063bd8b5013f6b6e35703707ffef66e00b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/model4.py @@ -0,0 +1,213 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/model5.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/model5.py new file mode 100644 index 0000000000000000000000000000000000000000..298ee3b840cbc8b7da585ee5e47a3822d06717b0 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/model5.py @@ -0,0 +1,260 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + + +def centered_seasonal_difference(z, valid, periods, horizon): + b, c = z.shape + time = torch.arange(horizon, device=z.device)[None, :] + sums = F.pad((z * valid).cumsum(-1), (1, 0)) + counts = F.pad(valid.float().cumsum(-1), (1, 0)) + deltas, extras = [], [] + for j in range(2): + period = periods[:, j:j+1].clamp(min=1) + anchor = c - period + time % period + centered, masks = [], [] + for cycle in range(16): + end = (c - cycle * period).clamp(min=0, max=c) + start = (c - (cycle + 1) * period).clamp(min=0, max=c) + count = counts.gather(1, end) - counts.gather(1, start) + mean = (sums.gather(1, end) - sums.gather(1, start)) / count.clamp(min=1) + index = anchor - cycle * period + safe = index.clamp(min=0, max=c-1) + present = (index >= 0) & valid.gather(1, safe) + centered.append(z.gather(1, safe) - mean) + masks.append(present) + values = torch.stack(centered) + seen = torch.stack(masks) + n4 = seen[:4].sum(0) + n16 = seen.sum(0) + mean4 = (values[:4] * seen[:4]).sum(0) / n4.clamp(min=1) + mean16 = (values * seen).sum(0) / n16.clamp(min=1) + active = (period >= 2) & (n4 >= 2) & (n16 >= 8) + delta = torch.where(active, mean16 - mean4, 0.) + support = torch.where(active, n16.float() / 16, 0.) + deltas.append(delta) + extras.extend([delta, support]) + return torch.stack(deltas, -1), torch.stack(extras, -1) + + + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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,long_seasonal_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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,long_seasonal_features=long_seasonal_features) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + self.long_query=nn.Linear(patch*4,d,bias=False) if long_seasonal_features else None + self.long_head=nn.Linear(d,patch*2) if long_seasonal_features else None + if long_seasonal_features: + nn.init.zeros_(self.long_query.weight) + nn.init.zeros_(self.long_head.weight);nn.init.zeros_(self.long_head.bias) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + if self.long_query is not None:long_delta,long_extra=centered_seasonal_difference(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + hidden=self.norm(q) + out=self.head(hidden).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + if self.long_head is not None: + gates=self.long_head(hidden).view(b,h,2).float().tanh() + median=median+(gates*long_delta).sum(-1) + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/model_manifest.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/model_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..ae4a245b6a20d2f7284c6dcdd3d4c14efc555cdf --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/model_manifest.json @@ -0,0 +1,2072 @@ +{ + "name": "six-expert-gate-spectral-member-6k", + "contract": "timeseries-forecast/v1", + "parameters": 549531180, + "pretrained_assets": [], + "sources_used": [ + "gifteval_pretrain/BEIJING_SUBWAY_30MIN", + "gifteval_pretrain/HZMETRO", + "gifteval_pretrain/LOS_LOOP", + "gifteval_pretrain/PEMS03", + "gifteval_pretrain/PEMS04", + "gifteval_pretrain/PEMS07", + "gifteval_pretrain/PEMS08", + "gifteval_pretrain/PEMS_BAY", + "gifteval_pretrain/Q-TRAFFIC", + "gifteval_pretrain/SHMETRO", + "gifteval_pretrain/alibaba_cluster_trace_2018", + "gifteval_pretrain/australian_electricity_demand", + "gifteval_pretrain/azure_vm_traces_2017", + "gifteval_pretrain/bdg-2_bear", + "gifteval_pretrain/bdg-2_fox", + "gifteval_pretrain/bdg-2_panther", + "gifteval_pretrain/bdg-2_rat", + "gifteval_pretrain/bitcoin_with_missing", + "gifteval_pretrain/borealis", + "gifteval_pretrain/borg_cluster_data_2011", + "gifteval_pretrain/buildings_900k", + "gifteval_pretrain/bull", + "gifteval_pretrain/cdc_fluview_ilinet", + "gifteval_pretrain/cdc_fluview_who_nrevss", + "gifteval_pretrain/china_air_quality", + "gifteval_pretrain/cif_2016_12", + "gifteval_pretrain/cif_2016_6", + "gifteval_pretrain/cmip6_2000", + "gifteval_pretrain/cmip6_2005", + "gifteval_pretrain/cmip6_2010", + "gifteval_pretrain/cockatoo", + "gifteval_pretrain/covid19_energy", + "gifteval_pretrain/covid_mobility", + "gifteval_pretrain/elecdemand", + "gifteval_pretrain/elf", + "gifteval_pretrain/era5_2010", + "gifteval_pretrain/era5_2011", + "gifteval_pretrain/era5_2012", + "gifteval_pretrain/era5_2013", + "gifteval_pretrain/era5_2014", + "gifteval_pretrain/era5_2015", + "gifteval_pretrain/era5_2016", + "gifteval_pretrain/era5_2017", + "gifteval_pretrain/era5_2018", + "gifteval_pretrain/extended_web_traffic_with_missing", + "gifteval_pretrain/favorita_sales", + "gifteval_pretrain/favorita_transactions", + "gifteval_pretrain/gfc12_load", + "gifteval_pretrain/gfc14_load", + "gifteval_pretrain/gfc17_load", + "gifteval_pretrain/godaddy", + "gifteval_pretrain/hog", + "gifteval_pretrain/ideal", + "gifteval_pretrain/kaggle_web_traffic_weekly", + "gifteval_pretrain/kdd2022", + "gifteval_pretrain/largest_2017", + "gifteval_pretrain/largest_2018", + "gifteval_pretrain/largest_2019", + "gifteval_pretrain/largest_2020", + "gifteval_pretrain/largest_2021", + "gifteval_pretrain/lcl", + "gifteval_pretrain/london_smart_meters_with_missing", + "gifteval_pretrain/m1_monthly", + "gifteval_pretrain/m1_quarterly", + "gifteval_pretrain/m1_yearly", + "gifteval_pretrain/m5", + "gifteval_pretrain/monash_m3_monthly", + "gifteval_pretrain/monash_m3_other", + "gifteval_pretrain/monash_m3_quarterly", + "gifteval_pretrain/nn5_daily_with_missing", + "gifteval_pretrain/nn5_weekly", + "gifteval_pretrain/oikolab_weather", + "gifteval_pretrain/pdb", + "gifteval_pretrain/project_tycho", + "gifteval_pretrain/residential_load_power", + "gifteval_pretrain/residential_pv_power", + "gifteval_pretrain/rideshare_with_missing", + "gifteval_pretrain/sceaux", + "gifteval_pretrain/smart", + "gifteval_pretrain/solar_power", + "gifteval_pretrain/spain", + "gifteval_pretrain/subseasonal", + "gifteval_pretrain/subseasonal_precip", + "gifteval_pretrain/sunspot_with_missing", + "gifteval_pretrain/taxi_30min", + "gifteval_pretrain/tourism_quarterly", + "gifteval_pretrain/tourism_yearly", + "gifteval_pretrain/traffic_hourly", + "gifteval_pretrain/traffic_weekly", + "gifteval_pretrain/uber_tlc_daily", + "gifteval_pretrain/uber_tlc_hourly", + "gifteval_pretrain/vehicle_trips_with_missing", + "gifteval_pretrain/wiki-rolling_nips", + "gifteval_pretrain/wind_farms_with_missing", + "gifteval_pretrain/wind_power", + "synthetic:both original and sign-reflected orientations of each sampled allowed or locally generated window; paired quantile loss, seed 197", + "synthetic:both original and sign-reflected orientations of each sampled allowed or locally generated window; paired quantile loss, seed 307", + "synthetic:both original and sign-reflected orientations of each sampled allowed or locally generated window; paired quantile loss, seed 401", + "synthetic:both original and sign-reflected orientations of each sampled allowed or locally generated window; paired quantile loss, seed 809", + "synthetic:both original and sign-reflected orientations of each sampled window, seed 197", + "synthetic:independent sign reflection of allowed-corpus and locally generated windows; gate training seed 751", + "synthetic:independent sign reflection of sampled allowed-corpus and locally generated windows; seeds 43,47,59,79,89,197", + "synthetic:own Fourier/trend/AR/intermittent/changepoint generator at weekly periods52,1, replacing a Bernoulli1/11 share of the original synthetic rows with unchanged total synthetic fraction; independent seed 1000200", + "synthetic:own Fourier/trend/intermittent generator with AR time constant log-uniform from 1 to 10000 steps and zero initial state; seed 307", + "synthetic:own Fourier/trend/intermittent generator with AR time constant log-uniform from 1 to 10000 steps and zero initial state; seed 79", + "synthetic:own Fourier/trend/intermittent generator with AR time constant log-uniform from 1 to 10000 steps and zero initial state; seed 809", + "synthetic:own direct_v1 Fourier seasons, damped trends, AR noise with coefficient uniform(0.2,0.995), changepoints and intermittent demand; gate training seed 751", + "synthetic:own direct_v1 Fourier seasons, damped trends, AR noise, changepoints and intermittent demand; seeds 23,43,47,59,79,89,197", + "synthetic:own direct_v1 Fourier seasons, damped trends, AR noise, changepoints and intermittent demand; seeds 23,43,47,59,79,89,197,401", + "synthetic:own direct_v1 Fourier seasons, damped trends, AR noise, changepoints and intermittent demand; seeds 23,43,47,59,79,89,197,503,577,661", + "synthetic:own direct_v1 Fourier seasons, damped trends, AR noise, changepoints and intermittent demand; seeds 307", + "synthetic:own direct_v1 Fourier seasons, damped trends, AR noise, changepoints and intermittent demand; seeds 307,809", + "synthetic:own random requested-horizon prefixes, half full and half patch-rounded one-quarter to full; gate training independent seed 300754", + "synthetic:own random requested-horizon prefixes, half of rows retain the full horizon and half use a patch-rounded prefix between one-quarter and the full horizon; independent seed 300200", + "synthetic:own random requested-horizon prefixes, half of rows retain the full horizon and half use a patch-rounded prefix between one-quarter and the full horizon; independent seed 300310", + "synthetic:own random requested-horizon prefixes, half of rows retain the full horizon and half use a patch-rounded prefix between one-quarter and the full horizon; independent seed 300404", + "synthetic:own random requested-horizon prefixes, half of rows retain the full horizon and half use a patch-rounded prefix between one-quarter and the full horizon; independent seed 300812", + "synthetic:own stationary Gaussian residuals generated by FFT, equal Matern0.5/1.5/2.5 and RBF spectral families, length scale log-uniform1to10000, theoretical unit marginal variance, FFT size next power of two at least4times window; replacing half of original synthetic residuals with all other generator components unchanged; independent seed 1100200" + ], + "members": [ + { + "weights": "member0.pt", + "weights_sha256": "0d4f90210ec38a1256db86115b600ba839a299594174d9da5fcf822aa82c7c55", + "parameters": 36997536, + "config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true, + "seasonal_dispersion_features": true, + "seasonal_width_features": true, + "spectral_phase_features": true, + "individual_spectral_spans": true + }, + "model_code": "model0.py" + }, + { + "weights": "member1.pt", + "weights_sha256": "308389b7217c080af9eb185559d4ee3cafa0f3e0f8c4dd8f5526b68198c89988", + "parameters": 36665488, + "config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "model_code": "model1.py" + }, + { + "weights": "member2.pt", + "weights_sha256": "1a2fb20a9fb5cae6526f2e36ea47559626bece78fd9c284899836505030ae9fe", + "parameters": 36601928, + "config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 4, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "input_patch": 8 + }, + "model_code": "model2.py" + }, + { + "weights": "member3.pt", + "weights_sha256": "d7cfcd72c3cb84aa69e447b76c4c3ab98c21b7c600a463f0b805f4b4300baf33", + "parameters": 146477344, + "config": { + "d": 1024, + "heads": 16, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "model_code": "model3.py" + }, + { + "weights": "member4.pt", + "weights_sha256": "2877a38b94a7d77a53a9df410349cecc2f6ab134c83a76744924543bbe73eb17", + "parameters": 146206864, + "config": { + "d": 1024, + "heads": 16, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "model_code": "model4.py" + }, + { + "weights": "member5.pt", + "weights_sha256": "4b309f0721378f97db815dd511b8b54711348270c48e9eae0103dba506f66708", + "parameters": 146575680, + "config": { + "d": 1024, + "heads": 16, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true + }, + "model_code": "model5.py" + } + ], + "checkpoint_sha256": "74d648f1505df6d90123e5d8ca2895b54805f37da97976a1e98cbc2564568960", + "checkpoint_digest_method": "SHA-256 of config.json including six ordered own-expert hashes, gate hash and fixed composition", + "training_lineage": [ + { + "checkpoint": "seasonal_width_transfer12k.pt", + "sha256": "0b11b7351a4a92d1d18c71a4159ec445be3a94ace8c7a9fa0edafad87d14e960", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true, + "seasonal_dispersion_features": true, + "seasonal_width_features": true + }, + "conversion": { + "method": "matched direct-width-head training delta, separately zero-extending base and control", + "formula": "zero_extend(E117first)+E129-zero_extend(E119)", + "coefficient": 1.0, + "base_zero_parameters": [ + "dispersion_query.weight", + "width_head.bias", + "width_head.weight" + ], + "control_zero_parameters": [ + "width_head.bias", + "width_head.weight" + ], + "dispersion_query": "candidate-minus-control only; no E128 correction", + "parent_hashes": { + "/workspace/research/long_seasonal_transfer12k.pt": "8a2b252b733cc79c31778ea27ba00fbe61206fef50454514b667c54a928d80a4", + "/workspace/research/runs/seasonal_width/ema012000.pt": "8a8c75cafcc7b42266aaab7d8458cb383b65313ce6da8c396e76760f7ab6e33c", + "/workspace/research/runs/seasonal_dispersion/ema012000.pt": "b0204fa8dd3371d9160fc00545d6b065ccb23bb18e345b3b63cd39c024c9acf5" + }, + "base_extension_forward_bitwise_equal": true, + "finite_ordered_fixture": true, + "check_seed": 769, + "seconds": 2.078599537955597, + "optimizer_updates": 0, + "validation_data_read": false + }, + "parents": [ + "long_seasonal_transfer12k.pt", + "runs/seasonal_width/ema012000.pt", + "runs/seasonal_dispersion/ema012000.pt" + ] + }, + { + "checkpoint": "long_seasonal_transfer12k.pt", + "sha256": "8a2b252b733cc79c31778ea27ba00fbe61206fef50454514b667c54a928d80a4", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true + }, + "conversion": { + "method": "matched training delta after zero extension of new seasonal query/head parameters", + "formula": "extend_zero(base) + candidate - extend_zero(control)", + "coefficient": 1.0, + "new_parameters_from_candidate": [ + "long_head.bias", + "long_head.weight", + "long_query.weight" + ], + "parent_hashes": { + "/workspace/research/spectral_add_delta6k.pt": "c3dfc433d51355228fc13d04913db1a7edf83030c33283b150bdcc50f5ae6ea2", + "/workspace/research/runs/long_seasonal/ema012000.pt": "d512cdac520239f0c10e021721424d87cee30086fa70f6cbc41f21e2e04988c3", + "/workspace/research/runs/overflow_control/ema012000.pt": "f11d056b95f1c5eeef174265ebc51742952600e0dae1fa52900860447d5be819" + }, + "base_extension_forward_bitwise_equal": true, + "check_seed": 571, + "seconds": 2.5279976530000567, + "optimizer_updates": 0, + "validation_data_read": false + }, + "parents": [ + "spectral_add_delta6k.pt", + "runs/long_seasonal/ema012000.pt", + "runs/overflow_control/ema012000.pt" + ] + }, + { + "checkpoint": "runs/seasonal_width/ema012000.pt", + "sha256": "8a8c75cafcc7b42266aaab7d8458cb383b65313ce6da8c396e76760f7ab6e33c", + "step": 12000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null, + "teacher_coefficient": null, + "compile_teacher": false, + "visibility_curriculum": false + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true, + "seasonal_dispersion_features": true, + "seasonal_width_features": true + }, + "parents": [ + "seasonal_width_initial.pt", + "seasonal_dispersion_initial.pt" + ] + }, + { + "checkpoint": "runs/seasonal_dispersion/ema012000.pt", + "sha256": "b0204fa8dd3371d9160fc00545d6b065ccb23bb18e345b3b63cd39c024c9acf5", + "step": 12000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null, + "teacher_coefficient": null + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true, + "seasonal_dispersion_features": true + }, + "parents": [ + "seasonal_dispersion_initial.pt", + "long_seasonal_initial.pt" + ] + }, + { + "checkpoint": "spectral_add_delta6k.pt", + "sha256": "c3dfc433d51355228fc13d04913db1a7edf83030c33283b150bdcc50f5ae6ea2", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/weekly_slow_ar_delta6k.pt": "c8adf9cadf97dac5e120d8d4d2c8c025bffa2e8b55d8664bf900cce55d00a70b", + "/workspace/research/runs/spectral_synth/ema006000.pt": "683f3824d3c1f605d17bb08d3eef127a54c67eca3867cfbcf1158710a55c4b24", + "/workspace/research/runs/overflow_control/ema006000.pt": "b19875c52ed5024383fb69ccc48cb07a5629ad8011abf134c7dcfcdc50fae2af" + }, + "seconds": 1.4204325219616294 + }, + "parents": [ + "weekly_slow_ar_delta6k.pt", + "runs/spectral_synth/ema006000.pt", + "runs/overflow_control/ema006000.pt" + ] + }, + { + "checkpoint": "runs/long_seasonal/ema012000.pt", + "sha256": "d512cdac520239f0c10e021721424d87cee30086fa70f6cbc41f21e2e04988c3", + "step": 12000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null, + "teacher_coefficient": null + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true + }, + "parents": [ + "long_seasonal_initial.pt", + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "runs/overflow_control/ema012000.pt", + "sha256": "f11d056b95f1c5eeef174265ebc51742952600e0dae1fa52900860447d5be819", + "step": 12000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "seasonal_width_initial.pt", + "sha256": "94ba155b90c6b510bccf92358cc225afe8f317285a19637ab5ca68072bbb83d1", + "step": 0, + "seed": 661, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "long_seasonal_features": true, + "seasonal_dispersion_features": true, + "seasonal_width_features": true + }, + "conversion": { + "method": "zero-initialized direct seasonal width head", + "parent_sha256": "5f07cac4fe7de3e878a01cb90384e79905fdb3156122b568e82c5923526aca3c", + "initial_function_bitwise_equal": true + }, + "parents": [ + "seasonal_dispersion_initial.pt" + ] + }, + { + "checkpoint": "seasonal_dispersion_initial.pt", + "sha256": "5f07cac4fe7de3e878a01cb90384e79905fdb3156122b568e82c5923526aca3c", + "step": 0, + "seed": 577, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "long_seasonal_features": true, + "seasonal_dispersion_features": true + }, + "conversion": { + "method": "zero-initialized phase-specific cycle-centered standard-deviation query", + "parent_sha256": "470ef98d69d00b17defbf41c70a92b22574154cdb6e0317993bccf113e4af93b", + "initial_function_bitwise_equal": true + }, + "parents": [ + "long_seasonal_initial.pt" + ] + }, + { + "checkpoint": "long_seasonal_initial.pt", + "sha256": "470ef98d69d00b17defbf41c70a92b22574154cdb6e0317993bccf113e4af93b", + "step": 0, + "seed": 503, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "long_seasonal_features": true + }, + "conversion": { + "method": "zero-initialized sixteen-cycle centered seasonal query/head additions", + "parent_sha256": "22c08571978be31ba57368eb983089a40a44d56d4ae5e17da41afd2a761a258c", + "initial_function_bitwise_equal": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "weekly_slow_ar_delta6k.pt", + "sha256": "c8adf9cadf97dac5e120d8d4d2c8c025bffa2e8b55d8664bf900cce55d00a70b", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/postloss_slow_ar_delta6k.pt": "0ae7875b49b99a44c295dc2b8243327aeacadc25b2354988abb2c37250359a49", + "/workspace/research/runs/weekly_synth/ema006000.pt": "de053e5baf9641e9245519990d6e5193fc91392cb76e72ceffee1ce63f578fca", + "/workspace/research/runs/overflow_control/ema006000.pt": "b19875c52ed5024383fb69ccc48cb07a5629ad8011abf134c7dcfcdc50fae2af" + }, + "seconds": 2.0751679679378867 + }, + "parents": [ + "postloss_slow_ar_delta6k.pt", + "runs/weekly_synth/ema006000.pt", + "runs/overflow_control/ema006000.pt" + ] + }, + { + "checkpoint": "runs/spectral_synth/ema006000.pt", + "sha256": "683f3824d3c1f605d17bb08d3eef127a54c67eca3867cfbcf1158710a55c4b24", + "step": 6000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null, + "teacher_coefficient": null, + "spectral_synthetic_seed": 1100200, + "spectral_replacement_probability": 0.5, + "spectral_length_scale": [ + 1, + 10000 + ], + "spectral_families": [ + "Matern0.5", + "Matern1.5", + "Matern2.5", + "RBF" + ] + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt", + "runs/confidence_query/ema006000.pt", + "runs/horizon_jitter/ema012000.pt", + "runs/large_corpus_control/ema012000.pt" + ] + }, + { + "checkpoint": "runs/overflow_control/ema006000.pt", + "sha256": "b19875c52ed5024383fb69ccc48cb07a5629ad8011abf134c7dcfcdc50fae2af", + "step": 6000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "horizon_delta12k.pt", + "sha256": "22c08571978be31ba57368eb983089a40a44d56d4ae5e17da41afd2a761a258c", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/runs/confidence_query/ema006000.pt": "0bad97e8994aac49ea173443db0a4fa8d72d33f9eb9e2660f06de75f7f1403eb", + "/workspace/research/runs/horizon_jitter/ema012000.pt": "830179d763916a1065fc615d2c5e22f4a3b5b19390dde707ab0f057e13cadff6", + "/workspace/research/runs/large_corpus_control/ema012000.pt": "7f9ba5e01ac59c51a3b63d3067b442e23e15d0abc51ddbcccdd04d6083ae4add" + }, + "seconds": 1.2663014469435439 + }, + "parents": [ + "runs/confidence_query/ema006000.pt", + "runs/horizon_jitter/ema012000.pt", + "runs/large_corpus_control/ema012000.pt" + ] + }, + { + "checkpoint": "postloss_slow_ar_delta6k.pt", + "sha256": "0ae7875b49b99a44c295dc2b8243327aeacadc25b2354988abb2c37250359a49", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/runs/postloss/ema003000.pt": "82c785d40998e155a20290c9965c346c26cd397fa0f3cf36278377ad2aed5c7d", + "/workspace/research/runs/long_memory_synth_recovery/ema006000.pt": "fea5b5290a3a9be5618eaeaf67e918e4f677d5be908d562040ce4bdfeb549bd9", + "/workspace/research/runs/partial_targets/ema006000.pt": "67562486b099a350da53c3caa5ff0932fe7fecdfe72c1879b064b2a9bb173dfb" + }, + "seconds": 1.0092943429481238 + }, + "parents": [ + "runs/postloss/ema003000.pt", + "runs/long_memory_synth_recovery/ema006000.pt", + "runs/partial_targets/ema006000.pt" + ] + }, + { + "checkpoint": "runs/weekly_synth/ema006000.pt", + "sha256": "de053e5baf9641e9245519990d6e5193fc91392cb76e72ceffee1ce63f578fca", + "step": 6000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true, + "weekly_synthetic_seed": 1000200, + "weekly_replacement_probability": 0.09090909090909091, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "runs/confidence_query/ema006000.pt", + "sha256": "0bad97e8994aac49ea173443db0a4fa8d72d33f9eb9e2660f06de75f7f1403eb", + "step": 6000, + "seed": 89, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 0.0002, + "steps": 6000 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true + }, + "parents": [ + "runs/recency_features/ema024000.pt" + ] + }, + { + "checkpoint": "runs/horizon_jitter/ema012000.pt", + "sha256": "830179d763916a1065fc615d2c5e22f4a3b5b19390dde707ab0f057e13cadff6", + "step": 12000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "partial_target_lengths": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/large_corpus_control/ema012000.pt", + "sha256": "7f9ba5e01ac59c51a3b63d3067b442e23e15d0abc51ddbcccdd04d6083ae4add", + "step": 12000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/postloss/ema003000.pt", + "sha256": "82c785d40998e155a20290c9965c346c26cd397fa0f3cf36278377ad2aed5c7d", + "step": 3000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "fixed_postprocessing_loss": true, + "normalization_overflow_fallback": true + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "runs/long_memory_synth_recovery/ema006000.pt", + "sha256": "fea5b5290a3a9be5618eaeaf67e918e4f677d5be908d562040ce4bdfeb549bd9", + "step": 6000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "context": null, + "sample_context": 4096, + "synthetic_ar_time_constants": [ + 1, + 10000 + ] + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "partial_target_lengths": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/partial_targets/ema006000.pt", + "sha256": "67562486b099a350da53c3caa5ff0932fe7fecdfe72c1879b064b2a9bb173dfb", + "step": 6000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "partial_target_lengths": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/recency_features/ema024000.pt", + "sha256": "1530fbb577a87ca4eb39da83d6fee9b8ee5bc924202e021e3a7b56493112f564", + "step": 24000, + "seed": 59, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/patch16_trial/ema006000.pt" + ] + }, + { + "checkpoint": "runs/recency_features/ema012000.pt", + "sha256": "8ccb6870a025e1097331a3a288b1183741a413f3460fbf3352d0c589c6a4394c", + "step": 12000, + "seed": 59, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/patch16_trial/ema006000.pt" + ] + }, + { + "checkpoint": "runs/patch16_trial/ema006000.pt", + "sha256": "0ff54447074e0271d2e331c7d3e6e9e0fdd73353e4d8cef0175ff627385f71c3", + "step": 6000, + "seed": 47, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024 + }, + "parents": [ + "patch16_init.pt" + ] + }, + { + "checkpoint": "patch16_init.pt", + "sha256": "d69531bfde5bf801e7f36c515bf15fd0cae0bd84f7d1479d35f4a7b67f26b508", + "step": 6000, + "seed": 43, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024 + }, + "conversion": { + "from_checkpoint": "/run-state/workspace/research/runs/large_sign/ema006000.pt", + "from_sha256": "96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547", + "method": "fold input/query halves by summation; retain first 16 output rows; preserve physical positional units" + }, + "parents": [ + "runs/large_sign/ema006000.pt" + ] + }, + { + "checkpoint": "runs/large_sign/ema006000.pt", + "sha256": "96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547", + "step": 6000, + "seed": 43, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 32, + "max_context": 4096, + "max_horizon": 1024 + }, + "parents": [ + "runs/direct_large/step024000.pt" + ] + }, + { + "checkpoint": "runs/direct_large/step024000.pt", + "sha256": "b7e4f38aebcd2cf38ce484edaad8d19851317fb3b8df485e2faa0d0423cbcb48", + "step": 24000, + "seed": 23, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 128, + "lr": 0.0002, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 32, + "max_context": 4096, + "max_horizon": 1024 + }, + "initialization": "random initialization in this workspace" + }, + { + "checkpoint": "runs/patch8/ema006000.pt", + "sha256": "308389b7217c080af9eb185559d4ee3cafa0f3e0f8c4dd8f5526b68198c89988", + "step": 6000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "patch8_initial.pt" + ] + }, + { + "checkpoint": "patch8_initial.pt", + "sha256": "e7da4d47a9cc984a9423296679d7c9127ef2d679be950b9e8d3758e6fca074cc", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "from_checkpoint": "/run-state/workspace/research/horizon_delta12k.pt", + "from_sha256": "22c08571978be31ba57368eb983089a40a44d56d4ae5e17da41afd2a761a258c", + "method": "fold input/query/recency halves by summation; retain first8 output rows; preserve physical position units", + "exact_function_preservation": false + }, + "parents": [ + "horizon_delta12k.pt", + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "runs/split_patch/ema012000.pt", + "sha256": "1a2fb20a9fb5cae6526f2e36ea47559626bece78fd9c284899836505030ae9fe", + "step": 12000, + "seed": 401, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 32, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300404 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 4, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "input_patch": 8 + }, + "parents": [ + "split_patch_initial.pt" + ] + }, + { + "checkpoint": "split_patch_initial.pt", + "sha256": "0719b4dce554764ef69181d8b19d8da11849ef32b35391ffee6700e639a73114", + "step": 0, + "seed": null, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 4, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "input_patch": 8 + }, + "conversion": { + "method": "retain input8; sum query/recency halves and keep first4 output rows; same physical position coordinates", + "exact_function_preservation": false, + "parent_sha256": "308389b7217c080af9eb185559d4ee3cafa0f3e0f8c4dd8f5526b68198c89988" + }, + "parents": [ + "runs/patch8/ema006000.pt", + "runs/patch8/ema006000.pt" + ] + }, + { + "checkpoint": "runs/random_capacity_1024/ema096000.pt", + "sha256": "d7cfcd72c3cb84aa69e447b76c4c3ab98c21b7c600a463f0b805f4b4300baf33", + "step": 96000, + "seed": 307, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 48, + "lr": 0.0002, + "steps": 96000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": true, + "synthetic_ar_time_constants": [ + 1, + 10000 + ], + "requested_horizon_seed": 300310, + "normalization_overflow_fallback": true + }, + "model_config": { + "d": 1024, + "heads": 16, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "random_capacity_1024_initial.pt" + ] + }, + { + "checkpoint": "random_capacity_1024_initial.pt", + "sha256": "c9693619ca6277c26fef3b2bde37ff6796bec97b3af9f94588bbc5ddd329ec90", + "step": 0, + "seed": 307, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 1024, + "heads": 16, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "initialization": "random initialization in this workspace" + }, + { + "checkpoint": "runs/capacity_patch8_candidate/ema006000.pt", + "sha256": "2877a38b94a7d77a53a9df410349cecc2f6ab134c83a76744924543bbe73eb17", + "step": 6000, + "seed": 809, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 32, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": true, + "synthetic_ar_time_constants": [ + 1, + 10000 + ], + "requested_horizon_seed": 300812, + "normalization_overflow_fallback": true, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null, + "teacher_coefficient": null, + "compile_teacher": false, + "visibility_curriculum": false + }, + "model_config": { + "d": 1024, + "heads": 16, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "capacity_patch8_initial.pt", + "runs/random_capacity_1024/ema096000.pt" + ] + }, + { + "checkpoint": "capacity_patch8_initial.pt", + "sha256": "3fef8f613e5fad3633e4fafe697453e2fe3691678fa581c8a2fea3e6da3de2c1", + "step": 96000, + "seed": 307, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 48, + "lr": 0.0002, + "steps": 96000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": true, + "synthetic_ar_time_constants": [ + 1, + 10000 + ], + "requested_horizon_seed": 300310, + "normalization_overflow_fallback": true + }, + "model_config": { + "d": 1024, + "heads": 16, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "from_checkpoint": "/run-state/workspace/research/runs/random_capacity_1024/ema096000.pt", + "from_sha256": "d7cfcd72c3cb84aa69e447b76c4c3ab98c21b7c600a463f0b805f4b4300baf33", + "method": "fold input/query/recency halves by summation; retain first8 output rows; preserve physical position units", + "exact_function_preservation": false + }, + "parents": [ + "runs/random_capacity_1024/ema096000.pt", + "runs/random_capacity_1024/ema096000.pt" + ] + }, + { + "checkpoint": "runs/random_capacity_long_seasonal/ema048000.pt", + "sha256": "4b309f0721378f97db815dd511b8b54711348270c48e9eae0103dba506f66708", + "step": 48000, + "seed": 307, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 48, + "lr": 0.0002, + "steps": 96000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": true, + "synthetic_ar_time_constants": [ + 1, + 10000 + ], + "requested_horizon_seed": 300310, + "normalization_overflow_fallback": true, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null, + "teacher_coefficient": null, + "compile_teacher": false, + "visibility_curriculum": false + }, + "model_config": { + "d": 1024, + "heads": 16, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true + }, + "parents": [ + "random_capacity_long_seasonal_initial.pt", + "random_capacity_1024_initial.pt" + ] + }, + { + "checkpoint": "random_capacity_long_seasonal_initial.pt", + "sha256": "f7e35a6341ffc6c1ce53cfd8934256dde937171f5002f1fc34b1fd169f1a15d6", + "step": 0, + "seed": 307, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 1024, + "heads": 16, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true + }, + "conversion": { + "method": "zero-initialize E107 seasonal query/head on own untrained E79random146M backbone", + "parent_sha256": "c9693619ca6277c26fef3b2bde37ff6796bec97b3af9f94588bbc5ddd329ec90", + "fixture_seed": 677, + "initial_function_bitwise_equal": true, + "optimizer_updates": 0 + }, + "parents": [ + "random_capacity_1024_initial.pt" + ] + }, + { + "sha256": "9d1401cd4d5b5f1c3ddd25a4a74e15e5db7ef708116cdf5c4fa7e90580b58da1", + "step": 0, + "role": "local gate random initialization, seed751" + }, + { + "sha256": "a7d0ee6866ea787f29eac043531aad3613674f159fd00b3491fd87fab8388fd1", + "step": 6000, + "role": "gate trained on allowed corpus and own synthetic generator; four experts frozen" + }, + { + "checkpoint": "runs/spectral_phase_individual/ema006000.pt", + "sha256": "bca83d228f218f56044ce37b1a4fbc84a2f2bb8a8f900ccb868b01621e4e0e14", + "step": 6000, + "seed": 197, + "ema": true, + "training_settings": { + "code_dir": "/workspace/research/spectral_phase_individual", + "packed": "/workspace/research/packed_sample", + "source_weights_from": "/workspace/research/packed_sample", + "out": "/workspace/research/runs/spectral_phase_individual", + "deterministic_training": false, + "initialize_from": "/workspace/research/spectral_phase_individual_initial.pt", + "initialize_ema": null, + "start_step": 0, + "resume": null, + "steps": 12000, + "batch": 64, + "lr": 2e-05, + "seed": 197, + "context": null, + "sample_context": 4096, + "save_every": 1000, + "stop_file": "/workspace/research/spectral_phase_individual.stop", + "recovery_every": 250, + "halt_after": null, + "loss_mode": "paired", + "compile_loss": false, + "reset_at": -1, + "reset_seed": 179, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null, + "teacher_package": null, + "teacher_coefficient": null, + "compile_teacher": false, + "visibility_curriculum": false, + "gate_package": null, + "micro_batch": null, + "trainable_scope": "all", + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true, + "spectral_phase_summary_rule": "Fixed Hann-window Fourier projection: recent4096,8x power-of-two FFT grid, top4 local17-bin peaks, minimum4cycles/span128/finite0.9, amplitude cap30, power confidence cap1; zero query and direct median head initialized from own E107 parent. No inference fitting.", + "spectral_phase_individual_span_rule": "Per row longest eligible right-aligned dyadic window128,256,512,1024,2048,4096 with finitefraction>=0.9; fixed missing-prefix padding, independent of batch rectangle" + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true, + "spectral_phase_features": true, + "individual_spectral_spans": true + }, + "parents": [ + "/workspace/research/long_seasonal_initial.pt" + ], + "role": "Own matched source or control for fixed E190 transfer" + }, + { + "checkpoint": "runs/long_seasonal/ema006000.pt", + "sha256": "ad45e0cfae574d3dc1be0b9720c9be0863db9ffe33891fdb22c86dfa83667253", + "step": 6000, + "seed": 197, + "ema": true, + "training_settings": { + "code_dir": "/workspace/research/long_seasonal", + "packed": "/workspace/research/packed_sample", + "source_weights_from": "/workspace/research/packed_sample", + "out": "/workspace/research/runs/long_seasonal", + "initialize_from": "/workspace/research/long_seasonal_initial.pt", + "initialize_ema": null, + "start_step": 0, + "resume": null, + "steps": 12000, + "batch": 64, + "lr": 2e-05, + "seed": 197, + "context": null, + "sample_context": 4096, + "save_every": 1000, + "stop_file": "/workspace/research/long_seasonal.stop", + "recovery_every": 250, + "halt_after": null, + "loss_mode": "paired", + "compile_loss": false, + "reset_at": -1, + "reset_seed": 179, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null, + "teacher_package": null, + "teacher_coefficient": null, + "trainable_scope": "all", + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true + }, + "parents": [ + "/workspace/research/horizon_delta12k.pt" + ], + "role": "Own matched source or control for fixed E190 transfer" + }, + { + "sha256": "0d4f90210ec38a1256db86115b600ba839a299594174d9da5fcf822aa82c7c55", + "step": 0, + "role": "Fixed FP32 E190 matched transfer; no optimizer updates", + "composition": { + "experiment": "E190", + "step": 6000, + "formula": "FP32 zero_extend(F0) + E164 - zero_extend(E107), coefficient exactly1; new spectral tensors equal E164; F0-only dispersion/width tensors preserved bitwise.", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/seasonal_width_transfer12k.pt": "0b11b7351a4a92d1d18c71a4159ec445be3a94ace8c7a9fa0edafad87d14e960", + "/workspace/research/runs/spectral_phase_individual/ema006000.pt": "bca83d228f218f56044ce37b1a4fbc84a2f2bb8a8f900ccb868b01621e4e0e14", + "/workspace/research/runs/long_seasonal/ema006000.pt": "ad45e0cfae574d3dc1be0b9720c9be0863db9ffe33891fdb22c86dfa83667253" + }, + "optimizer_updates": 0, + "validation_data_read": false, + "fixture_seed": 1907, + "f0_only_tensors_unchanged": true, + "model_sha256": "8871ad0ae4719dd0ed9844b1231407e6468e49d8c86c71ba7e9d546d28222528", + "checkpoint": "/workspace/research/spectral_width_transfer6k.pt", + "checkpoint_sha256": "0d4f90210ec38a1256db86115b600ba839a299594174d9da5fcf822aa82c7c55", + "parameters": 36997536 + } + } + ], + "every_member_forecasts_every_instance": true, + "member_history_caps": [ + { + "input_and_summary": 4096, + "encoder_and_normalization": 4096, + "fixed_rules": 4096 + }, + { + "input_and_summary": 4096, + "encoder_and_normalization": 4096, + "fixed_rules": 4096 + }, + { + "input_and_summary": 4096, + "encoder_and_normalization": 4096, + "fixed_rules": 4096 + }, + { + "input_and_summary": 4096, + "encoder_and_normalization": 4096, + "fixed_rules": 4096 + }, + { + "input_and_summary": 4096, + "encoder_and_normalization": 4096, + "fixed_rules": 4096 + }, + { + "input_and_summary": 4096, + "encoder_and_normalization": 4096, + "fixed_rules": 4096 + } + ], + "postprocessing_order": "Each own expert retains original fixed sign/positivity/seasonal/continuity/zero-mass/finite rules. E159 two-quartermeans and E152primary6k gate pool are computed in their original orderedFP32 forms; output is their equalFP32mean with finite guard. No final zero projection.", + "runtime_code_sha256": { + "infer.sh": "559615bb41d4c3c560653bbf2da9102a0934ad6498ce30f029c29da882e2a0b7", + "gate_normalization.py": "77226d599c15fbe6e442d0fd7cc5c43387b6f3669830e4b1f5754d9cdb4268c1", + "ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "model5.py": "3eaa4aed0a1c62b80d94be6c3084b10a594e9fce17444eac17ca3f1b0b5c549e", + "model3.py": "44eeb23c037e91b8f67e432615ce46540a7ac4242919785f9c4218de23121499", + "model.py": "c27748fa4b1186b513f76eca26052753b8dcd1794994e5989addaf371ca70f2e", + "zero_mass.py": "f079d509009bcda409b80eb64467c869b838cfbab11b2bd4c660c2875b6642fe", + "model2.py": "89bb87b2501b117ac02daf001a68f389ec488931ce18905445d15874760685be", + "continuity.py": "dbb08d2229ad80ad00f638b0b9f2f6ca13c663e0fd6730058e5fee8ff54545d5", + "seasonal.py": "b946e63048196ab5ea8b249137d48c80d8510943caccd0f180e4fb86d9b24b37", + "predict.py": "00b9d7cf2b12db47a95b28044255537334232b4cff4715d64ee18147efd47e29", + "model0.py": "8871ad0ae4719dd0ed9844b1231407e6468e49d8c86c71ba7e9d546d28222528", + "gate_frequency.py": "eb08437794e3c2493f3760aa39ad8bde268a8351d33fb868bc0f553bc13eb720", + "model1.py": "c27748fa4b1186b513f76eca26052753b8dcd1794994e5989addaf371ca70f2e", + "model4.py": "44eeb23c037e91b8f67e432615ce46540a7ac4242919785f9c4218de23121499", + "gate_model.py": "d596abae7946c917d748fa41bf3c1b5930b9afc3fcfa54e671e8f65a66ad7586" + }, + "notes": "Six own scratch-trained experts and a fixed gate. E192 replaces F0 in both ordered ensembles and the frozen gate inputs. Other members, gate weights, coefficients, fixed rules and runtime arithmetic remain unchanged.", + "parent_descriptor_sha256": "20f014ca61a9cfa4f275d9d7abfd297561ac37fddcdae9ba2ef60d3fca106cf8", + "gate_parameters": 6340, + "gate_weights_sha256": "a7d0ee6866ea787f29eac043531aad3613674f159fd00b3491fd87fab8388fd1", + "gate_training_step": 6000, + "gate_training_args": { + "code_dir": "/workspace/research/ensemble_gate_factorial", + "packed": "/workspace/research/packed_sample", + "source_weights_from": "/workspace/research/packed_sample", + "out": "/workspace/research/runs/ensemble_gate_refresh", + "initialize_from": "/workspace/research/ensemble_gate_initial.pt", + "initialize_ema": null, + "start_step": 0, + "resume": null, + "steps": 12000, + "batch": 64, + "lr": 0.001, + "seed": 751, + "context": null, + "sample_context": 4096, + "save_every": 1000, + "stop_file": "/workspace/research/ensemble_gate_refresh.stop", + "recovery_every": 250, + "halt_after": null, + "loss_mode": "paired", + "compile_loss": false, + "reset_at": -1, + "reset_seed": 179, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null, + "teacher_package": null, + "teacher_coefficient": null, + "compile_teacher": false, + "visibility_curriculum": false, + "gate_package": "/workspace/research/gating_experts_E148", + "micro_batch": null, + "trainable_scope": "6340 gate parameters only; four experts frozen and excluded from optimizer and EMA", + "requested_horizon_seed": 300754, + "normalization_overflow_fallback": true, + "fixed_expert_descriptor_sha256": "a1b4ab426901be8e1ee299eeeb3f041bac7cea3d4e59c4608824fc3d05c83e03", + "fixed_expert_checkpoint_sha256": [ + "0b11b7351a4a92d1d18c71a4159ec445be3a94ace8c7a9fa0edafad87d14e960", + "308389b7217c080af9eb185559d4ee3cafa0f3e0f8c4dd8f5526b68198c89988", + "1a2fb20a9fb5cae6526f2e36ea47559626bece78fd9c284899836505030ae9fe", + "d7cfcd72c3cb84aa69e447b76c4c3ab98c21b7c600a463f0b805f4b4300baf33" + ], + "expert_forecast_kind": "four own immutable E130 or E148 raw-scale final forecasts, identified by fixed descriptor/member hashes, including exact packaged per-member transformations", + "gate_factorial_study": "E152: expert version E130/E148 and small/full corpus coverage; source probabilities and all other gate settings fixed", + "gate_weight_rule": "0.125+0.5*softmax; same positive per-lead weight across all quantiles", + "gate_features": [ + "log_finite_count", + "log_period0", + "log_period1", + "log_horizon", + "lead_fraction", + "log_lead", + "finite_fraction", + "log_absdiff_lag1", + "log_absdiff_period0", + "log_absdiff_period1", + "adjacent_mean4", + "adjacent_mean16", + "adjacent_mean128", + "median_from_consensus_expert0", + "median_from_consensus_expert1", + "median_from_consensus_expert2", + "median_from_consensus_expert3", + "log_width80_expert0", + "log_width80_expert1", + "log_width80_expert2", + "log_width80_expert3", + "median_from_last_expert0", + "median_from_last_expert1", + "median_from_last_expert2", + "median_from_last_expert3", + "median_from_mean32_expert0", + "median_from_mean32_expert1", + "median_from_mean32_expert2", + "median_from_mean32_expert3" + ], + "fixed_postprocessing_loss": true, + "gate_precision": "FP32 gate, BF16 frozen experts, TF32 disabled" + }, + "gate_config": { + "input_dim": 29, + "hidden": 64, + "members": 4, + "mixing": 0.5, + "max_context": 4096 + }, + "gate_blend_coefficient": 0.5, + "gate_forecasts_every_instance": true, + "parent_ensemble_weights_by_horizon": { + "below720": [ + 0.25, + 0.25, + 0.25, + 0.125, + 0, + 0.125 + ], + "at_least720": [ + 0.25, + 0.25, + 0.25, + 0, + 0.125, + 0.125 + ] + }, + "replacement_study": "E192", + "replacement_step": 6000, + "replacement_member_index": 0, + "replacement_parent_descriptor_sha256": "a75fdfcbb4d8e38dd6e7cded3c097ff0a129976fa63277bfd277a6031ccc6140", + "runtime_code_digest": "72325b157573edaab56d496f64c031621ad049cc791386b6620b67c892a36a41" +} diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..5a59e26122883727cb597a115e69133695b7696e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/predict.py @@ -0,0 +1,91 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import importlib.util +from seasonal import apply_gate +from continuity import apply_continuity +from zero_mass import project +import ts_io +from gate_model import DirectForecaster as LearnedGate, combine as gate_combine + +def load_model(checkpoint,device='cuda'): + from types import SimpleNamespace + path=Path(checkpoint);descriptor=json.loads(path.read_text());members=[] + for entry in descriptor['members']: + ck=torch.load(path.parent/entry['weights'],map_location='cpu',weights_only=False) + spec=importlib.util.spec_from_file_location('member_model_'+str(len(members)),path.parent/entry['model_code']) + module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module) + with torch.device('meta'): + model=module.DirectForecaster(**ck['config']) + model.load_state_dict(ck['model'],assign=True);model=model.to(device);model.eval();members.append(model) + assert len(members)==6 + assert descriptor["horizon_threshold"]==720 and descriptor["blend_coefficient"]==.5 + assert descriptor['gate_blend_coefficient']==.5 + gate_ck=torch.load(path.parent/descriptor['gate']['weights'],map_location='cpu',weights_only=False) + with torch.device('meta'):gate=LearnedGate(**gate_ck['config']) + gate.load_state_dict(gate_ck['model'],assign=True);gate=gate.to(device);gate.eval() + return SimpleNamespace(models=members,gate=gate,max_context=max(m.max_context for m in members),horizon_threshold=descriptor['horizon_threshold']) + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + forecasts=[] + for member in model.models: + member_ctx=ctx[:,-member.max_context:] + member_x=x[:,-member.max_context:] + rule_context=getattr(member,'rule_context',member.max_context) + rule_ctx=member_ctx[:,-rule_context:] + rule_x=member_x[:,-rule_context:] + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16): + qq,mu,scale=member(torch.cat((member_x,-member_x),0),p.repeat(2,1),h) + qq=qq*scale[:,:,None]+mu[:,:,None] + qq=(qq[:len(ids)]-qq[len(ids):].flip(-1))*.5 + recent=rule_x[:,-4096:] + positive=((recent>=0)|~torch.isfinite(recent)).all(-1) + qq=torch.where(positive[:,None,None],qq.clamp(min=0),qq) + q=qq.transpose(1,2).float().cpu().numpy() + q=apply_gate(rule_ctx[:,-4096:],p.cpu().numpy(),q) + q=project(rule_ctx,apply_continuity(rule_ctx,q)) + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + forecasts.append(q) + fourth=4 if h>=model.horizon_threshold else 3 + q=(forecasts[0]+forecasts[1]+forecasts[2]+forecasts[fourth])/4 + alternative=(forecasts[0]+forecasts[1]+forecasts[2]+forecasts[5])/4 + q=(q+alternative)/2 + # The independent four-expert gate receives exactly F0/F1/F2/F3. + gate_inputs=np.stack(forecasts[:4],axis=1).transpose(0,1,3,2).copy() + with torch.no_grad(): + expert_quantiles=torch.from_numpy(gate_inputs).to(x.device) + lengths=torch.full((len(ids),),h,device=x.device) + weights=model.gate(x,p,expert_quantiles,lengths) + gated=gate_combine(expert_quantiles,weights).transpose(1,2).cpu().numpy() + q=(q+gated)/2 + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'config.json'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/blend_assemble_and_validate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/blend_assemble_and_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..ea666b905a10b40f21b818c6e12950749100e4be --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/blend_assemble_and_validate.py @@ -0,0 +1,38 @@ +"""E159: assemble the reviewed six-expert candidate, then run the guarded public suite.""" +import json,os,subprocess,time +from pathlib import Path +R=Path('/workspace/research');started=time.monotonic() +selection=json.loads((R/'seasonal_six_member_blend_receipt.json').read_text());assert selection['selection_gate_passed'] +state=json.loads((R/'CURRENT_RESEARCH_STATE.json').read_text());declaration=state['selection_probes']['E159'] +current=state['published'];deltas=[x['skill']-y for x,y in zip(selection['rows'],[current['main_skill']]+current['earlier_skills'])] +assert sum(x>0 for x in deltas)>=3 and sum(deltas)>0 +receipt=R/'seasonal_six_member_blend_pipeline_receipt.json' +assert not receipt.exists() +status=dict(status='assembling',pid=os.getpid(),steps=[]) +def save(): + status['seconds']=time.monotonic()-started;temporary=receipt.with_suffix('.tmp') + temporary.write_text(json.dumps(status,indent=2));os.replace(temporary,receipt) +member=R/'candidate-fresh-seasonal-48k';package=R/'candidate-seasonal-six-member-blend' +commands=[('assemble_sixth',['python3',str(R/'direct_continuity/publish_general.py'), + '--weights',str(R/'runs/random_capacity_long_seasonal/ema048000.pt'), + '--report',str(R/'evals/random_capacity_long_seasonal_ema48000/report.json'),'--out',str(member), + '--runtime-dir',str(R/'random_capacity_long_seasonal_inference'), + '--model-file',str(R/'random_capacity_long_seasonal/model.py'),'--seasonal-mode','aligned', + '--zero-mass-threshold','.4','--fixed-trend-window','128', + '--training-code',str(R/'random_capacity'),'--training-code',str(R/'random_capacity_long_seasonal'), + '--training-code',str(R/'long_seasonal'),'--training-code',str(R/'recovery'),'--name','fresh-seasonal-48k'])] +command=['python3',str(R/'seasonal_six_member_blend/publish.py')] +for name in declaration['members']:command+=['--member',str(R/name)] +command+=['--out',str(package)] +commands+=[('assemble_six_member',command),('guarded_full_suite',['python3',str(R/'seasonal_six_member_blend/validate.py')])] +for label,command in commands: + status['status']=label;save();tick=time.monotonic();completed=subprocess.run(command) + status['steps'].append(dict(name=label,returncode=completed.returncode,seconds=time.monotonic()-tick));save() + if completed.returncode:status['status']='failed';save();raise SystemExit(completed.returncode) + if label=='assemble_sixth': + manifest=json.loads((member/'model_manifest.json').read_text()) + assert manifest['parameters']==146575680 and manifest['weights_sha256']==declaration['member_checkpoint_hashes'][5] + if label=='assemble_six_member': + manifest=json.loads((package/'model_manifest.json').read_text()) + assert manifest['parameters']==549426472 and [x['weights_sha256'] for x in manifest['members']]==declaration['member_checkpoint_hashes'] +status['status']='complete; full result review required';save();print(json.dumps(status),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/blend_check_composition.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/blend_check_composition.py new file mode 100644 index 0000000000000000000000000000000000000000..4e3955e7aa8b38e882df42f70a0e26a34cd9e09d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/blend_check_composition.py @@ -0,0 +1,20 @@ +"""Independent real-case composition for the fixed six-expert equal blend.""" +import json,time +from pathlib import Path +import h5py,numpy as np +R=Path('/workspace/research');started=time.monotonic();rows=[] +roots=[R/'composition-pred-width-transfer12k',R/'valid-pred-patch8-6k',R/'composition-pred-split-patch-12k',R/'composition-pred-fresh146m96',R/'composition-pred-capacity-patch8-6k',R/'composition-pred-fresh-seasonal-48k'] +for cid in ['electricity__H__short','solar__T__short','ett2__H__long']: + arrays=[] + for root in [R/'valid-pred-seasonal-six-member-blend',*roots]: + with h5py.File(root/'cases'/(cid+'.h5')) as f:arrays.append(f['quantiles'][:]) + actual=arrays[0];h=actual.shape[-1];selected=[0,1,2,4 if h>=720 else 3];expected=arrays[1].copy() + for i in selected[1:]:expected+=arrays[i+1] + expected/=4 + alternative=arrays[1].copy() + for i in [1,2,5]:alternative+=arrays[i+1] + alternative/=4;expected=(expected+alternative)/2 + assert np.array_equal(actual,expected) and np.isfinite(actual).all() + rows.append(dict(config_id=cid,horizon=h,selected_members=selected,shape=actual.shape,bitwise_equal_to_fixed_member_rule=True)) +result=dict(cpu_seconds=time.monotonic()-started,comparisons=rows,no_new_inference_or_training=True) +(R/'seasonal_six_member_blend_composition_checks.json').write_text(json.dumps(result,indent=2));print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/blend_check_runtime.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/blend_check_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..806f3fda92245c16623bd98240595475f0003de3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/blend_check_runtime.py @@ -0,0 +1,46 @@ +"""Check actual standalone composition and all-six forward calls on both rule branches.""" +import fcntl, hashlib, json, math, subprocess, sys, time +from pathlib import Path +import numpy as np +import torch + +R=Path('/workspace/research');package=R/'candidate-seasonal-six-member-blend';started=time.monotonic() +sys.path.insert(0,str(package));import predict +fixture=R/'fresh_capacity4_fixture';root=R/'seasonal_six_member_blend_fixture';root.mkdir(exist_ok=True) +refs=[R/'width12_fixture/standalone0',fixture/'standalone1',fixture/'standalone2',R/'fresh_capacity96_fixture/standalone3',R/'capacity_patch8_6k_ensemble_fixture/standalone3',root/'standalone5'] +descriptor=json.loads((package/'config.json').read_text());configs=json.loads((fixture/'input/index.json').read_text())['configs'] +assert {cfg['prediction_length']>=720 for cfg in configs}=={False,True} +with (R/'.evaluation.lock').open('a') as lock: + fcntl.flock(lock,fcntl.LOCK_EX) + subprocess.run(['python3',str(R/'candidate-fresh-seasonal-48k/predict.py'),str(fixture/'input'),str(refs[5]),'--batch','4'],check=True) + assert len(refs)==len(descriptor['members'])==6 + for ref,entry in zip(refs,descriptor['members']): + assert json.loads((ref/'model_manifest.json').read_text())['weights_sha256']==entry['weights_sha256'] + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False;torch.backends.cuda.matmul.allow_tf32=False + model=predict.load_model(package/'config.json');calls=[[] for _ in model.models] + def hook(index): + def record(module,args,output):calls[index].append(dict(horizon=int(args[2]),sign_averaged_rows=int(args[0].shape[0]))) + return record + handles=[member.register_forward_hook(hook(i)) for i,member in enumerate(model.models)] + predict.run(model,fixture/'input',root/'ensemble',batch=4) + for handle in handles:handle.remove() + checks=[] + for cfg in configs: + h=cfg['prediction_length'];selected=[0,1,2,4 if h>=720 else 3];filename=cfg['config_id']+'.h5' + expected=predict.ts_io.read_prediction_file(refs[0]/'cases'/filename)[1].copy() + for i in selected[1:]:expected+=predict.ts_io.read_prediction_file(refs[i]/'cases'/filename)[1] + expected/=4 + alternative=predict.ts_io.read_prediction_file(refs[0]/'cases'/filename)[1].copy() + for i in [1,2,5]:alternative+=predict.ts_io.read_prediction_file(refs[i]/'cases'/filename)[1] + alternative/=4;expected=(expected+alternative)/2 + mean,actual=predict.ts_io.read_prediction_file(root/'ensemble/cases'/filename) + assert np.array_equal(actual,expected) and np.array_equal(mean,actual[:,:,4]) + assert np.isfinite(actual).all() and np.all(np.diff(actual,axis=2)>=0) + count=cfg['n_instances']*cfg['n_variates'];per_member=[] + for member_calls in calls: + matching=[call for call in member_calls if call['horizon']==h] + assert len(matching)==math.ceil(count/4) and sum(call['sign_averaged_rows'] for call in matching)==2*count + per_member.append(len(matching)) + checks.append(dict(config_id=cfg['config_id'],horizon=h,selected_members=selected,bitwise_composition=True,finite_ordered=True,every_member_forecasts_every_instance=True,forward_calls_by_member=per_member)) +result=dict(descriptor_sha256=hashlib.sha256((package/'config.json').read_bytes()).hexdigest(),checks=checks,member_checkpoint_hashes=[entry['weights_sha256'] for entry in descriptor['members']],seconds=time.monotonic()-started) +(R/'seasonal_six_member_blend_runtime_checks.json').write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/blend_probe.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/blend_probe.py new file mode 100644 index 0000000000000000000000000000000000000000..be2530a46b7424d61e9c4835db98662f073d9d5f --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/blend_probe.py @@ -0,0 +1,48 @@ +"""Score one predeclared equal-weight ensemble using validation predictions only.""" +import argparse +import json +import math +import sys +import time +from pathlib import Path + +sys.path.insert(0,'/workspace/evaluation') +from ts_io import read_truth_file,read_prediction_file +from score import config_metrics,relative,gmean,json_safe + +ap=argparse.ArgumentParser() +ap.add_argument('--valid',required=True) +ap.add_argument('--baseline') +ap.add_argument('--pred',action='append',required=True) +ap.add_argument('--out',required=True) +a=ap.parse_args();assert len(a.pred)==6;started=time.monotonic();root=Path(a.valid) +index=json.loads((root/'input/index.json').read_text()) +baseline=json.loads(Path(a.baseline or root/'baseline.json').read_text())['configs'] +rows=[] +for cfg in index['configs']: + cid=cfg['config_id'];path=Path('cases')/(cid+'.h5') + y,scale,_=read_truth_file(root/'truth'/path) + predictions=[read_prediction_file(Path(member)/path)[1] for member in a.pred] + assert all(q.shape==predictions[0].shape for q in predictions) + selected=[0,1,2,4 if cfg['prediction_length']>=720 else 3] + q=predictions[0].copy() + for i in selected[1:]:q+=predictions[i] + q/=4 + alternative=predictions[0].copy() + for i in [1,2,5]:alternative+=predictions[i] + alternative/=4 + q=(q+alternative)/2 + metrics=config_metrics(y,scale,q[:,:,4],q) + rows.append({**cfg,'metrics':metrics,'relative':{k:relative(metrics[k],baseline[cid][k]) for k in ['mase','wql']}}) +rm=gmean([c['relative']['mase'] for c in rows]);rw=gmean([c['relative']['wql'] for c in rows]) +groups={} +for kind in ['term','domain','freq']: + buckets={} + for c in rows:buckets.setdefault(c[kind],[]).append(c) + groups[kind]={k:1-math.sqrt(gmean([c['relative']['mase'] for c in v])*gmean([c['relative']['wql'] for c in v])) for k,v in buckets.items()} +result={'composition':'All6 computed; equal FP32 mean of ordered E154horizon-rule quarters and E156seasonal48 quarters', + 'skill_score':1-math.sqrt(rm*rw),'rel_mase_gmean':rm,'rel_wql_gmean':rw, + 'groups':groups,'configs':rows,'cpu_seconds':time.monotonic()-started, + 'members':a.pred,'member_checkpoint_hashes':[json.loads((Path(p)/'report.json').read_text())['checkpoint_sha256'] for p in a.pred],'horizon_threshold':720,'weights_below_threshold':[.25,.25,.25,.125,0,.125],'weights_at_or_above_threshold':[.25,.25,.25,0,.125,.125],'selection_only':True} +Path(a.out).write_text(json.dumps(json_safe(result),indent=2)) +print(json.dumps({k:result[k] for k in ['skill_score','rel_mase_gmean','rel_wql_gmean','cpu_seconds']})) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/blend_publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/blend_publish.py new file mode 100644 index 0000000000000000000000000000000000000000..4d8dc6acbf326b792c98ab331aec1d5817571881 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/blend_publish.py @@ -0,0 +1,108 @@ +"""Assemble and atomically publish a complete six-member, fixed-horizon-rule package.""" +import argparse +import ctypes +import hashlib +import json +import os +import shutil +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ap = argparse.ArgumentParser() +ap.add_argument('--member', action='append', required=True) +ap.add_argument('--out', required=True) +ap.add_argument('--report') +ap.add_argument('--experiments', default='/workspace/research/direct_v1/EXPERIMENTS.md') +a = ap.parse_args() +assert len(a.member) == 6 +final = Path(a.out) +stage = final.parent / f'.{final.name}-staging-{os.getpid()}' +shutil.rmtree(stage, ignore_errors=True) +stage.mkdir(parents=True) + +def digest(path): + h = hashlib.sha256() + with Path(path).open('rb') as f: + for block in iter(lambda: f.read(8 * 1024 * 1024), b''): + h.update(block) + return h.hexdigest() + +for name in ('infer.sh', 'predict.py', 'model.py', 'seasonal.py', 'continuity.py', + 'zero_mass.py', 'ts_io.py'): + shutil.copy2(HERE / 'runtime' / name, stage / name) +shutil.copy2('/opt/runtime/requirements.txt', stage / 'requirements.txt') +shutil.copy2(a.experiments, stage / 'EXPERIMENTS.md') +members, sources, lineage = [], set(), {} +for i, source in enumerate(map(Path, a.member)): + manifest = json.loads((source / 'model_manifest.json').read_text()) + assert manifest['pretrained_assets'] == [] + for shared in ['seasonal.py','continuity.py','zero_mass.py']: + assert digest(source/shared)==digest(stage/shared),'Members must retain identical fixed postprocessing rules' + name = f'member{i}.pt' + model_code = f'model{i}.py' + shutil.copy2(source / 'model.py', stage / model_code) + assert digest(stage / model_code) == manifest['runtime_code_sha256']['model.py'] + shutil.copy2(source / 'weights.pt', stage / name) + assert digest(stage / name) == manifest['weights_sha256'] + members.append({'weights': name, 'weights_sha256': manifest['weights_sha256'], + 'parameters': manifest['parameters'], 'config': manifest['config'], 'model_code': model_code}) + sources.update(manifest['sources_used']) + for item in manifest['training_lineage']: + lineage.setdefault(item['sha256'], item) + dst = stage / 'provenance' / f'member{i}' + dst.mkdir(parents=True) + shutil.copy2(source / 'model_manifest.json', dst / 'model_manifest.json') + shutil.copytree(source / 'provenance', dst / 'training') +shutil.copy2(__file__, stage / 'provenance' / 'publish.py') +for script in HERE.glob('*.py'): + shutil.copy2(script, stage / 'provenance' / ('blend_' + script.name)) +descriptor = {'members': members, 'horizon_threshold': 720, 'blend_coefficient': .5, + 'weights_below_threshold': [.25,.25,.25,.125,0,.125], + 'weights_at_or_above_threshold': [.25,.25,.25,0,.125,.125], + 'composition': 'Every member forecasts every instance. A=(F0+F1+F2+F[4 if H>=720 else3])/4 and B=(F0+F1+F2+F5)/4 are ordered FP32 quarter means after fixed member rules; output=(A+B)/2 in FP32'} +(stage / 'config.json').write_text(json.dumps(descriptor, indent=2) + '\n') +identifier = digest(stage / 'config.json') +manifest = { + 'name': 'direct-seasonal-six-member-equal-blend', 'contract': 'timeseries-forecast/v1', + 'parameters': sum(m['parameters'] for m in members), 'pretrained_assets': [], + 'sources_used': sorted(sources), 'members': members, + 'checkpoint_sha256': identifier, + 'checkpoint_digest_method': 'SHA-256 of config.json, including ordered member weight hashes', + 'training_lineage': list(lineage.values()), 'ensemble_weights_by_horizon': {'below720':[.25,.25,.25,.125,0,.125], 'at_least720':[.25,.25,.25,0,.125,.125]}, + 'every_member_forecasts_every_instance': True, + 'member_history_caps': [{'input_and_summary': m['config']['max_context'], 'encoder_and_normalization': m['config'].get('encoder_context',m['config']['max_context']), 'fixed_rules': m['config'].get('encoder_context',m['config']['max_context'])} for m in members], + 'postprocessing_order': 'each member: sign averaging, positivity, aligned seasonal rule, continuity, zero0.4, finite-value replacement; then form ordered E154 horizon-rule quarter mean and E156 seasonal48 quarter mean, and average those two in FP32 with equal weight', + 'runtime_code_sha256': {p.name: digest(p) for p in stage.iterdir() if p.suffix in ('.py', '.sh')}, + 'notes': 'All members originate from random initialization in this workspace. Only declared pretraining sources and local generators were used. Validation is selection/diagnostics only. No inference-time fitting or parameter adaptation.', +} +(stage / 'model_manifest.json').write_text(json.dumps(manifest, indent=2) + '\n') +if a.report: + report = json.loads(Path(a.report).read_text()) + assert report['checkpoint_sha256'] == identifier + shutil.copy2(a.report, stage / 'validation_report.json') +else: + report = {'status': 'candidate validation pending'} + (stage / 'validation_report.json').write_text(json.dumps(report) + '\n') +if final.resolve() == Path('/workspace/submission').resolve(): + assert a.report and report['n_configs'] == 97 and report['n_instances'] == 151170 + assert report['n_failed'] == 0 +patch_sizes = ', '.join(str(m['config'].get('input_patch', m['config']['patch'])) + '/' + str(m['config']['patch']) for m in members) +(stage / 'README.md').write_text(f'''# Six-member seasonal foundation forecaster + +Run `bash infer.sh INPUT_DIR OUTPUT_DIR`. All runtime assets are included, with versions pinned in requirements.txt. The package contains six locally trained models totaling {manifest['parameters']:,} parameters. Every member forecasts every instance. First form two ordered FP32 quarter means: A uses members0,1,2 plus member3 for horizons below720, or member4 otherwise; B uses members0,1,2,5. The final quantiles are the equal FP32 average (A+B)/2. All six contributions are computed before this fixed composition. This one equal blend was selected on validation, with no coefficient or horizon-threshold sweep and no fitting on input contexts. + +Each member retains its declared context limits, listed in model_manifest.json under member_history_caps. A model with a separate encoder_context uses longer history only for learned seasonal summaries; its encoder, normalization and fixed forecast rules use the shorter declared limit. Their history/forecast patch sizes are {patch_sizes}, in member order. Each member retains its own original model implementation and normalization; overflow handling follows each member's own implementation. Each member uses finite-history normalization and the same fixed sign averaging, positivity, seasonal, continuity and zero-mass rules. The seasonal template aligns four cycles to the latest cycle's mean and amplitude. The trend summary uses a fixed width of 128 observations. The zero projection threshold is 0.4 context standard deviations. No additional zero projection is applied after averaging. There is no inference-time training, fitting or parameter adaptation. + +model_manifest.json declares every source, member hash and training lineage. config.json contains relative member paths and their hashes. The original member manifests and all trainer/generator code are archived in provenance/. No pretrained assets were used. Normalization uses the supplied context and needs no external statistics. + +EXPERIMENTS.md records hypotheses, negative results, compute, group metrics and hashes. validation_report.json records the package evaluation. Validation and earlier-cutoff scores are not the held-out reward scale. +''') +if final.exists(): + libc = ctypes.CDLL(None, use_errno=True) + if libc.renameat2(-100, os.fsencode(stage), -100, os.fsencode(final), 2): + raise OSError(ctypes.get_errno(), os.strerror(ctypes.get_errno())) + shutil.rmtree(stage) +else: + os.replace(stage, final) +print(json.dumps({'out': str(final), 'checkpoint_sha256': identifier, + 'parameters': manifest['parameters']})) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/blend_run.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/blend_run.py new file mode 100644 index 0000000000000000000000000000000000000000..0a6a659fcda7efe8102af4e0505f8e1f944d840e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/blend_run.py @@ -0,0 +1,27 @@ +"""One predeclared equal blend with six computed experts; cached validation selection only.""" +import datetime, json, subprocess, time +from pathlib import Path + +R=Path('/workspace/research');started=time.monotonic() +declaration=json.loads((R/'CURRENT_RESEARCH_STATE.json').read_text())['selection_probes']['E159'] +rows=[] +names=['seasonal_width_transfer12k','patch8_ema6000','split_patch_ema12000','random_capacity_1024_ema96000','capacity_patch8_candidate_ema6000','random_capacity_long_seasonal_ema48000'] +for cutoff,folder in [('valid_screen','evals'),('valid_backcast','backcast_evals'),('valid_backcast2','backcast2_evals'),('valid_backcast3','backcast3_evals')]: + out=R/f'seasonal_six_member_blend_{cutoff}.json';assert not out.exists() + parent=json.loads((R/f'horizon_patch8_routing_{cutoff}.json').read_text()) + assert parent['member_checkpoint_hashes']==declaration['member_checkpoint_hashes'][:5] + command=['python3',str(R/'seasonal_six_member_blend/probe.py'),'--valid',str(R/cutoff),'--out',str(out)] + for name,sha in zip(names,declaration['member_checkpoint_hashes']): + report=json.loads((R/folder/name/'report.json').read_text()) + assert report['checkpoint_sha256']==sha and report['n_failed']==0 + command+=['--pred',str(R/folder/name)] + subprocess.run(command,check=True) + probe=json.loads(out.read_text());assert probe['member_checkpoint_hashes']==declaration['member_checkpoint_hashes'] + rows.append(dict(cutoff=cutoff,skill=probe['skill_score'],control_skill=parent['skill_score'],delta=probe['skill_score']-parent['skill_score'], + groups=probe['groups'],group_deltas={key:{name:value-parent['groups'][key][name] for name,value in group.items()} for key,group in probe['groups'].items()},cpu_seconds=probe['cpu_seconds'])) +result=dict(declaration=declaration,rows=rows,positive_cutoffs=sum(row['delta']>0 for row in rows),mean_delta=sum(row['delta'] for row in rows)/4, + seconds=time.monotonic()-started,optimizer_updates=0,new_neural_inference=False) +result['selection_gate_passed']=result['positive_cutoffs']>=3 and result['mean_delta']>0 +(R/'seasonal_six_member_blend_receipt.json').write_text(json.dumps(result,indent=2)) +with (R/'direct_v1/EXPERIMENTS.md').open('a') as f:f.write('\n'+datetime.datetime.now(datetime.timezone.utc).isoformat()+': E159 fixed equal-pool probes '+json.dumps(result)+'. No automatic publication.\n') +print(json.dumps(result),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/blend_validate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/blend_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..42eac7e9e621e141c7c983b5c0d3fffc3cae0cfa --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/blend_validate.py @@ -0,0 +1,26 @@ +"""Complete public replay only after the fixed E159 cutoff gates.""" +import json,os,subprocess,time +from pathlib import Path +R=Path('/workspace/research');selection=json.loads((R/'seasonal_six_member_blend_receipt.json').read_text());assert selection['selection_gate_passed'] +current=json.loads((R/'CURRENT_RESEARCH_STATE.json').read_text())['published'] +deltas=[row['skill']-value for row,value in zip(selection['rows'],[current['main_skill']]+current['earlier_skills'])] +assert len(deltas)==4 and sum(x>0 for x in deltas)>=3 and sum(deltas)>0 +package=R/'candidate-seasonal-six-member-blend';report=R/'valid-report-seasonal-six-member-blend.json';pred=R/'valid-pred-seasonal-six-member-blend' +manifest=json.loads((package/'model_manifest.json').read_text());assert manifest['parameters']==549426472 +assert [entry['weights_sha256'] for entry in manifest['members']]==selection['declaration']['member_checkpoint_hashes'] +started=time.monotonic();receipt=R/'seasonal_six_member_blend_validation_receipt.json' +state=dict(status='running',package=str(package),steps=[],current_parent=current['checkpoint_sha256'],current_cutoff_deltas=deltas) +def save(): + state['seconds']=time.monotonic()-started;tmp=receipt.with_suffix('.tmp');tmp.write_text(json.dumps(state,indent=2));os.replace(tmp,receipt) +commands=[('synthetic_composition_and_every_member_calls',['python3',str(R/'seasonal_six_member_blend/check_runtime.py')]), + ('relocation',['python3',str(R/'verify_package_examples.py'),'--package',str(package),'--receipt',str(R/'seasonal_six_member_blend_package_checks.json')]), + ('full_public_replay',['python3',str(R/'run_package_validation.py'),'--package',str(package),'--out',str(pred),'--report',str(report)]), + ('independent_sixth_member',['python3',str(R/'run_composition_member.py'),'--package',str(R/'candidate-fresh-seasonal-48k'),'--out',str(R/'composition-pred-fresh-seasonal-48k'),'--receipt',str(R/'seasonal_six_member_blend_standalone_composition_replay.json')]), + ('real_composition',['python3',str(R/'seasonal_six_member_blend/check_composition.py')]), + ('descriptive_comparison',['python3',str(R/'compare_reports.py'),'--candidate',str(report),'--parent',current['full_report'],'--out',str(R/'seasonal_six_member_blend_comparison.json')])] +for label,command in commands: + state['current_step']=label;save();tick=time.monotonic();completed=subprocess.run(command) + state['steps'].append(dict(name=label,returncode=completed.returncode,seconds=time.monotonic()-tick));save() + if completed.returncode:state['status']='failed';save();raise SystemExit(completed.returncode) +full=json.loads(report.read_text());assert full['n_failed']==0 and full['n_configs']==97 and full['n_instances']==151170 +state.update(status='complete; review required',skill=full['skill_score']);save();print(json.dumps(state),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/model_manifest.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/model_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..42e69b5c2324df1b3378a803d7b73e49b05f944e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/model_manifest.json @@ -0,0 +1,1482 @@ +{ + "name": "direct-seasonal-foundation", + "contract": "timeseries-forecast/v1", + "parameters": 36899168, + "pretrained_assets": [], + "sources_used": [ + "gifteval_pretrain/BEIJING_SUBWAY_30MIN", + "gifteval_pretrain/HZMETRO", + "gifteval_pretrain/LOS_LOOP", + "gifteval_pretrain/PEMS03", + "gifteval_pretrain/PEMS04", + "gifteval_pretrain/PEMS07", + "gifteval_pretrain/PEMS08", + "gifteval_pretrain/PEMS_BAY", + "gifteval_pretrain/Q-TRAFFIC", + "gifteval_pretrain/SHMETRO", + "gifteval_pretrain/alibaba_cluster_trace_2018", + "gifteval_pretrain/australian_electricity_demand", + "gifteval_pretrain/azure_vm_traces_2017", + "gifteval_pretrain/bdg-2_bear", + "gifteval_pretrain/bdg-2_fox", + "gifteval_pretrain/bdg-2_panther", + "gifteval_pretrain/bdg-2_rat", + "gifteval_pretrain/bitcoin_with_missing", + "gifteval_pretrain/borealis", + "gifteval_pretrain/borg_cluster_data_2011", + "gifteval_pretrain/buildings_900k", + "gifteval_pretrain/bull", + "gifteval_pretrain/cdc_fluview_ilinet", + "gifteval_pretrain/cdc_fluview_who_nrevss", + "gifteval_pretrain/china_air_quality", + "gifteval_pretrain/cif_2016_12", + "gifteval_pretrain/cif_2016_6", + "gifteval_pretrain/cmip6_2000", + "gifteval_pretrain/cmip6_2005", + "gifteval_pretrain/cmip6_2010", + "gifteval_pretrain/cockatoo", + "gifteval_pretrain/covid19_energy", + "gifteval_pretrain/covid_mobility", + "gifteval_pretrain/elecdemand", + "gifteval_pretrain/elf", + "gifteval_pretrain/era5_2010", + "gifteval_pretrain/era5_2011", + "gifteval_pretrain/era5_2012", + "gifteval_pretrain/era5_2013", + "gifteval_pretrain/era5_2014", + "gifteval_pretrain/era5_2015", + "gifteval_pretrain/era5_2016", + "gifteval_pretrain/era5_2017", + "gifteval_pretrain/era5_2018", + "gifteval_pretrain/extended_web_traffic_with_missing", + "gifteval_pretrain/favorita_sales", + "gifteval_pretrain/favorita_transactions", + "gifteval_pretrain/gfc12_load", + "gifteval_pretrain/gfc14_load", + "gifteval_pretrain/gfc17_load", + "gifteval_pretrain/godaddy", + "gifteval_pretrain/hog", + "gifteval_pretrain/ideal", + "gifteval_pretrain/kaggle_web_traffic_weekly", + "gifteval_pretrain/kdd2022", + "gifteval_pretrain/largest_2017", + "gifteval_pretrain/largest_2018", + "gifteval_pretrain/largest_2019", + "gifteval_pretrain/largest_2020", + "gifteval_pretrain/largest_2021", + "gifteval_pretrain/lcl", + "gifteval_pretrain/london_smart_meters_with_missing", + "gifteval_pretrain/m1_monthly", + "gifteval_pretrain/m1_quarterly", + "gifteval_pretrain/m1_yearly", + "gifteval_pretrain/m5", + "gifteval_pretrain/monash_m3_monthly", + "gifteval_pretrain/monash_m3_other", + "gifteval_pretrain/monash_m3_quarterly", + "gifteval_pretrain/nn5_daily_with_missing", + "gifteval_pretrain/nn5_weekly", + "gifteval_pretrain/oikolab_weather", + "gifteval_pretrain/pdb", + "gifteval_pretrain/project_tycho", + "gifteval_pretrain/residential_load_power", + "gifteval_pretrain/residential_pv_power", + "gifteval_pretrain/rideshare_with_missing", + "gifteval_pretrain/sceaux", + "gifteval_pretrain/smart", + "gifteval_pretrain/solar_power", + "gifteval_pretrain/spain", + "gifteval_pretrain/subseasonal", + "gifteval_pretrain/subseasonal_precip", + "gifteval_pretrain/sunspot_with_missing", + "gifteval_pretrain/taxi_30min", + "gifteval_pretrain/tourism_quarterly", + "gifteval_pretrain/tourism_yearly", + "gifteval_pretrain/traffic_hourly", + "gifteval_pretrain/traffic_weekly", + "gifteval_pretrain/uber_tlc_daily", + "gifteval_pretrain/uber_tlc_hourly", + "gifteval_pretrain/vehicle_trips_with_missing", + "gifteval_pretrain/wiki-rolling_nips", + "gifteval_pretrain/wind_farms_with_missing", + "gifteval_pretrain/wind_power", + "synthetic:both original and sign-reflected orientations of each sampled allowed or locally generated window; paired quantile loss, seed 197", + "synthetic:both original and sign-reflected orientations of each sampled window, seed 197", + "synthetic:independent sign reflection of sampled allowed-corpus and locally generated windows; seeds 43,47,59,79,89,197", + "synthetic:own Fourier/trend/AR/intermittent/changepoint generator at weekly periods52,1, replacing a Bernoulli1/11 share of the original synthetic rows with unchanged total synthetic fraction; independent seed 1000200", + "synthetic:own Fourier/trend/intermittent generator with AR time constant log-uniform from 1 to 10000 steps and zero initial state; seed 79", + "synthetic:own direct_v1 Fourier seasons, damped trends, AR noise, changepoints and intermittent demand; seeds 23,43,47,59,79,89,197,503,577,661", + "synthetic:own random requested-horizon prefixes, half of rows retain the full horizon and half use a patch-rounded prefix between one-quarter and the full horizon; independent seed 300200", + "synthetic:own stationary Gaussian residuals generated by FFT, equal Matern0.5/1.5/2.5 and RBF spectral families, length scale log-uniform1to10000, theoretical unit marginal variance, FFT size next power of two at least4times window; replacing half of original synthetic residuals with all other generator components unchanged; independent seed 1100200" + ], + "weights_sha256": "0b11b7351a4a92d1d18c71a4159ec445be3a94ace8c7a9fa0edafad87d14e960", + "config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true, + "seasonal_dispersion_features": true, + "seasonal_width_features": true + }, + "training_lineage": [ + { + "checkpoint": "seasonal_width_transfer12k.pt", + "sha256": "0b11b7351a4a92d1d18c71a4159ec445be3a94ace8c7a9fa0edafad87d14e960", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true, + "seasonal_dispersion_features": true, + "seasonal_width_features": true + }, + "conversion": { + "method": "matched direct-width-head training delta, separately zero-extending base and control", + "formula": "zero_extend(E117first)+E129-zero_extend(E119)", + "coefficient": 1.0, + "base_zero_parameters": [ + "dispersion_query.weight", + "width_head.bias", + "width_head.weight" + ], + "control_zero_parameters": [ + "width_head.bias", + "width_head.weight" + ], + "dispersion_query": "candidate-minus-control only; no E128 correction", + "parent_hashes": { + "/workspace/research/long_seasonal_transfer12k.pt": "8a2b252b733cc79c31778ea27ba00fbe61206fef50454514b667c54a928d80a4", + "/workspace/research/runs/seasonal_width/ema012000.pt": "8a8c75cafcc7b42266aaab7d8458cb383b65313ce6da8c396e76760f7ab6e33c", + "/workspace/research/runs/seasonal_dispersion/ema012000.pt": "b0204fa8dd3371d9160fc00545d6b065ccb23bb18e345b3b63cd39c024c9acf5" + }, + "base_extension_forward_bitwise_equal": true, + "finite_ordered_fixture": true, + "check_seed": 769, + "seconds": 2.078599537955597, + "optimizer_updates": 0, + "validation_data_read": false + }, + "parents": [ + "long_seasonal_transfer12k.pt", + "runs/seasonal_width/ema012000.pt", + "runs/seasonal_dispersion/ema012000.pt" + ] + }, + { + "checkpoint": "long_seasonal_transfer12k.pt", + "sha256": "8a2b252b733cc79c31778ea27ba00fbe61206fef50454514b667c54a928d80a4", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true + }, + "conversion": { + "method": "matched training delta after zero extension of new seasonal query/head parameters", + "formula": "extend_zero(base) + candidate - extend_zero(control)", + "coefficient": 1.0, + "new_parameters_from_candidate": [ + "long_head.bias", + "long_head.weight", + "long_query.weight" + ], + "parent_hashes": { + "/workspace/research/spectral_add_delta6k.pt": "c3dfc433d51355228fc13d04913db1a7edf83030c33283b150bdcc50f5ae6ea2", + "/workspace/research/runs/long_seasonal/ema012000.pt": "d512cdac520239f0c10e021721424d87cee30086fa70f6cbc41f21e2e04988c3", + "/workspace/research/runs/overflow_control/ema012000.pt": "f11d056b95f1c5eeef174265ebc51742952600e0dae1fa52900860447d5be819" + }, + "base_extension_forward_bitwise_equal": true, + "check_seed": 571, + "seconds": 2.5279976530000567, + "optimizer_updates": 0, + "validation_data_read": false + }, + "parents": [ + "spectral_add_delta6k.pt", + "runs/long_seasonal/ema012000.pt", + "runs/overflow_control/ema012000.pt" + ] + }, + { + "checkpoint": "runs/seasonal_width/ema012000.pt", + "sha256": "8a8c75cafcc7b42266aaab7d8458cb383b65313ce6da8c396e76760f7ab6e33c", + "step": 12000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null, + "teacher_coefficient": null, + "compile_teacher": false, + "visibility_curriculum": false + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true, + "seasonal_dispersion_features": true, + "seasonal_width_features": true + }, + "parents": [ + "seasonal_width_initial.pt", + "seasonal_dispersion_initial.pt" + ] + }, + { + "checkpoint": "runs/seasonal_dispersion/ema012000.pt", + "sha256": "b0204fa8dd3371d9160fc00545d6b065ccb23bb18e345b3b63cd39c024c9acf5", + "step": 12000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null, + "teacher_coefficient": null + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true, + "seasonal_dispersion_features": true + }, + "parents": [ + "seasonal_dispersion_initial.pt", + "long_seasonal_initial.pt" + ] + }, + { + "checkpoint": "spectral_add_delta6k.pt", + "sha256": "c3dfc433d51355228fc13d04913db1a7edf83030c33283b150bdcc50f5ae6ea2", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/weekly_slow_ar_delta6k.pt": "c8adf9cadf97dac5e120d8d4d2c8c025bffa2e8b55d8664bf900cce55d00a70b", + "/workspace/research/runs/spectral_synth/ema006000.pt": "683f3824d3c1f605d17bb08d3eef127a54c67eca3867cfbcf1158710a55c4b24", + "/workspace/research/runs/overflow_control/ema006000.pt": "b19875c52ed5024383fb69ccc48cb07a5629ad8011abf134c7dcfcdc50fae2af" + }, + "seconds": 1.4204325219616294 + }, + "parents": [ + "weekly_slow_ar_delta6k.pt", + "runs/spectral_synth/ema006000.pt", + "runs/overflow_control/ema006000.pt" + ] + }, + { + "checkpoint": "runs/long_seasonal/ema012000.pt", + "sha256": "d512cdac520239f0c10e021721424d87cee30086fa70f6cbc41f21e2e04988c3", + "step": 12000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null, + "teacher_coefficient": null + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true, + "long_seasonal_features": true + }, + "parents": [ + "long_seasonal_initial.pt", + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "runs/overflow_control/ema012000.pt", + "sha256": "f11d056b95f1c5eeef174265ebc51742952600e0dae1fa52900860447d5be819", + "step": 12000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "seasonal_width_initial.pt", + "sha256": "94ba155b90c6b510bccf92358cc225afe8f317285a19637ab5ca68072bbb83d1", + "step": 0, + "seed": 661, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "long_seasonal_features": true, + "seasonal_dispersion_features": true, + "seasonal_width_features": true + }, + "conversion": { + "method": "zero-initialized direct seasonal width head", + "parent_sha256": "5f07cac4fe7de3e878a01cb90384e79905fdb3156122b568e82c5923526aca3c", + "initial_function_bitwise_equal": true + }, + "parents": [ + "seasonal_dispersion_initial.pt" + ] + }, + { + "checkpoint": "seasonal_dispersion_initial.pt", + "sha256": "5f07cac4fe7de3e878a01cb90384e79905fdb3156122b568e82c5923526aca3c", + "step": 0, + "seed": 577, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "long_seasonal_features": true, + "seasonal_dispersion_features": true + }, + "conversion": { + "method": "zero-initialized phase-specific cycle-centered standard-deviation query", + "parent_sha256": "470ef98d69d00b17defbf41c70a92b22574154cdb6e0317993bccf113e4af93b", + "initial_function_bitwise_equal": true + }, + "parents": [ + "long_seasonal_initial.pt" + ] + }, + { + "checkpoint": "long_seasonal_initial.pt", + "sha256": "470ef98d69d00b17defbf41c70a92b22574154cdb6e0317993bccf113e4af93b", + "step": 0, + "seed": 503, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "long_seasonal_features": true + }, + "conversion": { + "method": "zero-initialized sixteen-cycle centered seasonal query/head additions", + "parent_sha256": "22c08571978be31ba57368eb983089a40a44d56d4ae5e17da41afd2a761a258c", + "initial_function_bitwise_equal": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "weekly_slow_ar_delta6k.pt", + "sha256": "c8adf9cadf97dac5e120d8d4d2c8c025bffa2e8b55d8664bf900cce55d00a70b", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/postloss_slow_ar_delta6k.pt": "0ae7875b49b99a44c295dc2b8243327aeacadc25b2354988abb2c37250359a49", + "/workspace/research/runs/weekly_synth/ema006000.pt": "de053e5baf9641e9245519990d6e5193fc91392cb76e72ceffee1ce63f578fca", + "/workspace/research/runs/overflow_control/ema006000.pt": "b19875c52ed5024383fb69ccc48cb07a5629ad8011abf134c7dcfcdc50fae2af" + }, + "seconds": 2.0751679679378867 + }, + "parents": [ + "postloss_slow_ar_delta6k.pt", + "runs/weekly_synth/ema006000.pt", + "runs/overflow_control/ema006000.pt" + ] + }, + { + "checkpoint": "runs/spectral_synth/ema006000.pt", + "sha256": "683f3824d3c1f605d17bb08d3eef127a54c67eca3867cfbcf1158710a55c4b24", + "step": 6000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null, + "teacher_coefficient": null, + "spectral_synthetic_seed": 1100200, + "spectral_replacement_probability": 0.5, + "spectral_length_scale": [ + 1, + 10000 + ], + "spectral_families": [ + "Matern0.5", + "Matern1.5", + "Matern2.5", + "RBF" + ] + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt", + "runs/confidence_query/ema006000.pt", + "runs/horizon_jitter/ema012000.pt", + "runs/large_corpus_control/ema012000.pt" + ] + }, + { + "checkpoint": "runs/overflow_control/ema006000.pt", + "sha256": "b19875c52ed5024383fb69ccc48cb07a5629ad8011abf134c7dcfcdc50fae2af", + "step": 6000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "horizon_delta12k.pt", + "sha256": "22c08571978be31ba57368eb983089a40a44d56d4ae5e17da41afd2a761a258c", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/runs/confidence_query/ema006000.pt": "0bad97e8994aac49ea173443db0a4fa8d72d33f9eb9e2660f06de75f7f1403eb", + "/workspace/research/runs/horizon_jitter/ema012000.pt": "830179d763916a1065fc615d2c5e22f4a3b5b19390dde707ab0f057e13cadff6", + "/workspace/research/runs/large_corpus_control/ema012000.pt": "7f9ba5e01ac59c51a3b63d3067b442e23e15d0abc51ddbcccdd04d6083ae4add" + }, + "seconds": 1.2663014469435439 + }, + "parents": [ + "runs/confidence_query/ema006000.pt", + "runs/horizon_jitter/ema012000.pt", + "runs/large_corpus_control/ema012000.pt" + ] + }, + { + "checkpoint": "postloss_slow_ar_delta6k.pt", + "sha256": "0ae7875b49b99a44c295dc2b8243327aeacadc25b2354988abb2c37250359a49", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/runs/postloss/ema003000.pt": "82c785d40998e155a20290c9965c346c26cd397fa0f3cf36278377ad2aed5c7d", + "/workspace/research/runs/long_memory_synth_recovery/ema006000.pt": "fea5b5290a3a9be5618eaeaf67e918e4f677d5be908d562040ce4bdfeb549bd9", + "/workspace/research/runs/partial_targets/ema006000.pt": "67562486b099a350da53c3caa5ff0932fe7fecdfe72c1879b064b2a9bb173dfb" + }, + "seconds": 1.0092943429481238 + }, + "parents": [ + "runs/postloss/ema003000.pt", + "runs/long_memory_synth_recovery/ema006000.pt", + "runs/partial_targets/ema006000.pt" + ] + }, + { + "checkpoint": "runs/weekly_synth/ema006000.pt", + "sha256": "de053e5baf9641e9245519990d6e5193fc91392cb76e72ceffee1ce63f578fca", + "step": 6000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "normalization_overflow_fallback": true, + "weekly_synthetic_seed": 1000200, + "weekly_replacement_probability": 0.09090909090909091, + "anneal_from_step": null, + "anneal_from_lr": null, + "anneal_final_lr": null + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "runs/confidence_query/ema006000.pt", + "sha256": "0bad97e8994aac49ea173443db0a4fa8d72d33f9eb9e2660f06de75f7f1403eb", + "step": 6000, + "seed": 89, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 0.0002, + "steps": 6000 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true + }, + "parents": [ + "runs/recency_features/ema024000.pt" + ] + }, + { + "checkpoint": "runs/horizon_jitter/ema012000.pt", + "sha256": "830179d763916a1065fc615d2c5e22f4a3b5b19390dde707ab0f057e13cadff6", + "step": 12000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "partial_target_lengths": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/large_corpus_control/ema012000.pt", + "sha256": "7f9ba5e01ac59c51a3b63d3067b442e23e15d0abc51ddbcccdd04d6083ae4add", + "step": 12000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/postloss/ema003000.pt", + "sha256": "82c785d40998e155a20290c9965c346c26cd397fa0f3cf36278377ad2aed5c7d", + "step": 3000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200, + "fixed_postprocessing_loss": true, + "normalization_overflow_fallback": true + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "runs/long_memory_synth_recovery/ema006000.pt", + "sha256": "fea5b5290a3a9be5618eaeaf67e918e4f677d5be908d562040ce4bdfeb549bd9", + "step": 6000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "context": null, + "sample_context": 4096, + "synthetic_ar_time_constants": [ + 1, + 10000 + ] + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "partial_target_lengths": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/partial_targets/ema006000.pt", + "sha256": "67562486b099a350da53c3caa5ff0932fe7fecdfe72c1879b064b2a9bb173dfb", + "step": 6000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "partial_target_lengths": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/recency_features/ema024000.pt", + "sha256": "1530fbb577a87ca4eb39da83d6fee9b8ee5bc924202e021e3a7b56493112f564", + "step": 24000, + "seed": 59, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/patch16_trial/ema006000.pt" + ] + }, + { + "checkpoint": "runs/recency_features/ema012000.pt", + "sha256": "8ccb6870a025e1097331a3a288b1183741a413f3460fbf3352d0c589c6a4394c", + "step": 12000, + "seed": 59, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/patch16_trial/ema006000.pt" + ] + }, + { + "checkpoint": "runs/patch16_trial/ema006000.pt", + "sha256": "0ff54447074e0271d2e331c7d3e6e9e0fdd73353e4d8cef0175ff627385f71c3", + "step": 6000, + "seed": 47, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024 + }, + "parents": [ + "patch16_init.pt" + ] + }, + { + "checkpoint": "patch16_init.pt", + "sha256": "d69531bfde5bf801e7f36c515bf15fd0cae0bd84f7d1479d35f4a7b67f26b508", + "step": 6000, + "seed": 43, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024 + }, + "conversion": { + "from_checkpoint": "/run-state/workspace/research/runs/large_sign/ema006000.pt", + "from_sha256": "96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547", + "method": "fold input/query halves by summation; retain first 16 output rows; preserve physical positional units" + }, + "parents": [ + "runs/large_sign/ema006000.pt" + ] + }, + { + "checkpoint": "runs/large_sign/ema006000.pt", + "sha256": "96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547", + "step": 6000, + "seed": 43, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 32, + "max_context": 4096, + "max_horizon": 1024 + }, + "parents": [ + "runs/direct_large/step024000.pt" + ] + }, + { + "checkpoint": "runs/direct_large/step024000.pt", + "sha256": "b7e4f38aebcd2cf38ce484edaad8d19851317fb3b8df485e2faa0d0423cbcb48", + "step": 24000, + "seed": 23, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 128, + "lr": 0.0002, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 32, + "max_context": 4096, + "max_horizon": 1024 + }, + "initialization": "random initialization in this workspace" + } + ], + "symmetric_averaging": true, + "seasonal_gate": { + "variance_ratio_threshold": 0.25, + "maximum_weight": 0.98, + "cycles_averaged": 4, + "template_mode": "aligned", + "amplitude_ratio_clip": [ + 0.5, + 2.0 + ], + "latest_cycle_minimum_coverage": 0.75, + "variance_noise_correction": "mean squared seasonal differences / 2" + }, + "continuity": { + "decay_steps": 24, + "variance_ratio_threshold": 0.5, + "maximum_weight": 0.95, + "lookback": 512, + "slope_median_differences": 8 + }, + "notes": "All training lineage originates from random initialization here, using only the declared corpus and locally generated series. Validation was used only for selection and diagnostics. Context transformations are fixed formulas; there is no inference-time fitting or parameter adaptation.", + "runtime_code_sha256": { + "predict.py": "9bde896945a2cd8f892e7eeb6328ed2dfda09293532f3a4a64d929c9943614ef", + "seasonal.py": "b946e63048196ab5ea8b249137d48c80d8510943caccd0f180e4fb86d9b24b37", + "ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "model.py": "0d9557eca352e3c493f47c310355aa576da2e75c8f7cb5b69786c3d162644f38", + "continuity.py": "dbb08d2229ad80ad00f638b0b9f2f6ca13c663e0fd6730058e5fee8ff54545d5", + "infer.sh": "5fe66b4fe9a4787285d830cfd96975701e97286a75ba7c3687bd8891475edf68", + "zero_mass.py": "f079d509009bcda409b80eb64467c869b838cfbab11b2bd4c660c2875b6642fe" + }, + "checkpoint_composition": { + "method": "matched direct-width-head training delta, separately zero-extending base and control", + "formula": "zero_extend(E117first)+E129-zero_extend(E119)", + "coefficient": 1.0, + "base_zero_parameters": [ + "dispersion_query.weight", + "width_head.bias", + "width_head.weight" + ], + "control_zero_parameters": [ + "width_head.bias", + "width_head.weight" + ], + "dispersion_query": "candidate-minus-control only; no E128 correction", + "parent_hashes": { + "/workspace/research/long_seasonal_transfer12k.pt": "8a2b252b733cc79c31778ea27ba00fbe61206fef50454514b667c54a928d80a4", + "/workspace/research/runs/seasonal_width/ema012000.pt": "8a8c75cafcc7b42266aaab7d8458cb383b65313ce6da8c396e76760f7ab6e33c", + "/workspace/research/runs/seasonal_dispersion/ema012000.pt": "b0204fa8dd3371d9160fc00545d6b065ccb23bb18e345b3b63cd39c024c9acf5" + }, + "base_extension_forward_bitwise_equal": true, + "finite_ordered_fixture": true, + "check_seed": 769, + "seconds": 2.078599537955597, + "optimizer_updates": 0, + "validation_data_read": false + }, + "normalization_overflow_fallback": { + "trigger": "nonfinite float32 context mean or scale", + "arithmetic": "float64 context statistics on affected rows; original arithmetic on ordinary rows", + "inference_fitting": false + }, + "trend_summary": { + "fixed_averaging_width": 128, + "matches_all_pretraining_context_widths": true, + "independent_of_batch_padding": true + }, + "zero_mass_projection": { + "threshold_in_context_standard_deviations": 0.4, + "nonnegative_context_required": true, + "minimum_exact_zeros": 4, + "minimum_zero_fraction": 0.1, + "context_cap": 4096 + }, + "recency_features": { + "query_projection_parameters": 32768, + "latest_vs_four_cycle_level": true, + "amplitude_ratio_clip": [ + 0.5, + 2.0 + ], + "minimum_observed_cycles": 3 + }, + "seasonal_dispersion_features": { + "features": "log1p unbiased standard deviation across matching phases of four and sixteen individually centered cycles, for each of two periods", + "active_rule": "period>=2,at least2recent and8total matching-phase observations", + "query_projection_parameters": 32768, + "initialization": "zero projection preserves the own parent model exactly", + "trainable_scope": "all parameters", + "fixed_output_rescaling": false + }, + "seasonal_width_features": { + "head_parameters": 16416, + "delta": "active*(log1p(cycle-centered matching-phase standard deviation over16cycles)-log2)", + "multiplier": "exp(clamp(sum(tanh(learned_gate)*delta),-log4,log4))", + "bounds": [ + 0.25, + 4.0 + ], + "active_rule": "period>=2,n4>=2,n16>=8", + "all_eight_width_increments_share_multiplier": true, + "zero_initialization_preserves_parent": true, + "trainable_scope": "all parameters" + }, + "long_seasonal_features": { + "cycles": [ + 4, + 16 + ], + "each_cycle_centered": true, + "minimum_total_cycles": 8, + "minimum_recent_cycles": 2, + "query_features": [ + "centered16-minus4 phase mean", + "observed16-cycle fraction" + ], + "median_shift": "sum of two learned tanh gates times template differences", + "same_shift_all_quantiles": true, + "maximum_context": 4096, + "parameters_fixed_at_inference": true + }, + "confidence_features": { + "query_projection_parameters": 3072, + "backbone_frozen_during_projection_training": true, + "training_objective": "weighted quantile and median loss after averaging both sign orientations", + "statistics": [ + "mean absolute difference", + "root mean square difference" + ], + "lags": "one and the two frequency-derived periods", + "lookback": "512 for lag one; eight cycles for seasonal lags", + "minimum_valid_pairs": 8, + "insufficient_pair_defaults": [ + 1, + 1.4142135623730951 + ], + "statistic_clip": 10, + "transform": "log1p", + "stage_scope": "Frozen-backbone details refer to projection introduction; subsequent updates are recorded in training_lineage.training_settings." + }, + "partial_target_training": { + "available_horizon": "last finite training-label position rounded up to the patch boundary", + "decoder_future_key_mask": true, + "per_row_horizon_metadata": true, + "inference_uses_requested_horizon_only": true + }, + "training_provenance_code_sha256": { + "confidence_query/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "confidence_query/model.py": "b4f11ba2018e2b50879cdc33acf0138301548971508b58035a7c96a29aaa6f2d", + "confidence_query/train.py": "fc8a7555a5a6b0a6f91e80ac8cc9cbbfddaa2b26468c57f49dfb17671b22ce93", + "direct_large/data.py": "6e6db217936f8dd79380d2ceff3eaa8598a44f1b60b17acae7bfde2363116847", + "direct_large/evaluate.py": "eaea99e8cd44c9f7c70a45fa9abf51354ae5449dbad273fcb55e48ad02652223", + "direct_large/model.py": "146d93a3f95b13bda8b1b437bc36621b91356cf946e94f62999f89e7fb348071", + "direct_large/pack.py": "3bcc4ce9eb3361ad741ceebd7efce7a2fb86fb49543f52c72aabd0e3e8cd17ce", + "direct_large/predict.py": "930a9f18f9f5da47c03859698c9d2f5567d1e1c73fd61edac1ed20b3a6f9bb50", + "direct_large/publish.py": "3c167f33e8571731c26f1cb70168eda54ef9cb4c76423dfd374240b75ca5f106", + "direct_large/record.py": "b3b00b0ed14bc3af00c7b1ad97195238ecb8f06e96bc41f0c07913bc3f6ed949", + "direct_large/train.py": "b9ad6b2adddeaf12961b529d6535dd33f6d044a31979b5c9e49dceafbadd3ac0", + "direct_large/ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "direct_large/validation_subset.py": "8d3eb9d3f3aa124368761ef402ff066935c0be31a62b25b8551a45dcb922e28d", + "full_paired/check.py": "90ac1c78846439d51ab8acd62a19bd536c7c394bd02e94f6d5ff17c0af8bd116", + "full_paired/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "full_paired/model.py": "c27748fa4b1186b513f76eca26052753b8dcd1794994e5989addaf371ca70f2e", + "horizon_jitter/data.py": "5044cf648323420095ed6058d29f837c07ff5559b606df8b00cc8d1e95c8b58e", + "horizon_jitter/model.py": "186bb282236f23cc665a012194d26e58f51004c680393352ec053f5308f1240f", + "horizon_jitter/train.py": "4e9cbca1293f18f7eea2c72dba127815c0934a13c86e8f6cc881a749676d41a6", + "large_corpus/data.py": "27c078cb0ed085717a364f556b5ff976fd803d5af37612cf3a03a0a3ca12a678", + "large_corpus/model.py": "e3a1bc01e89a0d6d750ede2cc969272ad01e1ca580b174af7dee00db029f1cf7", + "large_corpus/train.py": "3baca16c3945e6ef241ccbc9c13644539e3c265f71095cbbaa61a3d338e4fafe", + "large_sign/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "large_sign/evaluate.py": "eaea99e8cd44c9f7c70a45fa9abf51354ae5449dbad273fcb55e48ad02652223", + "large_sign/model.py": "3fff6445a1982a1b3c92f06a9b5f1bb627dda6a291b0b2364bcfb1a6457830d7", + "large_sign/pack.py": "3bcc4ce9eb3361ad741ceebd7efce7a2fb86fb49543f52c72aabd0e3e8cd17ce", + "large_sign/predict.py": "930a9f18f9f5da47c03859698c9d2f5567d1e1c73fd61edac1ed20b3a6f9bb50", + "large_sign/publish.py": "3c167f33e8571731c26f1cb70168eda54ef9cb4c76423dfd374240b75ca5f106", + "large_sign/record.py": "b3b00b0ed14bc3af00c7b1ad97195238ecb8f06e96bc41f0c07913bc3f6ed949", + "large_sign/train.py": "a597f40ab87cce04e96dc654d12e56cdf40ffd87f00034d8bc4d56dff4eb7c68", + "large_sign/ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "large_sign/validation_subset.py": "8d3eb9d3f3aa124368761ef402ff066935c0be31a62b25b8551a45dcb922e28d", + "long_memory_synth/data.py": "2955ec414de97f7ec91c8863873b7ae50ebe8f0ccb7fe48c41599e69da88ec34", + "long_memory_synth/model.py": "186bb282236f23cc665a012194d26e58f51004c680393352ec053f5308f1240f", + "long_memory_synth/train.py": "75918ac02d30ad8289632bc8a3ce1386c949fd670522799af59536d4cab0b9e9", + "long_seasonal/check.py": "e55fe780892204889e210d1591ae3f0b964d72ec1916b9b5e768b938aba28fc1", + "long_seasonal/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "long_seasonal/launch.py": "68c56b8abde125eb8de866807f8deb946c30e4c52866bc0cafcab82198b58def", + "long_seasonal/long_features.py": "270d84ff1208085f65856e8c489998e6248af5c5ea1c3c47b5161f7d6b621b13", + "long_seasonal/model.py": "3eaa4aed0a1c62b80d94be6c3084b10a594e9fce17444eac17ca3f1b0b5c549e", + "long_seasonal/transfer.py": "301df5a793988edbe50b3384c5777d8679161142943578bc7723a552ed4f3d04", + "overflow_control/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "overflow_control/model.py": "44eeb23c037e91b8f67e432615ce46540a7ac4242919785f9c4218de23121499", + "partial_delta/merge.py": "63984a0f46f7d48817037f5bf5a1c9319e45a9b1924cde62c667ac49ce47532e", + "partial_targets/data.py": "27c078cb0ed085717a364f556b5ff976fd803d5af37612cf3a03a0a3ca12a678", + "partial_targets/model.py": "186bb282236f23cc665a012194d26e58f51004c680393352ec053f5308f1240f", + "partial_targets/train.py": "3baca16c3945e6ef241ccbc9c13644539e3c265f71095cbbaa61a3d338e4fafe", + "patch16/convert.py": "11e1d30100ab25311020ac1f4ab8227ec66156836df5de613300867977091c45", + "patch16/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "patch16/evaluate.py": "eaea99e8cd44c9f7c70a45fa9abf51354ae5449dbad273fcb55e48ad02652223", + "patch16/model.py": "8031c597b354eb2cf464140bee40c3ec8dff86c775b5c55c5ce910302b443582", + "patch16/pack.py": "3bcc4ce9eb3361ad741ceebd7efce7a2fb86fb49543f52c72aabd0e3e8cd17ce", + "patch16/predict.py": "930a9f18f9f5da47c03859698c9d2f5567d1e1c73fd61edac1ed20b3a6f9bb50", + "patch16/publish.py": "3c167f33e8571731c26f1cb70168eda54ef9cb4c76423dfd374240b75ca5f106", + "patch16/record.py": "b3b00b0ed14bc3af00c7b1ad97195238ecb8f06e96bc41f0c07913bc3f6ed949", + "patch16/train.py": "3156710f76111a31447cbe638ee27fe2811d060917aa083aab0b5134d98accf8", + "patch16/ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "patch16/validation_subset.py": "8d3eb9d3f3aa124368761ef402ff066935c0be31a62b25b8551a45dcb922e28d", + "postloss/check_numerical_fix.py": "527dffcd94ec1a02b214dd300261d189b06c386f0b8c4d4df3320098f5fc0e68", + "postloss/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "postloss/diagnose_nonfinite.py": "82d10c5751ea1d21ecd36cd5eb54c00aabcaf78a8562b259551d028d452be47b", + "postloss/gpu_check.py": "c0a7e23d9f74cdab4fa04e1a4b9f89c64bb58f5e24228aa5e0f2cf554fef2d1f", + "postloss/launch_completion.py": "ef584b22259e3bc741b16ef876a6120bfcee08e2b9237a7990ed560a0dbf77ae", + "postloss/model.py": "d4b76fb1a63789e091b114dd947abe30be3e47c2e2e9d41cecb3e3353af86ac5", + "postloss/model_before_numerical_fix.py": "1ad846ac7adc16298b9643a79f4ee1b94f4db82fa716c6db77a2fcbb2160c261", + "postloss/restart.py": "5baa9a0947a0d30f7773113c05bd1f53b8ed1817aeaa2365078b06df9ce2fbca", + "postloss/torch_post.py": "0762fc5d330a4039798a81788e4adb8bfe206aba2aa29a1b53ecad0bd3bff217", + "recency_features/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "recency_features/model.py": "e3a1bc01e89a0d6d750ede2cc969272ad01e1ca580b174af7dee00db029f1cf7", + "recency_features/train.py": "a654b9a27b6c27141e1d4e517ab28fcae3f2c23d061742fa2f6c01e3d23c8a00", + "recovery/brief.py": "14826a63bbdf9eeebc8e784cbbe9bc2670e5ea74daf008a17a8578dee95453fb", + "recovery/capacity_curves.py": "2bdc6635705b70a868e115cd13eb529563acacf6f47c71f250a50dce8e943be4", + "recovery/exposure_audit.py": "54c194a626b8876ece84686b39b22360155c9fada7248a393ca9b7d6ee38002b", + "recovery/launch_matched_cutoffs.py": "7d5b9b569df284c143bb4fe50033ed6be21ff1b54cb4405723b2ebcdefe6e562", + "recovery/matched_report.py": "82696104e2e7da9cee48611e42aebc0f5c4916f2273fdeb9a3158c4dd3700b04", + "recovery/median_error_structure.py": "f6e126496eba2e0aa1fce1efeac7e926f0fbc28005ab81c0f1c9cf73ecd93782", + "recovery/pack_composition.py": "66c198e44b55fc4dce50dec505a0127eb9d97390e04d0f97c271ace11ad0f49f", + "recovery/quantile_coverage.py": "7a4057d1aa38c5e7de0ca601db0003a8fd3a9a2e6123b2fdb81fa8aedbc34787", + "recovery/reclaim_completed_cache.py": "d0a23e5a73b362f03a3be0d9fcc8dd5292d17da0489484a9c52af84bd05d9638", + "recovery/refresh_journal.py": "6ccbbbf7494f3b310f2e4d47e572487b62494ae52ef6598de93ce8ae28c8a7a5", + "recovery/relaunch_20261022b.py": "f90ddd77928a793c8e151ba74cfa9cc84c8aefad0c0d943a833c74bc07b79313", + "recovery/relaunch_20261023.py": "a4c40c5674b0d05cfe9bb1fffe907f02dec16c53cbddb8b86efbba1b96649097", + "recovery/schedules.py": "7748fd6b2bbbe64037472faf7e6583d03cf339138d2f3c07b1bac9e65bf2d4f5", + "recovery/seasonal_history_support.py": "fe2da1a695715c3add9472f0bfebc946783b179b1a8415f85565a937885f7076", + "recovery/snapshot.py": "2bca59056f90a58dc18ee9d9f3f9d6b74a62d04c8eea5a1e0ae5a745ba942bbf", + "recovery/synthetic_window_audit.py": "912e38fd094f35fb528a77388d8076600207b369bb3b2c2133a24c3c485019a1", + "recovery/train.py": "76946cbda4b20c1d9922914955ccd221f2ccc574a0d452012431cf2c6a66f38f", + "recovery/watch_matched_cutoffs.py": "177dbe6d8b5186dd3ce1c4b261a55cd5cfb44f6ed2922ef64b489deb2117fa6b", + "seasonal_dispersion/check.py": "aec0a137044f8da807fa7f4212f196dd99c7d823f0c93d526592f3659481721f", + "seasonal_dispersion/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "seasonal_dispersion/durability.py": "5e249e02a5a2b0b61f3c78693f273b851d98db3e964e004dcd19c920679c6a1f", + "seasonal_dispersion/launch.py": "5befe970b37e12829e8cc97f201568c95a2d06311a2730e6599b4372cc9a55b1", + "seasonal_dispersion/model.py": "35d591ca15c0875d6562a45618fd7483796eaec8d4c8306408e716c72693c4b3", + "seasonal_width/check.py": "6fd58bfeca5cb16aa70bfa66a93ec0ede4d43d554e976368c143afe986377c1e", + "seasonal_width/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "seasonal_width/launch.py": "7473cd5ee8b9094439a7375c58f4069ece047e0c7c9c77064856355fc09be9b3", + "seasonal_width/model.py": "0d9557eca352e3c493f47c310355aa576da2e75c8f7cb5b69786c3d162644f38", + "seasonal_width_transfer/assemble.py": "7313ef4be82840bb0e89b989375a348e633ac24f5a63fb1e15e9730492acd2eb", + "seasonal_width_transfer/check_runtime.py": "1a5e7113c3ab3452dce6eee5f26d9283e48da825c15e2c595be43756bde0b443", + "seasonal_width_transfer/merge.py": "a67ab547f82b3f86935c47ef82c6f196e3cd80af3b3860247125dc742076cdd3", + "seasonal_width_transfer/promote.py": "73bb7adf33bf2553503e71565604c198762519c64d1199730cf240946edd3d50", + "seasonal_width_transfer/run.py": "0bb371e4e7585fd36d2afc499412d1cf166194395c56519d230ba7d2d1298ee3", + "seasonal_width_transfer/validate.py": "6d13c787616e012d47888c9821779e00c0b8c2aa554b4e4e98a04f3dbeb95dd9", + "spectral_synth/check.py": "c308c87af0a6756fafefa460751cc370ed44ee98f3f52364b1ed6879a3c4e110", + "spectral_synth/data.py": "1780475ef9573c9731cf67f46c1a339ab2fa466c28bbbee5948322ae3f33ca29", + "spectral_synth/launch.py": "5888c115ae4b38b307ac1ac1bb4a9c200a1aa35850819dab55eaeb47946c38e2", + "spectral_synth/model.py": "44eeb23c037e91b8f67e432615ce46540a7ac4242919785f9c4218de23121499", + "spectral_synth/spectral.py": "347aa6d352df72ff18ef35a267b8e0479546263b26174d5256d4e9903cce5f71", + "spectral_transfer/run.py": "33fb544faca0633cd96440e2e4fa3c0e38c8e8cde8a215bfaf8357ed224bfcd8", + "weekly_synth/check.py": "a122b553d9ddc01a506a36713a0df478b03d7fe0b3f9ee1fa34c22c3e982adbf", + "weekly_synth/data.py": "774d0d5216fa263db9d809289dd3daa877f0bcea6ed44a628dd9f8e53829815f", + "weekly_synth/launch.py": "b28347982ecf6d87b45970824d0961027297296e8a6d4372414caeae28427e9d", + "weekly_synth/model.py": "44eeb23c037e91b8f67e432615ce46540a7ac4242919785f9c4218de23121499" + } +} diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/confidence_query/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/confidence_query/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/confidence_query/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/confidence_query/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/confidence_query/model.py new file mode 100644 index 0000000000000000000000000000000000000000..b881039b3752b3396e06415a8d01d24956fa29a7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/confidence_query/model.py @@ -0,0 +1,190 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + if self.recency is not None: + pos=torch.arange(c,device=z.device)[None,:];extras=[] + for j in range(2): + period=periods[:,j:j+1] + recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + n=ctx.shape[0] + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1]) + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/confidence_query/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/confidence_query/train.py new file mode 100644 index 0000000000000000000000000000000000000000..fd9d2a3a0502cee1a67c41c832266c7f87cc5a80 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/confidence_query/train.py @@ -0,0 +1,54 @@ +"""Train only confidence-query features on a frozen model, using paired-sign forecast loss.""" +import argparse,json,math,time,os +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) +ap.add_argument('--initialize-from',required=True);ap.add_argument('--steps',type=int,default=6000) +ap.add_argument('--batch',type=int,default=128);ap.add_argument('--lr',type=float,default=2e-4) +ap.add_argument('--seed',type=int,default=89);ap.add_argument('--save-every',type=int,default=1000);a=ap.parse_args() +torch.set_num_threads(1);torch.manual_seed(a.seed);torch.backends.cuda.matmul.allow_tf32=True +out=Path(a.out);out.mkdir(parents=True,exist_ok=True) +ck=torch.load(a.initialize_from,map_location='cpu',weights_only=False) +config={**ck['config'],'confidence_features':True};model=DirectForecaster(**config).cuda() +missing,unexpected=model.load_state_dict(ck['model'],strict=False) +assert not unexpected and all(k.startswith('confidence.') for k in missing) +for name,param in model.named_parameters():param.requires_grad_(name.startswith('confidence.')) +params=[p for p in model.parameters() if p.requires_grad] +opt=torch.optim.AdamW(params,lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) +ema={k:v.detach().clone() for k,v in model.state_dict().items()};sampler=Sampler(a.packed,seed=a.seed) +(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)) +rng=np.random.default_rng(a.seed) +def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) +def save(step): + for prefix,weights in [('step',model.state_dict()),('ema',ema)]: + state={'model':weights,'config':model.config,'step':step,'args':vars(a),'ema':prefix=='ema'} + path=out/f'{prefix}{step:06d}.pt';torch.save(state,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) +save(0);pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] +for step in range(1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch);x,y,p=[torch.from_numpy(x).cuda() for x in arrays] + lr=a.lr*min(1,step/200)*(.2+.8*.5*(1+math.cos(math.pi*step/a.steps))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(params,1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items(): + if k.startswith('confidence.'):ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + if step%a.save_every==0 or step==a.steps:save(step) +pool.shutdown() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/direct_large/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/direct_large/data.py new file mode 100644 index 0000000000000000000000000000000000000000..2378e33d7352ba5ad97d566148782e63e64b367c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/direct_large/data.py @@ -0,0 +1,71 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + return ctx,tgt,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/direct_large/evaluate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/direct_large/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..05f086d4d84def4a48165f9e65d2948877675e56 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/direct_large/evaluate.py @@ -0,0 +1,16 @@ +import sys,json,argparse,time,hashlib +from pathlib import Path +import torch +from predict import load_model,run +sys.path.insert(0,'/workspace/evaluation') +from score import score,json_safe + +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);ap.add_argument('--valid',default='/workspace/research/valid_screen');ap.add_argument('--baseline',default='/workspace/research/valid_screen/baseline.json');a=ap.parse_args() +torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cuda.matmul.allow_tf32=False +t0=time.time();out=Path(a.out);v=Path(a.valid) +run(load_model(a.weights),v/'input',out) +base=json.loads(Path(a.baseline).read_text())['configs'] +rep=score(v/'truth',out,base) +rep['checkpoint_sha256']=hashlib.sha256(Path(a.weights).read_bytes()).hexdigest();rep['eval_seconds']=time.time()-t0 +(out/'report.json').write_text(json.dumps(json_safe(rep),indent=1)) +print(json.dumps({k:rep[k] for k in ('skill_score','rel_mase_gmean','rel_wql_gmean','n_failed','groups','eval_seconds')},indent=1)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/direct_large/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/direct_large/model.py new file mode 100644 index 0000000000000000000000000000000000000000..7a224cc12a159446a1e427b2052b53d1d1f7e83e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/direct_large/model.py @@ -0,0 +1,142 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional(torch.arange(-nt,0,device=z.device),self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + q=self.query(base.reshape(b,h//p,p*9))+positional(torch.arange(h//p,device=z.device),self.d)[None]+emb + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + pin=torch.maximum(levels*err,(levels-1)*err).mean(-1) + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + return per.mean() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/direct_large/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/direct_large/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/direct_large/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/direct_large/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/direct_large/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..e20c6630475d6b4fa6906eb4ed9454b7b5aeec2c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/direct_large/predict.py @@ -0,0 +1,43 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):q=model.predict(x,p,h).float().cpu().numpy() + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/direct_large/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/direct_large/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf95c9aec5936076b881c340edb960786f2d40d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/direct_large/publish.py @@ -0,0 +1,31 @@ +"""Assemble a relocatable package, then atomically exchange complete directories.""" +import json,os,shutil,ctypes,hashlib,argparse +from pathlib import Path +import torch +HERE=Path(__file__).resolve().parent + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',default='/workspace/submission');ap.add_argument('--report',required=True);ap.add_argument('--experiments',default=str(HERE/'EXPERIMENTS.md'));a=ap.parse_args() + final=Path(a.out);staging=final.parent/f'.{final.name}-staging-{os.getpid()}' + shutil.rmtree(staging,ignore_errors=True);staging.mkdir(parents=True) + for file in ('model.py','predict.py','infer.sh','ts_io.py'): + shutil.copy(HERE/file,staging/file) + shutil.copy(a.weights,staging/'weights.pt');shutil.copy('/opt/runtime/requirements.txt',staging/'requirements.txt') + ck=torch.load(a.weights,map_location='cpu',weights_only=False);digest=hashlib.sha256((staging/'weights.pt').read_bytes()).hexdigest() + sources=json.loads(Path('/workspace/research/packed_sample/meta.json').read_text())['dirs'] + manifest={'name':'direct-seasonal-quantile-v1','contract':'timeseries-forecast/v1','parameters':sum(x.numel() for x in ck['model'].values()),'pretrained_assets':[],'sources_used':[f'gifteval_pretrain/{d}' for d in sources]+['synthetic:direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; data.py generator seed 17'],'weights_sha256':digest,'training_step':ck['step'],'config':ck['config'],'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.'} + (staging/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') + (staging/'config.json').write_text(json.dumps(ck['config'],indent=2)+'\n') + shutil.copy(a.experiments,staging/'EXPERIMENTS.md');shutil.copy(a.report,staging/'validation_report.json') + # Include generator/sampler provenance, which is not imported by inference. + (staging/'provenance').mkdir() + for file in ('pack.py','data.py','train.py'):shutil.copy(HERE/file,staging/'provenance'/file) + (staging/'README.md').write_text('# Direct seasonal quantile foundation forecaster\n\nRun `bash infer.sh INPUT_DIR OUTPUT_DIR`. This package contains all inference assets and uses only its supplied input directory. The 6.76M 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.\n\nThe 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.\n') + if final.exists(): + libc=ctypes.CDLL(None,use_errno=True) + if libc.renameat2(-100,os.fsencode(staging),-100,os.fsencode(final),2):raise OSError(ctypes.get_errno(),os.strerror(ctypes.get_errno())) + shutil.rmtree(staging) + else:os.replace(staging,final) + print(json.dumps(manifest,indent=1)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/direct_large/record.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/direct_large/record.py new file mode 100644 index 0000000000000000000000000000000000000000..1850a33f46fa3ee4d78cac4a5d6152404801a131 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/direct_large/record.py @@ -0,0 +1,9 @@ +import argparse,json,math +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('report');ap.add_argument('--label',required=True);ap.add_argument('--outcome',default='Screened for model selection.');a=ap.parse_args() +r=json.loads(Path(a.report).read_text());p=Path(__file__).with_name('EXPERIMENTS.md') +lines=[f'\n## {a.label}',f'- Checkpoint SHA-256: `{r.get("checkpoint_sha256","see model_manifest.json")}`.',f'- Evaluation: {r["n_configs"]} configurations, {r["n_instances"]} instances, {r["n_failed"]} failed configurations; {r.get("eval_seconds","not separately timed")} seconds.',f'- Overall skill {r["skill_score"]:.6f}; relative MASE {r["rel_mase_gmean"]:.6f}; relative WQL {r["rel_wql_gmean"]:.6f}.'] +for group,entries in r['groups'].items(): + lines.append(f'- {group} skill: '+', '.join(f'{k}={1-math.sqrt(v["rel_mase_gmean"]*v["rel_wql_gmean"]):.4f}' for k,v in entries.items())+'.') +lines.append('- Outcome: '+a.outcome) +with p.open('a') as f:f.write('\n'.join(lines)+'\n') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/direct_large/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/direct_large/train.py new file mode 100644 index 0000000000000000000000000000000000000000..a2ccc736bfef804259199a2dd315347d9854b680 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/direct_large/train.py @@ -0,0 +1,67 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(6);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/direct_large/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/direct_large/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/direct_large/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/direct_large/validation_subset.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/direct_large/validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..4df83e69c4f9a3365955e5d17ffcfc0af71372b7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/direct_large/validation_subset.py @@ -0,0 +1,18 @@ +"""Model-selection-only subset spanning all 97 configurations, seed 2026.""" +import sys,json,copy +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +import ts_io + +root=Path('/workspace/data/valid');out=Path('/workspace/research/valid_screen') +idx=json.loads((root/'input/index.json').read_text());new=copy.deepcopy(idx);rng=np.random.default_rng(2026) +for cfg in new['configs']: + cid=cfg['config_id'];case=ts_io.CaseFile(root/'input/cases'/f'{cid}.h5') + ids=np.sort(rng.choice(case.n,min(case.n,192),replace=False)) + ts_io.write_case_subset(case,ids,out/'input/cases'/f'{cid}.h5') + lab,se,meta=ts_io.read_truth_file(root/'truth/cases'/f'{cid}.h5') + ts_io.write_truth_file(out/'truth/cases'/f'{cid}.h5',lab[ids],se[ids],meta) + cfg['n_instances']=len(ids);case.close() +for kind in ('input','truth'):(out/kind/'index.json').write_text(json.dumps(new,indent=1)) +print('screen instances',sum(c['n_instances'] for c in new['configs'])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/full_paired/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/full_paired/check.py new file mode 100644 index 0000000000000000000000000000000000000000..fda928e16338305fd9912f7bc08cacff58bd8aa4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/full_paired/check.py @@ -0,0 +1,34 @@ +import importlib.util,json,time +from pathlib import Path +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +r=Path('/workspace/research');torch.set_num_threads(1);torch.manual_seed(197);start=time.monotonic() +ck=torch.load(r/'horizon_delta12k.pt',map_location='cpu',weights_only=False) +spec=importlib.util.spec_from_file_location('parent_model',r/'confidence_inference/model.py') +old=importlib.util.module_from_spec(spec);spec.loader.exec_module(old) +parent=old.DirectForecaster(**ck['config']);parent.load_state_dict(ck['model']) +m=DirectForecaster(**ck['config']);m.load_state_dict(ck['model']) +x=torch.randn(4,512);x[0,:50]=float('nan');p=torch.tensor([[24,168]]*4);y=torch.randn(4,128);y[0,32:]=float('nan') +with torch.inference_mode(): + assert all(torch.equal(a,b) for a,b in zip(m(x,p,48),parent(x,p,48))) + short=m(x,p,32)[0];long=m(x,p,128,forecast_lengths=torch.full((4,),32))[0][:,:32] + assert torch.allclose(short,long,atol=3e-6,rtol=1e-6),(short-long).abs().max() + paired=float(loss_fn(m,x,y,p,paired=True));reverse=float(loss_fn(m,-x,-y,p,paired=True)) + assert abs(paired-reverse)<1e-7,(paired,reverse) +a=Sampler(r/'packed_sample',197);b=Sampler(r/'packed_sample',197) +for c,h in [(512,32),(4096,1024)]: + assert all(np.array_equal(v,w,equal_nan=True) for v,w in zip(a.sample(16,c,h),b.sample(16,c,h))) +assert a.rng.bit_generator.state==b.rng.bit_generator.state and a.horizon_rng.bit_generator.state==b.horizon_rng.bit_generator.state +cpu=time.monotonic()-start;del parent,ck,a,b +m=m.cuda();ema={k:v.detach().clone() for k,v in m.state_dict().items()} +moments=[torch.zeros_like(v) for v in m.parameters() for _ in range(2)] +torch.backends.cuda.matmul.allow_tf32=True;torch.cuda.reset_peak_memory_stats();start=time.monotonic() +x=torch.randn(64,4096,device='cuda');y=torch.randn(64,1024,device='cuda');p=torch.tensor([[24,168]]*64,device='cuda') +with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(m,x,y,p,paired=True) +loss.backward();torch.cuda.synchronize() +assert torch.isfinite(loss) and all(v.grad is not None and torch.isfinite(v.grad).all() for v in m.parameters()) +z={'cpu_seconds':cpu,'initial_forecast_bitwise_parent':True,'unused_future_tokens_do_not_change_requested_prefix':True,'paired_loss_sign_symmetric':True,'matched_sampler_main_and_horizon_rng':True,'gpu_fixture_seconds':time.monotonic()-start,'allocated_mib':torch.cuda.max_memory_allocated()/2**20,'reserved_mib':torch.cuda.max_memory_reserved()/2**20,'optimizer_updates':0} +(r/'full_paired_checks.json').write_text(json.dumps(z,indent=2));print(json.dumps(z),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/full_paired/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/full_paired/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/full_paired/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/full_paired/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/full_paired/model.py new file mode 100644 index 0000000000000000000000000000000000000000..dedcdff4698028a8ba655865f8425d0dc3ef0dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/full_paired/model.py @@ -0,0 +1,204 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/horizon_jitter/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/horizon_jitter/data.py new file mode 100644 index 0000000000000000000000000000000000000000..3d632af7e96a71f30b7964a2b3fd73bc1c3f3f3e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/horizon_jitter/data.py @@ -0,0 +1,86 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/horizon_jitter/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/horizon_jitter/model.py new file mode 100644 index 0000000000000000000000000000000000000000..4ffe50d9aadf21d73949e2052ceb7f3642bf65d3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/horizon_jitter/model.py @@ -0,0 +1,180 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(ctx,periods,target.shape[-1],forecast_lengths=lengths) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/horizon_jitter/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/horizon_jitter/train.py new file mode 100644 index 0000000000000000000000000000000000000000..768d33da4421b24bd760d7d9680d0c2cd9bd84e4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/horizon_jitter/train.py @@ -0,0 +1,74 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler,truncate_targets + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + horizon_rng=np.random.default_rng(a.seed+startstep+300003) + def nextbatch(): + 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])) + return truncate_targets(sampler.sample(a.batch,c,h),horizon_rng,a.patch) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_corpus/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_corpus/data.py new file mode 100644 index 0000000000000000000000000000000000000000..a51e912d3c4b63a3ec0cd85133bf0e7aa3429569 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_corpus/data.py @@ -0,0 +1,73 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_corpus/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_corpus/model.py new file mode 100644 index 0000000000000000000000000000000000000000..f8271c5b0bf9a5edb961e1c7839761fe50a2e40b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_corpus/model.py @@ -0,0 +1,171 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024,recency_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + if self.recency is not None: + pos=torch.arange(c,device=z.device)[None,:];extras=[] + for j in range(2): + period=periods[:,j:j+1] + recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_corpus/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_corpus/train.py new file mode 100644 index 0000000000000000000000000000000000000000..2e77612e443d78dd80bcb6a0cc6d01169f61a3a4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_corpus/train.py @@ -0,0 +1,73 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_sign/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_sign/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_sign/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_sign/evaluate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_sign/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..05f086d4d84def4a48165f9e65d2948877675e56 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_sign/evaluate.py @@ -0,0 +1,16 @@ +import sys,json,argparse,time,hashlib +from pathlib import Path +import torch +from predict import load_model,run +sys.path.insert(0,'/workspace/evaluation') +from score import score,json_safe + +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);ap.add_argument('--valid',default='/workspace/research/valid_screen');ap.add_argument('--baseline',default='/workspace/research/valid_screen/baseline.json');a=ap.parse_args() +torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cuda.matmul.allow_tf32=False +t0=time.time();out=Path(a.out);v=Path(a.valid) +run(load_model(a.weights),v/'input',out) +base=json.loads(Path(a.baseline).read_text())['configs'] +rep=score(v/'truth',out,base) +rep['checkpoint_sha256']=hashlib.sha256(Path(a.weights).read_bytes()).hexdigest();rep['eval_seconds']=time.time()-t0 +(out/'report.json').write_text(json.dumps(json_safe(rep),indent=1)) +print(json.dumps({k:rep[k] for k in ('skill_score','rel_mase_gmean','rel_wql_gmean','n_failed','groups','eval_seconds')},indent=1)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_sign/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_sign/model.py new file mode 100644 index 0000000000000000000000000000000000000000..60aeb14b5f4fa298521ddce8a3276d076c1bb631 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_sign/model.py @@ -0,0 +1,154 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional(torch.arange(-nt,0,device=z.device),self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + q=self.query(base.reshape(b,h//p,p*9))+positional(torch.arange(h//p,device=z.device),self.d)[None]+emb + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_sign/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_sign/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_sign/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_sign/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_sign/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..e20c6630475d6b4fa6906eb4ed9454b7b5aeec2c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_sign/predict.py @@ -0,0 +1,43 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):q=model.predict(x,p,h).float().cpu().numpy() + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_sign/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_sign/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf95c9aec5936076b881c340edb960786f2d40d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_sign/publish.py @@ -0,0 +1,31 @@ +"""Assemble a relocatable package, then atomically exchange complete directories.""" +import json,os,shutil,ctypes,hashlib,argparse +from pathlib import Path +import torch +HERE=Path(__file__).resolve().parent + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',default='/workspace/submission');ap.add_argument('--report',required=True);ap.add_argument('--experiments',default=str(HERE/'EXPERIMENTS.md'));a=ap.parse_args() + final=Path(a.out);staging=final.parent/f'.{final.name}-staging-{os.getpid()}' + shutil.rmtree(staging,ignore_errors=True);staging.mkdir(parents=True) + for file in ('model.py','predict.py','infer.sh','ts_io.py'): + shutil.copy(HERE/file,staging/file) + shutil.copy(a.weights,staging/'weights.pt');shutil.copy('/opt/runtime/requirements.txt',staging/'requirements.txt') + ck=torch.load(a.weights,map_location='cpu',weights_only=False);digest=hashlib.sha256((staging/'weights.pt').read_bytes()).hexdigest() + sources=json.loads(Path('/workspace/research/packed_sample/meta.json').read_text())['dirs'] + manifest={'name':'direct-seasonal-quantile-v1','contract':'timeseries-forecast/v1','parameters':sum(x.numel() for x in ck['model'].values()),'pretrained_assets':[],'sources_used':[f'gifteval_pretrain/{d}' for d in sources]+['synthetic:direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; data.py generator seed 17'],'weights_sha256':digest,'training_step':ck['step'],'config':ck['config'],'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.'} + (staging/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') + (staging/'config.json').write_text(json.dumps(ck['config'],indent=2)+'\n') + shutil.copy(a.experiments,staging/'EXPERIMENTS.md');shutil.copy(a.report,staging/'validation_report.json') + # Include generator/sampler provenance, which is not imported by inference. + (staging/'provenance').mkdir() + for file in ('pack.py','data.py','train.py'):shutil.copy(HERE/file,staging/'provenance'/file) + (staging/'README.md').write_text('# Direct seasonal quantile foundation forecaster\n\nRun `bash infer.sh INPUT_DIR OUTPUT_DIR`. This package contains all inference assets and uses only its supplied input directory. The 6.76M 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.\n\nThe 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.\n') + if final.exists(): + libc=ctypes.CDLL(None,use_errno=True) + if libc.renameat2(-100,os.fsencode(staging),-100,os.fsencode(final),2):raise OSError(ctypes.get_errno(),os.strerror(ctypes.get_errno())) + shutil.rmtree(staging) + else:os.replace(staging,final) + print(json.dumps(manifest,indent=1)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_sign/record.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_sign/record.py new file mode 100644 index 0000000000000000000000000000000000000000..1850a33f46fa3ee4d78cac4a5d6152404801a131 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_sign/record.py @@ -0,0 +1,9 @@ +import argparse,json,math +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('report');ap.add_argument('--label',required=True);ap.add_argument('--outcome',default='Screened for model selection.');a=ap.parse_args() +r=json.loads(Path(a.report).read_text());p=Path(__file__).with_name('EXPERIMENTS.md') +lines=[f'\n## {a.label}',f'- Checkpoint SHA-256: `{r.get("checkpoint_sha256","see model_manifest.json")}`.',f'- Evaluation: {r["n_configs"]} configurations, {r["n_instances"]} instances, {r["n_failed"]} failed configurations; {r.get("eval_seconds","not separately timed")} seconds.',f'- Overall skill {r["skill_score"]:.6f}; relative MASE {r["rel_mase_gmean"]:.6f}; relative WQL {r["rel_wql_gmean"]:.6f}.'] +for group,entries in r['groups'].items(): + lines.append(f'- {group} skill: '+', '.join(f'{k}={1-math.sqrt(v["rel_mase_gmean"]*v["rel_wql_gmean"]):.4f}' for k,v in entries.items())+'.') +lines.append('- Outcome: '+a.outcome) +with p.open('a') as f:f.write('\n'.join(lines)+'\n') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_sign/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_sign/train.py new file mode 100644 index 0000000000000000000000000000000000000000..d089166fb1612ddf4955fcd2f096cb0b33624dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_sign/train.py @@ -0,0 +1,70 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(3);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_sign/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_sign/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_sign/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_sign/validation_subset.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_sign/validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..4df83e69c4f9a3365955e5d17ffcfc0af71372b7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/large_sign/validation_subset.py @@ -0,0 +1,18 @@ +"""Model-selection-only subset spanning all 97 configurations, seed 2026.""" +import sys,json,copy +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +import ts_io + +root=Path('/workspace/data/valid');out=Path('/workspace/research/valid_screen') +idx=json.loads((root/'input/index.json').read_text());new=copy.deepcopy(idx);rng=np.random.default_rng(2026) +for cfg in new['configs']: + cid=cfg['config_id'];case=ts_io.CaseFile(root/'input/cases'/f'{cid}.h5') + ids=np.sort(rng.choice(case.n,min(case.n,192),replace=False)) + ts_io.write_case_subset(case,ids,out/'input/cases'/f'{cid}.h5') + lab,se,meta=ts_io.read_truth_file(root/'truth/cases'/f'{cid}.h5') + ts_io.write_truth_file(out/'truth/cases'/f'{cid}.h5',lab[ids],se[ids],meta) + cfg['n_instances']=len(ids);case.close() +for kind in ('input','truth'):(out/kind/'index.json').write_text(json.dumps(new,indent=1)) +print('screen instances',sum(c['n_instances'] for c in new['configs'])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/long_memory_synth/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/long_memory_synth/data.py new file mode 100644 index 0000000000000000000000000000000000000000..95410ba700e638fc2e1375b14dece4df57c10110 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/long_memory_synth/data.py @@ -0,0 +1,73 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=np.exp(-10**(-r.uniform(0,4)));noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/long_memory_synth/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/long_memory_synth/model.py new file mode 100644 index 0000000000000000000000000000000000000000..4ffe50d9aadf21d73949e2052ceb7f3642bf65d3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/long_memory_synth/model.py @@ -0,0 +1,180 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(ctx,periods,target.shape[-1],forecast_lengths=lengths) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/long_memory_synth/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/long_memory_synth/train.py new file mode 100644 index 0000000000000000000000000000000000000000..61de733eea03837247278d9010c2ed8b955d7359 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/long_memory_synth/train.py @@ -0,0 +1,74 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + a.synthetic_ar_time_constants=[1,10000] + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/long_seasonal/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/long_seasonal/check.py new file mode 100644 index 0000000000000000000000000000000000000000..beba62576fae73576eef907b81c674e96622670d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/long_seasonal/check.py @@ -0,0 +1,145 @@ +"""Check exact initialization, fixed feature arithmetic and allowed-data gradients.""" +import argparse +import hashlib +import importlib.util +import json +import sys +import time +from pathlib import Path + +import numpy as np +import torch + +R = Path('/workspace/research') +sys.path.insert(0, str(R / 'long_seasonal')) +from model import DirectForecaster, centered_seasonal_difference, loss_fn +from data import Sampler + +ap = argparse.ArgumentParser() +ap.add_argument('--gpu', action='store_true') +a = ap.parse_args() +torch.set_num_threads(2) +torch.manual_seed(503) +started = time.monotonic() +spec = importlib.util.spec_from_file_location('long_control_model', R / 'overflow_control/model.py') +control_code = importlib.util.module_from_spec(spec) +spec.loader.exec_module(control_code) +parent_path = R / 'horizon_delta12k.pt' +parent = torch.load(parent_path, map_location='cpu', weights_only=False) +config = dict(parent['config'], long_seasonal_features=True) +candidate = DirectForecaster(**config) +missing, unexpected = candidate.load_state_dict(parent['model'], strict=False) +assert set(missing) == {'long_query.weight', 'long_head.weight', 'long_head.bias'} +assert not unexpected +assert all(torch.count_nonzero(candidate.state_dict()[key]) == 0 for key in missing) +control = control_code.DirectForecaster(**parent['config']) +control.load_state_dict(parent['model']) +assert all(torch.equal(value, candidate.state_dict()[key]) for key, value in parent['model'].items()) + +if a.gpu: + import fcntl + lock = open(R / '.evaluation.lock', 'a') + fcntl.flock(lock, fcntl.LOCK_EX) + device = 'cuda' + torch.backends.cuda.matmul.allow_tf32 = False + candidate = candidate.cuda() + control = control.cuda() + rng = np.random.default_rng(509) + x = torch.tensor(rng.normal(size=(8, 512)).astype(np.float32), device=device) + x[0, :23] = float('nan') + x[1] = 0 + p = torch.tensor([[24,168],[7,365],[12,1],[52,1],[4,1],[1,1],[96,672],[2,14]], device=device) + with torch.inference_mode(), torch.autocast('cuda', dtype=torch.bfloat16): + expected = control(x, p, 128) + actual = candidate(x, p, 128) + assert all(torch.equal(v, w) for v, w in zip(expected, actual)) + del control, expected, actual, x, p + torch.cuda.empty_cache() + torch.cuda.reset_peak_memory_stats() + sampler = Sampler(R / 'packed_sample', seed=509, source_weights_from=R / 'packed_sample') + arrays = sampler.sample(64, 4096, 1024) + tensors = [torch.from_numpy(v).cuda() for v in arrays] + placeholders = [torch.zeros_like(v) for v in candidate.parameters() for _ in range(3)] + with torch.autocast('cuda', dtype=torch.bfloat16): + loss = loss_fn(candidate, *tensors, paired=True) + loss.backward() + assert torch.isfinite(loss) + assert all(v.grad is None or torch.isfinite(v.grad).all() for v in candidate.parameters()) + gradients = {key: float(dict(candidate.named_parameters())[key].grad.norm()) for key in missing} + assert gradients['long_head.weight'] > 0 and gradients['long_query.weight'] > 0 + result = dict(seed=509, gpu_initial_function_bitwise_equal=True, + max_shape=[64,4096,1024], loss=float(loss.detach()), added_gradient_norms=gradients, + reserved_mib=torch.cuda.max_memory_reserved()/2**20, + allocated_mib=torch.cuda.max_memory_allocated()/2**20, + includes_ema_and_adam_placeholders=True, seconds=time.monotonic()-started, + optimizer_updates=0, validation_data_read=False) + (R / 'long_seasonal_gpu_checks.json').write_text(json.dumps(result, indent=2)) + print(json.dumps(result)) + raise SystemExit() + +rng = np.random.default_rng(503) +z = rng.normal(size=(4, 96)).astype(np.float32) +valid = rng.random(z.shape) > .12 +z[~valid] = 0 +periods = np.array([[4,7],[2,3],[12,1],[24,168]], dtype=np.int64) +delta, extra = centered_seasonal_difference(torch.from_numpy(z), torch.from_numpy(valid), + torch.from_numpy(periods), 23) +expected = np.zeros((4,23,2), np.float32) +support = np.zeros_like(expected) +for row in range(4): + for j in range(2): + period = int(periods[row,j]) + for t in range(23): + observations, recent = [], [] + for cycle in range(16): + end = max(0, 96-cycle*period) + start = max(0, 96-(cycle+1)*period) + index = 96-period+t%period-cycle*period + if index < 0 or not valid[row,index]: + continue + mean = z[row,start:end][valid[row,start:end]].mean(dtype=np.float64) + value = float(z[row,index])-mean + observations.append(value) + if cycle < 4: + recent.append(value) + if period>=2 and len(observations)>=8 and len(recent)>=2: + expected[row,t,j] = np.mean(observations)-np.mean(recent) + support[row,t,j] = len(observations)/16 +assert np.max(np.abs(delta.numpy()-expected)) < 1e-6 +assert np.array_equal(extra.numpy()[:,:,[1,3]], support) +# Adding a different constant to each complete cycle leaves centered templates unchanged. +z0 = torch.tensor(rng.normal(size=(1,64)).astype(np.float32)) +offsets = torch.tensor(rng.normal(size=(1,16,1)).astype(np.float32)) +z1 = (z0.view(1,16,4)+offsets).view(1,64) +p = torch.tensor([[4,4]]) +ones = torch.ones_like(z0,dtype=torch.bool) +v0 = centered_seasonal_difference(z0,ones,p,16)[0] +v1 = centered_seasonal_difference(z1,ones,p,16)[0] +assert torch.max(torch.abs(v0-v1)) < 1e-6 +for c,h in [(32,6),(96,23),(512,128)]: + ctx = torch.tensor(rng.normal(size=(4,c)).astype(np.float32)) + ctx[0,:c//3] = float('nan') + ctx[1] = 0 + ctx[2] = float('nan') + with torch.inference_mode(): + expected = control(ctx,torch.from_numpy(periods),h) + actual = candidate(ctx,torch.from_numpy(periods),h) + assert all(torch.equal(v,w) for v,w in zip(expected,actual)) +assert (R/'long_seasonal/data.py').read_bytes()==(R/'overflow_control/data.py').read_bytes() +out = R / 'long_seasonal_initial.pt' +assert not out.exists(), 'Do not overwrite an existing declared initial checkpoint' +checkpoint = dict(model=candidate.state_dict(), config=config, step=0, + args=dict(packed=str(R/'packed_sample'), seed=503), + parent_checkpoints=[str(parent_path)], + conversion=dict(method='zero-initialized sixteen-cycle centered seasonal query/head additions', + parent_sha256=hashlib.sha256(parent_path.read_bytes()).hexdigest(), + initial_function_bitwise_equal=True)) +torch.save(checkpoint,out) +result = dict(seed=503, independent_feature_arithmetic=True, centered_cycle_offset_invariance=True, + initial_function_bitwise_equal=True, inherited_weights_bitwise_equal=True, + sampler_byte_identical=True, added_parameters=sum(candidate.state_dict()[k].numel() for k in missing), + total_parameters=sum(v.numel() for v in candidate.parameters()), + checkpoint_sha256=hashlib.sha256(out.read_bytes()).hexdigest(), + seconds=time.monotonic()-started, optimizer_updates=0, validation_data_read=False) +(R/'long_seasonal_checks.json').write_text(json.dumps(result,indent=2)) +print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/long_seasonal/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/long_seasonal/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/long_seasonal/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/long_seasonal/launch.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/long_seasonal/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..d7fd732aae9def625f17a4d15dd2dbe3f4cd9317 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/long_seasonal/launch.py @@ -0,0 +1,31 @@ +"""Queue the audited learned sixteen-cycle summary after nested-volume training.""" +def main(): + import json + import os + import subprocess + from pathlib import Path + R=Path('/workspace/research') + checks=json.loads((R/'long_seasonal_checks.json').read_text()) + assert checks['initial_function_bitwise_equal'] and checks['inherited_weights_bitwise_equal'] + assert checks['independent_feature_arithmetic'] and checks['sampler_byte_identical'] + gpu=json.loads((R/'long_seasonal_gpu_checks.json').read_text()) + assert gpu['gpu_initial_function_bitwise_equal'] and gpu['reserved_mib']<10000 + env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1') + command=['python3',str(R/'recovery/train.py'),'--code-dir',str(R/'long_seasonal'), + '--packed',str(R/'packed_sample'),'--source-weights-from',str(R/'packed_sample'), + '--out',str(R/'runs/long_seasonal'),'--initialize-from',str(R/'long_seasonal_initial.pt'), + '--steps','12000','--batch','64','--lr','.00002','--seed','197','--loss-mode','paired', + '--stop-file',str(R/'long_seasonal.stop')] + with (R/'long_seasonal_queue.log').open('w') as qlog,(R/'long_seasonal_watch.log').open('w') as wlog: + queued=subprocess.Popen(['python3',str(R/'queued_train.py'),'--label','E107 learned sixteen-cycle summary seed197', + '--log',str(R/'long_seasonal_train.log'),'--receipt',str(R/'long_seasonal_queue.json'), + '--wait-pid','13470','--require-checkpoint',str(R/'runs/stratified_volume/recovery.pt'), + '--',*command],stdout=qlog,stderr=subprocess.STDOUT,env=env) + watch=subprocess.Popen(['python3',str(R/'watch_evaluate.py'),'--run',str(R/'runs/long_seasonal'), + '--evaluator',str(R/'long_seasonal_inference/evaluate.py'),'--name','long_seasonal', + '--expected-packed',str(R/'packed_sample'),'--steps','1000,3000,6000,12000'],stdout=wlog,stderr=subprocess.STDOUT,env=env) + print({'queue_pid':queued.pid,'watch_pid':watch.pid},flush=True) + result=queued.wait() + if result:watch.terminate() + watch.wait();raise SystemExit(result) +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/long_seasonal/long_features.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/long_seasonal/long_features.py new file mode 100644 index 0000000000000000000000000000000000000000..efc6e3ba327c6016d844148fcfcc29ac63863f23 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/long_seasonal/long_features.py @@ -0,0 +1,37 @@ +"""Fixed within-context phase summaries; no estimated or adapted parameters.""" +import torch +from torch.nn import functional as F + + +def centered_seasonal_difference(z, valid, periods, horizon): + b, c = z.shape + time = torch.arange(horizon, device=z.device)[None, :] + sums = F.pad((z * valid).cumsum(-1), (1, 0)) + counts = F.pad(valid.float().cumsum(-1), (1, 0)) + deltas, extras = [], [] + for j in range(2): + period = periods[:, j:j+1].clamp(min=1) + anchor = c - period + time % period + centered, masks = [], [] + for cycle in range(16): + end = (c - cycle * period).clamp(min=0, max=c) + start = (c - (cycle + 1) * period).clamp(min=0, max=c) + count = counts.gather(1, end) - counts.gather(1, start) + mean = (sums.gather(1, end) - sums.gather(1, start)) / count.clamp(min=1) + index = anchor - cycle * period + safe = index.clamp(min=0, max=c-1) + present = (index >= 0) & valid.gather(1, safe) + centered.append(z.gather(1, safe) - mean) + masks.append(present) + values = torch.stack(centered) + seen = torch.stack(masks) + n4 = seen[:4].sum(0) + n16 = seen.sum(0) + mean4 = (values[:4] * seen[:4]).sum(0) / n4.clamp(min=1) + mean16 = (values * seen).sum(0) / n16.clamp(min=1) + active = (period >= 2) & (n4 >= 2) & (n16 >= 8) + delta = torch.where(active, mean16 - mean4, 0.) + support = torch.where(active, n16.float() / 16, 0.) + deltas.append(delta) + extras.extend([delta, support]) + return torch.stack(deltas, -1), torch.stack(extras, -1) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/long_seasonal/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/long_seasonal/model.py new file mode 100644 index 0000000000000000000000000000000000000000..298ee3b840cbc8b7da585ee5e47a3822d06717b0 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/long_seasonal/model.py @@ -0,0 +1,260 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + + +def centered_seasonal_difference(z, valid, periods, horizon): + b, c = z.shape + time = torch.arange(horizon, device=z.device)[None, :] + sums = F.pad((z * valid).cumsum(-1), (1, 0)) + counts = F.pad(valid.float().cumsum(-1), (1, 0)) + deltas, extras = [], [] + for j in range(2): + period = periods[:, j:j+1].clamp(min=1) + anchor = c - period + time % period + centered, masks = [], [] + for cycle in range(16): + end = (c - cycle * period).clamp(min=0, max=c) + start = (c - (cycle + 1) * period).clamp(min=0, max=c) + count = counts.gather(1, end) - counts.gather(1, start) + mean = (sums.gather(1, end) - sums.gather(1, start)) / count.clamp(min=1) + index = anchor - cycle * period + safe = index.clamp(min=0, max=c-1) + present = (index >= 0) & valid.gather(1, safe) + centered.append(z.gather(1, safe) - mean) + masks.append(present) + values = torch.stack(centered) + seen = torch.stack(masks) + n4 = seen[:4].sum(0) + n16 = seen.sum(0) + mean4 = (values[:4] * seen[:4]).sum(0) / n4.clamp(min=1) + mean16 = (values * seen).sum(0) / n16.clamp(min=1) + active = (period >= 2) & (n4 >= 2) & (n16 >= 8) + delta = torch.where(active, mean16 - mean4, 0.) + support = torch.where(active, n16.float() / 16, 0.) + deltas.append(delta) + extras.extend([delta, support]) + return torch.stack(deltas, -1), torch.stack(extras, -1) + + + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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,long_seasonal_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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,long_seasonal_features=long_seasonal_features) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + self.long_query=nn.Linear(patch*4,d,bias=False) if long_seasonal_features else None + self.long_head=nn.Linear(d,patch*2) if long_seasonal_features else None + if long_seasonal_features: + nn.init.zeros_(self.long_query.weight) + nn.init.zeros_(self.long_head.weight);nn.init.zeros_(self.long_head.bias) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + if self.long_query is not None:long_delta,long_extra=centered_seasonal_difference(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + hidden=self.norm(q) + out=self.head(hidden).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + if self.long_head is not None: + gates=self.long_head(hidden).view(b,h,2).float().tanh() + median=median+(gates*long_delta).sum(-1) + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/long_seasonal/transfer.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/long_seasonal/transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..c20a4df852f5b150e634ae2c06510d01c7ea18b3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/long_seasonal/transfer.py @@ -0,0 +1,73 @@ +"""Apply one matched feature-learning difference with explicit zero-extension semantics.""" +import argparse +import hashlib +import importlib.util +import json +import sys +import time +from pathlib import Path + +import numpy as np +import torch + +R = Path('/workspace/research') +parser = argparse.ArgumentParser() +for key in ['base','candidate','control','out']: + parser.add_argument('--'+key,required=True) +args = parser.parse_args() +torch.set_num_threads(2) +torch.manual_seed(571) +started = time.monotonic() +paths = [Path(args.base),Path(args.candidate),Path(args.control)] +base,candidate,control = [torch.load(p,map_location='cpu',weights_only=False) for p in paths] +extra = {'long_query.weight','long_head.weight','long_head.bias'} +assert set(base['model'])==set(control['model']) +assert set(candidate['model'])==set(base['model'])|extra +config = dict(candidate['config']) +assert config.pop('long_seasonal_features') is True +assert config==base['config']==control['config'] +sys.path.insert(0,str(R/'long_seasonal')) +from model import DirectForecaster +extended = DirectForecaster(**candidate['config']) +missing,unexpected = extended.load_state_dict(base['model'],strict=False) +assert set(missing)==extra and not unexpected +assert all(torch.count_nonzero(extended.state_dict()[k])==0 for k in extra) +spec = importlib.util.spec_from_file_location('transfer_original_model',R/'overflow_control/model.py') +code = importlib.util.module_from_spec(spec) +spec.loader.exec_module(code) +original = code.DirectForecaster(**base['config']) +original.load_state_dict(base['model']) +rng = np.random.default_rng(571) +periods = torch.tensor([[24,168],[7,365],[52,1],[1,1]]) +for c,h in [(32,6),(512,128)]: + ctx = torch.tensor(rng.normal(size=(4,c)).astype(np.float32)) + ctx[0,:c//3] = float('nan') + ctx[1] = 0 + ctx[2] = float('nan') + with torch.inference_mode(): + a = original(ctx,periods,h) + b = extended(ctx,periods,h) + assert all(torch.equal(v,w) for v,w in zip(a,b)) +weights = {k:v.clone() for k,v in extended.state_dict().items()} +for k in weights: + if k in extra: + weights[k].copy_(candidate['model'][k]) + else: + assert weights[k].shape==candidate['model'][k].shape==control['model'][k].shape + weights[k].add_(candidate['model'][k]-control['model'][k]) +assert all(torch.isfinite(v).all() for v in weights.values()) +out = Path(args.out) +assert not out.exists(),'Refuse to overwrite a declared fixed candidate' +conversion = dict(method='matched training delta after zero extension of new seasonal query/head parameters', + formula='extend_zero(base) + candidate - extend_zero(control)',coefficient=1.0, + new_parameters_from_candidate=sorted(extra), + parent_hashes={str(p):hashlib.sha256(p.read_bytes()).hexdigest() for p in paths}, + base_extension_forward_bitwise_equal=True,check_seed=571, + seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False) +checkpoint = dict(model=weights,config=candidate['config'],step=0,args={'packed':base['args']['packed']}, + parent_checkpoints=[str(p) for p in paths],conversion=conversion) +torch.save(checkpoint,out) +result = dict(conversion,checkpoint_sha256=hashlib.sha256(out.read_bytes()).hexdigest(), + parameters=sum(v.numel() for v in weights.values())) +out.with_suffix('.json').write_text(json.dumps(result,indent=2)) +print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/overflow_control/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/overflow_control/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/overflow_control/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/overflow_control/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/overflow_control/model.py new file mode 100644 index 0000000000000000000000000000000000000000..3532e5063bd8b5013f6b6e35703707ffef66e00b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/overflow_control/model.py @@ -0,0 +1,213 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/partial_delta/merge.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/partial_delta/merge.py new file mode 100644 index 0000000000000000000000000000000000000000..3dde47d52d25ed2b013942b3887f1bf686e42ed8 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/partial_delta/merge.py @@ -0,0 +1,16 @@ +"""Apply the difference of two matched, locally trained checkpoints to our selected model.""" +import argparse,torch,hashlib,json,time +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('--base',required=True);ap.add_argument('--candidate',required=True);ap.add_argument('--control',required=True);ap.add_argument('--out',required=True);a=ap.parse_args() +torch.set_num_threads(1);start=time.monotonic() +base=torch.load(a.base,map_location='cpu',weights_only=False);candidate=torch.load(a.candidate,map_location='cpu',weights_only=False);control=torch.load(a.control,map_location='cpu',weights_only=False) +assert set(candidate['model'])==set(control['model']) +weights={k:v.clone() for k,v in base['model'].items()} +for k in candidate['model']: + assert k in weights and weights[k].shape==candidate['model'][k].shape==control['model'][k].shape + weights[k].add_(candidate['model'][k]-control['model'][k]) +assert all(torch.isfinite(v).all() for v in weights.values()) +parents=[a.base,a.candidate,a.control] +conversion={'method':'matched training delta','formula':'base + candidate - control','coefficient':1.0,'parent_hashes':{p:hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in parents},'seconds':time.monotonic()-start} +ck={'model':weights,'config':base['config'],'step':0,'args':{'packed':base['args']['packed']},'parent_checkpoints':parents,'conversion':conversion} +torch.save(ck,a.out);print(json.dumps(conversion)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/partial_targets/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/partial_targets/data.py new file mode 100644 index 0000000000000000000000000000000000000000..a51e912d3c4b63a3ec0cd85133bf0e7aa3429569 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/partial_targets/data.py @@ -0,0 +1,73 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/partial_targets/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/partial_targets/model.py new file mode 100644 index 0000000000000000000000000000000000000000..4ffe50d9aadf21d73949e2052ceb7f3642bf65d3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/partial_targets/model.py @@ -0,0 +1,180 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(ctx,periods,target.shape[-1],forecast_lengths=lengths) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/partial_targets/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/partial_targets/train.py new file mode 100644 index 0000000000000000000000000000000000000000..2e77612e443d78dd80bcb6a0cc6d01169f61a3a4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/partial_targets/train.py @@ -0,0 +1,73 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',required=True) + 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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(2);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep,source_weights_from=a.source_weights_from) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/convert.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/convert.py new file mode 100644 index 0000000000000000000000000000000000000000..b2cbc8fc919be6a77eca9ab19c4faa06060a2e0d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/convert.py @@ -0,0 +1,18 @@ +"""Convert only our own trained checkpoint from 32- to 16-point patches. + +Context/query projections fold the two halves by summation, preserving the +embedding of constant features. The output projection keeps the first half. +Attention/MLP weights are inherited unchanged; position units remain 32 points. +""" +import argparse,torch,hashlib +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('--input',required=True);ap.add_argument('--output',required=True);a=ap.parse_args() +ck=torch.load(a.input,map_location='cpu',weights_only=False);state=ck['model'];d=ck['config']['d'];assert ck['config']['patch']==32 +old=state['embed.0.weight'].reshape(d,2,32);state['embed.0.weight']=(old[:,:,:16]+old[:,:,16:]).reshape(d,32) +old=state['query.0.weight'].reshape(d,32,9);state['query.0.weight']=(old[:,:16]+old[:,16:]).reshape(d,16*9) +state['head.weight']=state['head.weight'].reshape(32,18,d)[:16].reshape(16*18,d).clone() +state['head.bias']=state['head.bias'].reshape(32,18)[:16].reshape(16*18).clone() +ck['config']['patch']=16 +ck['conversion']={'from_checkpoint':str(Path(a.input).resolve()),'from_sha256':hashlib.sha256(Path(a.input).read_bytes()).hexdigest(),'method':'fold input/query halves by summation; retain first 16 output rows; preserve physical positional units'} +ck['args']={**ck['args'],'initialize_from':str(Path(a.input).resolve()),'converted':True} +torch.save(ck,a.output) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/data.py new file mode 100644 index 0000000000000000000000000000000000000000..40223a1f590e36dc202f2fb1e7c270f692aaef85 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/data.py @@ -0,0 +1,72 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + w=min(len(values),20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/evaluate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..05f086d4d84def4a48165f9e65d2948877675e56 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/evaluate.py @@ -0,0 +1,16 @@ +import sys,json,argparse,time,hashlib +from pathlib import Path +import torch +from predict import load_model,run +sys.path.insert(0,'/workspace/evaluation') +from score import score,json_safe + +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);ap.add_argument('--valid',default='/workspace/research/valid_screen');ap.add_argument('--baseline',default='/workspace/research/valid_screen/baseline.json');a=ap.parse_args() +torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cuda.matmul.allow_tf32=False +t0=time.time();out=Path(a.out);v=Path(a.valid) +run(load_model(a.weights),v/'input',out) +base=json.loads(Path(a.baseline).read_text())['configs'] +rep=score(v/'truth',out,base) +rep['checkpoint_sha256']=hashlib.sha256(Path(a.weights).read_bytes()).hexdigest();rep['eval_seconds']=time.time()-t0 +(out/'report.json').write_text(json.dumps(json_safe(rep),indent=1)) +print(json.dumps({k:rep[k] for k in ('skill_score','rel_mase_gmean','rel_wql_gmean','n_failed','groups','eval_seconds')},indent=1)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/model.py new file mode 100644 index 0000000000000000000000000000000000000000..06cce56e2ce671b6683f0246900abfcac06bb3c0 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/model.py @@ -0,0 +1,154 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/pack.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0c404bdd2e9382ab7f431cb359b6df31ed12a6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/pack.py @@ -0,0 +1,56 @@ +"""Deterministic one-pass, source-capped pack; only mounted allow-listed Arrow data.""" +import json,time,hashlib,concurrent.futures,argparse +from pathlib import Path +import numpy as np +import pyarrow as pa + +ROOT=Path('/workspace/data/gifteval_pretrain') + +def pack_dir(job): + name,out,cap=job + rng=np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:4],'little')) + files=sorted((ROOT/name).glob('data-*.arrow')) + rng.shuffle(files) + # Spread large-source samples across eight shards rather than taking one contiguous slice. + files=files[:min(8,len(files))] + meta=[]; total=0; offsets=[0]; t0=time.time() + with open(out/f'{name}.bin','wb') as dest: + for file in files: + quota=max(1,cap//len(files)); kept=0 + with pa.memory_map(str(file),'r') as f: + table=pa.ipc.open_stream(f).read_all() + freq=table.column('freq')[0].as_py() if table.num_rows else '' + for target in table.column('target').chunks: + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + target=target.values + off=target.offsets.to_numpy() + flat=target.values.to_numpy(zero_copy_only=False) + ids=np.arange(len(target));rng.shuffle(ids) + for i in ids: + x=flat[off[i]:off[i+1]] + if len(x)<16 or not np.isfinite(x).any():continue + # Cap very long series at a random contiguous year-sized segment. + if len(x)>131072: + start=int(rng.integers(len(x)-131072+1));x=x[start:start+131072] + x=np.asarray(x,dtype=np.float32) + x.tofile(dest);total+=len(x);kept+=len(x);offsets.append(total) + meta.append({'dataset':name,'freq':freq,'length':len(x)}) + if kept>=quota:break + if kept>=quota:break + np.save(out/f'{name}.offsets.npy',np.asarray(offsets,np.int64)) + (out/f'{name}.json').write_text(json.dumps(meta)) + return name,total,len(meta),round(time.time()-t0,1) + +def main(): + 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() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + names=sorted(p.name for p in ROOT.iterdir() if p.is_dir() and not p.name.startswith('.')) + lock=json.loads(Path('/workspace/data/sources.lock.json').read_text()) + allowed=next(s for s in lock['sources'] if s['id']=='gifteval_pretrain')['directories'] + assert set(names)<=set(allowed) + with concurrent.futures.ThreadPoolExecutor(a.workers) as pool: + for result in pool.map(pack_dir,[(n,out,a.cap) for n in names]):print(result,flush=True) + counts={n:len(json.loads((out/f'{n}.json').read_text())) for n in names} + (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)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..e20c6630475d6b4fa6906eb4ed9454b7b5aeec2c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/predict.py @@ -0,0 +1,43 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):q=model.predict(x,p,h).float().cpu().numpy() + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf95c9aec5936076b881c340edb960786f2d40d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/publish.py @@ -0,0 +1,31 @@ +"""Assemble a relocatable package, then atomically exchange complete directories.""" +import json,os,shutil,ctypes,hashlib,argparse +from pathlib import Path +import torch +HERE=Path(__file__).resolve().parent + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',default='/workspace/submission');ap.add_argument('--report',required=True);ap.add_argument('--experiments',default=str(HERE/'EXPERIMENTS.md'));a=ap.parse_args() + final=Path(a.out);staging=final.parent/f'.{final.name}-staging-{os.getpid()}' + shutil.rmtree(staging,ignore_errors=True);staging.mkdir(parents=True) + for file in ('model.py','predict.py','infer.sh','ts_io.py'): + shutil.copy(HERE/file,staging/file) + shutil.copy(a.weights,staging/'weights.pt');shutil.copy('/opt/runtime/requirements.txt',staging/'requirements.txt') + ck=torch.load(a.weights,map_location='cpu',weights_only=False);digest=hashlib.sha256((staging/'weights.pt').read_bytes()).hexdigest() + sources=json.loads(Path('/workspace/research/packed_sample/meta.json').read_text())['dirs'] + manifest={'name':'direct-seasonal-quantile-v1','contract':'timeseries-forecast/v1','parameters':sum(x.numel() for x in ck['model'].values()),'pretrained_assets':[],'sources_used':[f'gifteval_pretrain/{d}' for d in sources]+['synthetic:direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; data.py generator seed 17'],'weights_sha256':digest,'training_step':ck['step'],'config':ck['config'],'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.'} + (staging/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') + (staging/'config.json').write_text(json.dumps(ck['config'],indent=2)+'\n') + shutil.copy(a.experiments,staging/'EXPERIMENTS.md');shutil.copy(a.report,staging/'validation_report.json') + # Include generator/sampler provenance, which is not imported by inference. + (staging/'provenance').mkdir() + for file in ('pack.py','data.py','train.py'):shutil.copy(HERE/file,staging/'provenance'/file) + (staging/'README.md').write_text('# Direct seasonal quantile foundation forecaster\n\nRun `bash infer.sh INPUT_DIR OUTPUT_DIR`. This package contains all inference assets and uses only its supplied input directory. The 6.76M 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.\n\nThe 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.\n') + if final.exists(): + libc=ctypes.CDLL(None,use_errno=True) + if libc.renameat2(-100,os.fsencode(staging),-100,os.fsencode(final),2):raise OSError(ctypes.get_errno(),os.strerror(ctypes.get_errno())) + shutil.rmtree(staging) + else:os.replace(staging,final) + print(json.dumps(manifest,indent=1)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/record.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/record.py new file mode 100644 index 0000000000000000000000000000000000000000..1850a33f46fa3ee4d78cac4a5d6152404801a131 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/record.py @@ -0,0 +1,9 @@ +import argparse,json,math +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('report');ap.add_argument('--label',required=True);ap.add_argument('--outcome',default='Screened for model selection.');a=ap.parse_args() +r=json.loads(Path(a.report).read_text());p=Path(__file__).with_name('EXPERIMENTS.md') +lines=[f'\n## {a.label}',f'- Checkpoint SHA-256: `{r.get("checkpoint_sha256","see model_manifest.json")}`.',f'- Evaluation: {r["n_configs"]} configurations, {r["n_instances"]} instances, {r["n_failed"]} failed configurations; {r.get("eval_seconds","not separately timed")} seconds.',f'- Overall skill {r["skill_score"]:.6f}; relative MASE {r["rel_mase_gmean"]:.6f}; relative WQL {r["rel_wql_gmean"]:.6f}.'] +for group,entries in r['groups'].items(): + lines.append(f'- {group} skill: '+', '.join(f'{k}={1-math.sqrt(v["rel_mase_gmean"]*v["rel_wql_gmean"]):.4f}' for k,v in entries.items())+'.') +lines.append('- Outcome: '+a.outcome) +with p.open('a') as f:f.write('\n'.join(lines)+'\n') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/train.py new file mode 100644 index 0000000000000000000000000000000000000000..3cdc106980371c99d81c71d6746943c47206be83 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/train.py @@ -0,0 +1,71 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(3);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/validation_subset.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..4df83e69c4f9a3365955e5d17ffcfc0af71372b7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/patch16/validation_subset.py @@ -0,0 +1,18 @@ +"""Model-selection-only subset spanning all 97 configurations, seed 2026.""" +import sys,json,copy +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +import ts_io + +root=Path('/workspace/data/valid');out=Path('/workspace/research/valid_screen') +idx=json.loads((root/'input/index.json').read_text());new=copy.deepcopy(idx);rng=np.random.default_rng(2026) +for cfg in new['configs']: + cid=cfg['config_id'];case=ts_io.CaseFile(root/'input/cases'/f'{cid}.h5') + ids=np.sort(rng.choice(case.n,min(case.n,192),replace=False)) + ts_io.write_case_subset(case,ids,out/'input/cases'/f'{cid}.h5') + lab,se,meta=ts_io.read_truth_file(root/'truth/cases'/f'{cid}.h5') + ts_io.write_truth_file(out/'truth/cases'/f'{cid}.h5',lab[ids],se[ids],meta) + cfg['n_instances']=len(ids);case.close() +for kind in ('input','truth'):(out/kind/'index.json').write_text(json.dumps(new,indent=1)) +print('screen instances',sum(c['n_instances'] for c in new['configs'])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/postloss/check_numerical_fix.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/postloss/check_numerical_fix.py new file mode 100644 index 0000000000000000000000000000000000000000..0dd7f0b04a538020f59a4d4e8d6bc4884e0acd29 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/postloss/check_numerical_fix.py @@ -0,0 +1,26 @@ +"""Regression test for observed variance overflow in permitted training data.""" +import importlib.util +import json +from pathlib import Path +import time +import torch +from model import DirectForecaster,loss_fn + +R=Path('/workspace/research');torch.set_num_threads(1);started=time.monotonic() +spec=importlib.util.spec_from_file_location('original',Path(__file__).with_name('model_before_numerical_fix.py')) +original=importlib.util.module_from_spec(spec);spec.loader.exec_module(original) +torch.manual_seed(331);normal=torch.randn(8,512);normal[0,:200]=float('nan');normal[1]=float('nan');normal[2]=0 +old=original.DirectForecaster.standardize(normal);new=DirectForecaster.standardize(normal) +assert all(torch.equal(a,b) for a,b in zip(old,new)) +f=torch.load(R/'postloss_nonfinite_fixture.pt',map_location='cpu',weights_only=False) +indices=torch.tensor([37]);ctx=f['ctx'][indices];target=f['target'][indices];periods=f['periods'][indices] +z,valid,mu,scale=DirectForecaster.standardize(ctx) +assert torch.isfinite(z).all() and torch.isfinite(mu).all() and torch.isfinite(scale).all() +ck=torch.load(R/'horizon_delta12k.pt',map_location='cpu',weights_only=False) +m=DirectForecaster(**ck['config']).cuda();m.load_state_dict(ck['model']) +with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(m,ctx.cuda(),target.cuda(),periods.cuda(),paired=True) +loss.backward();torch.cuda.synchronize() +assert torch.isfinite(loss) and all(v.grad is not None and torch.isfinite(v.grad).all() for v in m.parameters()) +result={'ordinary_rows_bitwise_original':True,'observed_overflow_row_loss':float(loss.detach()), + 'all_gradients_finite':True,'optimizer_updates':0,'seconds':time.monotonic()-started} +(R/'postloss_numerical_fix_checks.json').write_text(json.dumps(result,indent=2));print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/postloss/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/postloss/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/postloss/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/postloss/diagnose_nonfinite.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/postloss/diagnose_nonfinite.py new file mode 100644 index 0000000000000000000000000000000000000000..770ff91d0718cbb6b947fc91fd61697ea50cbfd6 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/postloss/diagnose_nonfinite.py @@ -0,0 +1,42 @@ +"""Find nonfinite fixed-transform outputs on the unchanged allowed-corpus stream.""" +import json +from pathlib import Path +import time +import numpy as np +import torch +from model import DirectForecaster +from data import Sampler +from torch_post import apply_fixed,context_statistics + +R=Path('/workspace/research');torch.set_num_threads(1);torch.manual_seed(197) +torch.backends.cuda.matmul.allow_tf32=True +ck=torch.load(R/'horizon_delta12k.pt',map_location='cpu',weights_only=False) +m=DirectForecaster(**ck['config']).cuda();m.load_state_dict(ck['model']);m.eval() +sampler=Sampler(R/'packed_sample',seed=197,source_weights_from=R/'packed_sample') +rng=np.random.default_rng(197);started=time.monotonic() +for step in range(1,251): + 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])) + arrays=sampler.sample(64,c,h);ctx,target,periods=[torch.from_numpy(v).cuda() for v in arrays] + with torch.no_grad(),torch.autocast('cuda',dtype=torch.bfloat16): + seen=torch.isfinite(target);pos=torch.arange(h,device=ctx.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + raw,mu,scale=m(torch.cat((ctx,-ctx),0),periods.repeat(2,1),h,forecast_lengths=lengths.repeat(2)) + q=(raw[:64]-raw[64:].flip(-1))*.5;mu=mu[:64];scale=scale[:64] + denormalized=q*scale[:,:,None]+mu[:,:,None] + post=apply_fixed(ctx,periods,denormalized) + bad=~torch.isfinite(post).all((1,2)) + if bad.any(): + stats=context_statistics(ctx,periods,h) + badids=torch.nonzero(bad)[:,0] + receipt={'step':step,'context':c,'horizon':h,'bad_rows':badids.tolist(), + 'raw_finite':bool(torch.isfinite(q).all()),'scale_finite':bool(torch.isfinite(scale).all()), + 'denormalized_finite':bool(torch.isfinite(denormalized).all()), + 'statistics_finite':[bool(torch.isfinite(v).all()) for v in stats], + 'bad_scale':scale[bad].tolist(),'bad_mu':mu[bad].tolist(), + 'bad_maximum_context':torch.nan_to_num(ctx[bad]).abs().max(-1).values.tolist(), + 'seconds':time.monotonic()-started,'optimizer_updates':0} + torch.save({'ctx':ctx.cpu(),'target':target.cpu(),'periods':periods.cpu(), + 'raw':denormalized.cpu(),'scale':scale.cpu(),'post':post.cpu(), + 'statistics':[v.cpu() for v in stats]},R/'postloss_nonfinite_fixture.pt') + (R/'postloss_nonfinite_diagnostic.json').write_text(json.dumps(receipt,indent=2));print(json.dumps(receipt));break +else:print(json.dumps({'no_nonfinite_fixed_parent_outputs_in_first_steps':250,'seconds':time.monotonic()-started})) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/postloss/gpu_check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/postloss/gpu_check.py new file mode 100644 index 0000000000000000000000000000000000000000..a457afa8d1dd55d2167434b70f4e1488e41e4049 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/postloss/gpu_check.py @@ -0,0 +1,24 @@ +"""Verify the new training loss at the largest scheduled bf16 shape.""" +import fcntl,json,sys,time +from pathlib import Path +import torch + +r=Path('/workspace/research');sys.path.insert(0,str(r/'postloss')) +from model import DirectForecaster,loss_fn +from data import Sampler +with open(r/'.evaluation.lock','a') as lock: + fcntl.flock(lock,fcntl.LOCK_EX) + torch.set_num_threads(1);torch.manual_seed(281);torch.backends.cuda.matmul.allow_tf32=True + started=time.monotonic() + ck=torch.load(r/'horizon_delta12k.pt',map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).cuda();model.load_state_dict(ck['model']) + x,y,p=[torch.from_numpy(a).cuda() for a in Sampler(r/'packed_sample',281).sample(64,4096,1024)] + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p,paired=True) + loss.backward();torch.cuda.synchronize() + assert torch.isfinite(loss) + assert all(v.grad is not None and torch.isfinite(v.grad).all() for v in model.parameters()) + result={'seed':281,'batch':64,'context':4096,'horizon':1024,'optimizer_updates':0, + 'loss':float(loss.detach()),'seconds':time.monotonic()-started, + 'peak_allocated_mib':torch.cuda.max_memory_allocated()/2**20, + 'peak_reserved_mib':torch.cuda.max_memory_reserved()/2**20} + (r/'postloss_gpu_check.json').write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/postloss/launch_completion.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/postloss/launch_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..8bdf1346b99ae846a2679a7494c9b88c1900bdce --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/postloss/launch_completion.py @@ -0,0 +1,30 @@ +"""Complete the original pruned schedule from its immutable exact training state.""" +def main(): + import json + import os + import subprocess + from pathlib import Path + R=Path('/workspace/research') + receipt=json.loads((R/'postloss_recovery003653.json').read_text()) + assert receipt['step']==3653 + assert json.loads((R/'postloss_completion_code_audit.json').read_text())['matches_original_E75_archived_training_code'] + assert (R/'postloss.stop').exists() + env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1') + command=['python3',str(R/'recovery/train.py'),'--code-dir',str(R/'postloss'), + '--packed',str(R/'packed_sample'),'--source-weights-from',str(R/'packed_sample'), + '--out',str(R/'runs/postloss_completion'),'--initialize-from',str(R/'horizon_delta12k.pt'), + '--resume',str(R/'postloss_recovery003653.pt'),'--steps','12000','--batch','64','--lr','.00002', + '--seed','197','--loss-mode','paired','--stop-file',str(R/'postloss_completion.stop')] + with (R/'postloss_completion_queue.log').open('w') as qlog,(R/'postloss_completion_watch.log').open('w') as wlog: + queued=subprocess.Popen(['python3',str(R/'queued_train.py'),'--label','E98 complete original E75 schedule', + '--log',str(R/'postloss_completion_train.log'),'--receipt',str(R/'postloss_completion_queue.json'), + '--wait-pid','9274','--require-checkpoint',str(R/'runs/split_patch/recovery.pt'), + '--',*command],stdout=qlog,stderr=subprocess.STDOUT,env=env) + watch=subprocess.Popen(['python3',str(R/'watch_evaluate.py'),'--run',str(R/'runs/postloss_completion'), + '--evaluator',str(R/'postloss_inference/evaluate.py'),'--name','postloss_completion', + '--steps','6000,12000'],stdout=wlog,stderr=subprocess.STDOUT,env=env) + print({'queue_pid':queued.pid,'watch_pid':watch.pid},flush=True) + result=queued.wait() + if result:watch.terminate() + watch.wait();raise SystemExit(result) +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/postloss/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/postloss/model.py new file mode 100644 index 0000000000000000000000000000000000000000..014b585df72cc69852a8eedf302320b52fe55aad --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/postloss/model.py @@ -0,0 +1,216 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + from torch_post import apply_fixed + q=apply_fixed(ctx,periods,q*scale[:,:,None]+mu[:,:,None]) + q=(q-mu[:,:,None])/scale[:,:,None] + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/postloss/model_before_numerical_fix.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/postloss/model_before_numerical_fix.py new file mode 100644 index 0000000000000000000000000000000000000000..1dab6e08582e4610693292e765d40a8b5392e97a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/postloss/model_before_numerical_fix.py @@ -0,0 +1,207 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + from torch_post import apply_fixed + q=apply_fixed(ctx,periods,q*scale[:,:,None]+mu[:,:,None]) + q=(q-mu[:,:,None])/scale[:,:,None] + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/postloss/restart.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/postloss/restart.py new file mode 100644 index 0000000000000000000000000000000000000000..fa09bf30ead55ac10ca2d8c9a55277ddd71986f7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/postloss/restart.py @@ -0,0 +1,25 @@ +"""Restart corrected E75 from the declared parent and record process compute.""" +import json +import os +from pathlib import Path +import subprocess +import time + +R=Path('/workspace/research');run=R/'runs/postloss' +receipt=json.loads((R/'postloss_queue_before_recovery2.json').read_text()) +command=receipt['command'] +assert not (run/'recovery.pt').exists(),'This script is only for the documented pre-checkpoint numerical restart.' +env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1') +with (R/'postloss_recovery3.log').open('w') as f: + p=subprocess.Popen(command,stdout=f,stderr=subprocess.STDOUT,env=env) +record={'command':command,'status':'running','pid':p.pid,'log':str(R/'postloss_recovery3.log'), + 'started_utc':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()), + 'note':'Restart own E62 initialization after verified float32 variance-overflow correction; original seed and recipe unchanged.'} +path=R/'postloss_recovery3_receipt.json';path.write_text(json.dumps(record,indent=2)) +watch=['python3',str(R/'watch_evaluate.py'),'--run',str(run),'--evaluator',str(R/'postloss_inference/evaluate.py'), + '--name','postloss','--steps','1000,3000,6000,12000'] +with (R/'postloss_watch_recovery3_fixed.log').open('w') as f: + subprocess.Popen(watch,stdout=f,stderr=subprocess.STDOUT,env=env) +started=time.monotonic();returncode=p.wait() +record.update(status='complete' if returncode==0 else 'failed',returncode=returncode,process_seconds=time.monotonic()-started) +path.write_text(json.dumps(record,indent=2));raise SystemExit(returncode) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/postloss/torch_post.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/postloss/torch_post.py new file mode 100644 index 0000000000000000000000000000000000000000..e19586bcc1677d56cedb6ce02c2f57797157f5f3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/postloss/torch_post.py @@ -0,0 +1,112 @@ +"""Differentiable forecast transforms with the package's fixed context rules. + +Context statistics are constants with respect to model parameters. Gradients +flow only through the forecast, including the continuity correction's anchor. +""" +import torch + + +@torch.no_grad() +def context_statistics(ctx, periods, horizon): + x=ctx.double(); finite=torch.isfinite(x); clean=torch.where(finite,x,0.) + b,c=x.shape; device=x.device + pos=torch.arange(c,device=device)[None,:] + count=finite.sum(-1).clamp(min=1) + mean=clean.sum(-1)/count + variance=(torch.where(finite,x-mean[:,None],0.).square()).sum(-1)/count + positive=((x>=0)|~finite).all(-1) + zeros=((x==0)&finite).sum(-1) + zero_active=positive&(zeros>=4)&(zeros/count>=.1) + cutoff=torch.where(zero_active,.4*variance.sqrt(),0.) + first=torch.where(finite,pos,c).min(-1).values + length=c-first + phase=torch.arange(max(1,c//3),device=device)[None,:] + future=torch.arange(horizon,device=device)[None,:] + z=torch.tensor([-1.2815515655,-.8416212336,-.5244005127,-.2533471031,0, + .2533471031,.5244005127,.8416212336,1.2815515655],device=device) + best_weight=torch.zeros(b,device=device,dtype=torch.float64) + prior=torch.zeros(b,horizon,9,device=device,dtype=torch.float64) + prior_valid=torch.zeros(b,horizon,device=device,dtype=torch.bool) + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + cycles=(length[:,None]//p).clamp(max=8) + history=finite&(pos>=c-cycles*p) + n=history.sum(-1).clamp(min=1) + center=(clean*history).sum(-1)/n + var=torch.where(history,x-center[:,None],0.).square().sum(-1)/n + previous=pos-p;safe=previous.clamp(min=0) + pairs=(previous>=c-cycles*p)&(previous>=0)&finite&finite.gather(1,safe) + pairs_count=pairs.sum(-1) + difference=clean-clean.gather(1,safe) + mse=(difference.square()*pairs).sum(-1)/pairs_count.clamp(min=1) + weight=(1-mse/(var+1e-12)/.25).clamp(0,.98) + eligible=(p[:,0]>=2)&(cycles[:,0]>=3)&(pairs_count>=p[:,0]) + weight=torch.where(eligible,weight,0.) + values=[];observed=[] + for cycle in range(4): + idx=c-p+phase-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(phase=0)&(cycle0 + template=(values*observed).sum(0)/nphase.clamp(min=1) + ntemplate=phase_valid.sum(-1).clamp(min=1) + template_mean=(template*phase_valid).sum(-1)/ntemplate + recent=finite&(pos>=c-p) + nr=recent.sum(-1).clamp(min=1) + recent_mean=(clean*recent).sum(-1)/nr + template=template+(recent_mean-template_mean)[:,None] + template_mean=(template*phase_valid).sum(-1)/ntemplate + recent_var=torch.where(recent,x-recent_mean[:,None],0.).square().sum(-1)/nr + template_var=((template-template_mean[:,None]).square()*phase_valid).sum(-1)/ntemplate + used_cycles=cycles[:,0].clamp(min=1,max=4) + noise=mse/2 + target_var=(recent_var-noise).clamp(min=0) + base_var=(template_var-noise/used_cycles).clamp(min=0) + ratio=(target_var/base_var.clamp(min=1e-12)).sqrt().clamp(.5,2.) + align=nr>=torch.maximum(torch.full_like(nr,2),.75*p[:,0]) + ratio=torch.where(align,ratio,1.) + template=template_mean[:,None]+(template-template_mean[:,None])*ratio[:,None] + sigma=(noise*(1+1/used_cycles)).sqrt() + index=(future%p).clamp(max=phase.shape[-1]-1) + selected=template.gather(1,index) + valid=phase_valid.gather(1,index) + q=selected[:,:,None]+sigma[:,None,None]*z[None,None,:] + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + choose=weight>best_weight + prior=torch.where(choose[:,None,None],q,prior) + prior_valid=torch.where(choose[:,None],valid,prior_valid) + best_weight=torch.maximum(best_weight,weight) + seasonal_weight=best_weight[:,None]*prior_valid + + recent=x[:,-512:];seen=torch.isfinite(recent) + n=seen.sum(-1).clamp(min=1);clean_recent=torch.where(seen,recent,0.) + center=clean_recent.sum(-1)/n + var=torch.where(seen,recent-center[:,None],0.).square().sum(-1)/n + differences=recent[:,1:]-recent[:,:-1] + diff_seen=torch.isfinite(differences);nd=diff_seen.sum(-1) + mse=torch.where(diff_seen,differences,0.).square().sum(-1)/nd.clamp(min=1) + tail=differences[:,-8:] + tail_seen=torch.isfinite(tail);nt=tail_seen.sum(-1) + sorted_tail=torch.where(tail_seen,tail,float('inf')).sort(-1).values + if tail.shape[-1]: + lo=((nt-1).clamp(min=0)//2)[:,None];hi=(nt//2).clamp(max=tail.shape[-1]-1)[:,None] + median=(sorted_tail.gather(1,lo)+sorted_tail.gather(1,hi))[:,0]/2 + else:median=torch.zeros(b,device=device,dtype=x.dtype) + continuity_weight=(1-mse/(var+1e-12)/.5).clamp(0,.95) + active=(nd>=8)&(nt>0)&seen[:,-1] + continuity_weight=torch.where(active,continuity_weight,0.) + anchor=torch.where(active,recent[:,-1]+median,0.) + return seasonal_weight,prior,continuity_weight,anchor,positive,cutoff + + +def apply_fixed(ctx,periods,quant): + """Quantiles are raw-scale tensors of shape (batch,horizon,9).""" + weight,prior,cweight,anchor,positive,cutoff=context_statistics(ctx,periods,quant.shape[1]) + q=torch.where(positive[:,None,None],quant.clamp(min=0),quant) + q=((1-weight[:,:,None])*q+weight[:,:,None]*prior).float() + bias=(cweight*(anchor-q[:,0,4])).float() + decay=torch.exp(-torch.arange(q.shape[1],device=q.device,dtype=torch.float64)/24) + q=(q.double()+bias[:,None,None]*decay[None,:,None]).float() + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return torch.where((q>=0)&(q8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recency_features/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recency_features/model.py new file mode 100644 index 0000000000000000000000000000000000000000..f8271c5b0bf9a5edb961e1c7839761fe50a2e40b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recency_features/model.py @@ -0,0 +1,171 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024,recency_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + if self.recency is not None: + pos=torch.arange(c,device=z.device)[None,:];extras=[] + for j in range(2): + period=periods[:,j:j+1] + recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recency_features/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recency_features/train.py new file mode 100644 index 0000000000000000000000000000000000000000..3bfb8b90f1a6656881b7598f864becaa737a76f4 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recency_features/train.py @@ -0,0 +1,73 @@ +import argparse,json,math,time,os,sys,shutil,hashlib +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import numpy as np +import torch +from model import DirectForecaster,loss_fn +from data import Sampler + +def save(model,path,step,args,opt=None): + ck={'model':model.state_dict(),'config':model.config,'step':step,'args':vars(args)} + if opt is not None:ck['opt']=opt.state_dict() + tmp=str(path)+'.tmp';torch.save(ck,tmp);os.replace(tmp,path) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--packed',required=True);ap.add_argument('--out',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) + ap.add_argument('--d',type=int,default=256);ap.add_argument('--enc',type=int,default=4);ap.add_argument('--dec',type=int,default=3) + ap.add_argument('--patch',type=int,default=32) + 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) + ap.add_argument('--resume',default='');ap.add_argument('--initialize-from',default='');ap.add_argument('--stop-file',default='');a=ap.parse_args() + torch.set_num_threads(3);torch.manual_seed(a.seed);np.random.seed(a.seed) + torch.backends.cuda.matmul.allow_tf32=True + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + model=DirectForecaster(d=a.d,enc_layers=a.enc,dec_layers=a.dec,patch=a.patch,max_context=a.context).cuda() + opt=torch.optim.AdamW(model.parameters(),lr=a.lr,weight_decay=.05,betas=(.9,.95),fused=True) + # Exponential averaging is a training-only stabilization; inference remains fixed. + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + startstep=0 + if a.resume: + ck=torch.load(a.resume,map_location='cuda',weights_only=False);model.load_state_dict(ck['model']);startstep=ck['step'] + if 'opt' in ck:opt.load_state_dict(ck['opt']) + if a.initialize_from: + ck=torch.load(a.initialize_from,map_location='cuda',weights_only=False) + missing,unexpected=model.load_state_dict(ck['model'],strict=False) + assert not unexpected and all(k.startswith('recency.') for k in missing) + ema={k:v.detach().clone() for k,v in model.state_dict().items()} + sampler=Sampler(a.packed,seed=a.seed+startstep) + params=sum(p.numel() for p in model.parameters());(out/'config.json').write_text(json.dumps({**vars(a),'parameters':params},indent=2)) + print('parameters',params,flush=True) + rng=np.random.default_rng(a.seed+startstep) + def nextbatch(): + 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])) + return sampler.sample(a.batch,c,h) + pool=ThreadPoolExecutor(1);future=pool.submit(nextbatch);t0=time.time();losses=[] + for step in range(startstep+1,a.steps+1): + arrays=future.result();future=pool.submit(nextbatch) + x,y,p=[torch.from_numpy(x).cuda(non_blocking=True) for x in arrays] + lr=a.lr*min(1,step/400)*(.2+.8*.5*(1+math.cos(math.pi*min(1,step/a.steps)))) + for g in opt.param_groups:g['lr']=lr + opt.zero_grad(set_to_none=True) + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(model,x,y,p) + loss.backward();gn=torch.nn.utils.clip_grad_norm_(model.parameters(),1.) + if torch.isfinite(gn): + opt.step() + with torch.no_grad(): + decay=min(.999,1-1/(step+1)) + for k,v in model.state_dict().items():ema[k].lerp_(v,1-decay) + losses.append(float(loss.detach())) + if step%50==0: + 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]} + print(json.dumps(rec),flush=True) + with open(out/'log.jsonl','a') as f:f.write(json.dumps(rec)+'\n') + losses=[] + stop=a.stop_file and Path(a.stop_file).exists() + if step%a.save_every==0 or step==a.steps or stop: + save(model,out/f'step{step:06d}.pt',step,a) + save(model,out/'last.pt',step,a,opt) + ck={'model':ema,'config':model.config,'step':step,'args':vars(a),'ema':True} + path=out/f'ema{step:06d}.pt';torch.save(ck,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) + if stop:break + pool.shutdown() + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/brief.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/brief.py new file mode 100644 index 0000000000000000000000000000000000000000..7f06e7c2e8fcd4ce31d08d936fa5018cf00dc855 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/brief.py @@ -0,0 +1,34 @@ +"""Write a short, current recovery handoff; never modify training state.""" +import datetime +import json +from pathlib import Path + +R = Path('/workspace/research') +s = json.loads((R/'CURRENT_RESEARCH_STATE.json').read_text()) +lines = ['# Current recovery brief', '', datetime.datetime.now(datetime.timezone.utc).isoformat(), '', + 'Continuous research; no endpoint/final hand-in. One H10080GB,22CPUs,224GiB requested RAM; no network or pretrained assets. Do not inspect credentials or spawn agents.', '', + '## Published', '', json.dumps(s['published']), '', '## Pending selection', '', + json.dumps(s.get('next_candidate',{})), '', json.dumps({k:v for k,v in s.get('selection_probes',{}).items() if k in ['E128','E130','E132','E133','E134','E135','E136','E137','E138','E139','E140','E141','E142']}), '', '## Active and queued training', ''] +for name, job in s.get('external_jobs',{}).items(): + if job['status'] not in ['running','waiting']: + continue + lines += [f'- {name}: {job["status"]}; receipt {job["receipt"]}; queue PID snapshot {job["queue_pid_at_snapshot"]}; children {job["child_pids_at_snapshot"]}.', + f' Last logged record: {json.dumps(job["last_phase_record"])}', + f' Complete recovery: {job["complete_recovery_checkpoint"]}; latest EMA: {job["latest_saved_ema"]}.'] +lines += ['', '## Recovery rules', '', + '- PIDs and launch-script dependencies are snapshots. After an operator restart, restore running jobs from each complete recovery.pt, preserving optimizer/EMA/RNG/prefetched batch and original schedules. Rewire waiting jobs to the newly launched dependency PIDs; do not blindly rerun old launch scripts.', + '- Waiting dependency chain: weekly_replication_control after long_seasonal; weekly_replication_candidate after that control; lowfreq_windows after that candidate; long_seasonal_replication after lowfreq_windows. phase_joint waits for random_capacity_512 final96000; seasonal_dispersion waits for phase_joint final12000; seasonal_history waits for seasonal_dispersion final12000. random_capacity_original_ar waits for random_capacity_1024 final96000; log_horizon waits for long_seasonal_replication final12000; seasonal_width waits for seasonal_history final12000; random_capacity_long_seasonal waits for both E94halfLR and E79wide final96000 and replaces only the E94allocation. visibility_curriculum waits for E110full and E79wide final96000 and replaces only the E110allocation; preserve --visibility-curriculum on any resume. direct_trend_head waits for E129seasonal_width final12000 and replaces that allocation. random_capacity_deep waits for E122originalAR and E79wide final96000, replacing only the E122allocation.', + '- E121 history-aware ensemble runtime is prepared at history_three_patch_ensemble; synthetic audit checks exact standalone composition and ordinary legacy equality. It also applies member finite cleanup before averaging, correcting a pre-existing extreme-value discrepancy. Use this separate publisher and complete public replay before any E121 publication; E130 now publishes four members using four_member_ensemble/publish.py, retaining both finite cleanup and per-member history support. Use that publisher for four-member packages.', + '- E126 compiled_teacher_trial completed its mandatory17000stop; do not resume it. It preserved original96000 LR schedule from immutable distill_ensemble_recovery016000.pt. Original E101 stays active. Compiler takeover rejected: max cutoff drift0.001964 exceeded0.0005 tolerance, with only3to5percent warm shared-device timing gain. No coefficient change selected. E125 component ablations completed; both paths help. E127 finite-member numerical fix is published with all97predictions bitwise unchanged; do not republish it. E128 dispersion transfers6000 and12000 both lost full validation; neither is published. E130 equal-quarter package is the current best. E132 checks scheduled E79wide96000 as the fourth member; E133 passed both source replication gates but its fixed averaged correction failed the ensemble gate (2of4positive, mean-0.0000154271); no full replay or averaging sweep. Receipts are indexed in CURRENT_RESEARCH_STATE.json.', + '- E138 learned gate uses immutable /workspace/research/gating_experts_E130, descriptorfa97880d..., even if submission improves. CPU/GPU/recovery/publicruntime/relocation audits passed; queued after E123final12000. Check queue receipt and rewire dependencies after restart. Training must preserve --gate-package and restore complete optimizer/EMA/RNG/prefetched batch. No expert tensors enter the gate optimizer. Gate publisher is ensemble_gate/publish.py. E139width primary6k is published at0.3843356309048914 after allfour diagnostics/fullsuite/bitwisecomposition;12k requires matched-source gate. E140separate loader-only candidate passed six-run syntheticidentity and45percent shared-device median loadreduction; full97bitwiseidentity/relocation pending, notpublished. Gate trainer/experts loader unchanged. E132final fourthmember andE142width6+final quartet both passeddiagnostics; assemble(kind fresh/joint) onlyafter E140runtime decision, then fullreplay andcomposition. E141matched146Mpatch16/patch8 continuations seed809/B32/LR2e-5/12k passed CPU/GPUaudits, queued29105control afterE13626926final12000 then29107candidate aftercontrolfinal12000. Same random_capacity model/data code, candidate folded ownE79wide96checkpoint. Preserve fullrecovery/compiledloss andsequentialdependency after restart. Use seasonal_width_transfer/promote.py only after better full replay and all checks.', + '- E101 distillation teacher is immutable /workspace/research/distill_teacher_E96, even after later publications. Do not substitute the current submission.', + '- Restore compiler_cache_backup to the same /tmp cache paths before restarting compiled trainers. Exact environment and commands are in CURRENT_RESEARCH_STATE.json.', + '- E105 output collision is documented in incidents/stratified_volume_output_collision. Correct E105 output is runs/stratified_volume. E95final and2k..12k weights survive, but E95optimizer recovery and original1k weights were lost. Do not resume completed E95.', + '- All previous negative/stopped branches stay stopped unless a new matched experiment explicitly revisits them. Never retrain the supplied baselines.', + '- Current training-source publisher archives all Python modules from explicitly declared directories, fixing earlier omissions of spectral.py and schedules.py. Complete-source members carry a -complete suffix when rebuilt. Runtime/weight hashes were unchanged.', + '- Full evaluation and GPU diagnostics use .evaluation.lock; the six main trainers share the one H100. The bounded E126 seventh-process probe completed17000 and should remain stopped. Dataset windows under data/valid and all earlier cutoffs are selection only, never training.', + '- Master journal direct_v1/EXPERIMENTS.md, chronological SESSION_20261023_PROGRESS.md, and RESEARCH_IDEAS.md contain decisions and rejected candidates. Recheck live processes and latest reports before acting.', + '', '## Time anchor', '', + 'Latest operator recovery allowance:151596research seconds at2026-10-23T02:45:51UTC. Pauses/preflight excluded. The goal remains active and has no requested token budget.', ''] +(R/'RECOVERY_BRIEF.md').write_text('\n'.join(lines)) +print('Wrote RECOVERY_BRIEF.md with '+str(sum(j['status'] in ['running','waiting'] for j in s.get('external_jobs',{}).values()))+' active/queued jobs.') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/capacity_curves.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/capacity_curves.py new file mode 100644 index 0000000000000000000000000000000000000000..c89a28a84243dc16ae52a1215c182a00f15dbc4e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/capacity_curves.py @@ -0,0 +1,50 @@ +"""Summarize completed validation checkpoints and measured shared-GPU training time.""" +import csv +import json +import time +from pathlib import Path + +R = Path('/workspace/research') +started = time.monotonic() +names = ['random_capacity_512', 'random_capacity_1024', 'random_capacity_1024_halflr', + 'random_capacity_full', 'distill_ensemble', 'random_capacity_512_anneal'] +rows = [] +for name in names: + log = R/(name+'_train.log') + records = {} + if log.exists(): + for line in log.read_text().splitlines(): + try: + item = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(item,dict) and 'step' in item and 'seconds' in item: + records[item['step']] = item + config_path = R/'runs'/name/'config.json' + config = json.loads(config_path.read_text()) if config_path.exists() else {} + for report in sorted((R/'evals').glob(name+'_ema*/report.json')): + result = json.loads(report.read_text()) + step = int(report.parent.name.rsplit('ema',1)[1]) + if result['n_failed']: + continue + record = records.get(step,{}) + rows.append(dict(run=name,step=step,parameters=config.get('parameters'), + seed=config.get('seed'),batch=config.get('batch'),learning_rate=config.get('lr'), + packed=config.get('packed'),skill=result['skill_score'], + rel_mase=result['rel_mase_gmean'],rel_wql=result['rel_wql_gmean'], + checkpoint_sha256=result['checkpoint_sha256'], + training_phase_loop_seconds=record.get('seconds'), + evaluation_seconds=result.get('eval_seconds'),report=str(report))) +rows.sort(key=lambda item:(names.index(item['run']),item['step'])) +output = dict(generated_utc=time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()), + note='Validation selection only. Time is logged process wall on the shared single H100, not isolated GPU time. The cooldown arm starts from the same saved24000state; its phase clock resets. No missing log time is inferred.', + rows=rows,analysis_seconds=time.monotonic()-started,no_training_or_new_inference=True) +(R/'capacity_learning_curves.json').write_text(json.dumps(output,indent=2)) +with (R/'capacity_learning_curves.csv').open('w',newline='') as handle: + writer = csv.DictWriter(handle,fieldnames=list(rows[0]) if rows else ['run']) + writer.writeheader() + writer.writerows(rows) +for name in names: + selected = [r for r in rows if r['run']==name] + if selected: + print(json.dumps(selected[-1])) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/exposure_audit.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/exposure_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..fb67738bc9ed77f87173feda2430365e66c75966 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/exposure_audit.py @@ -0,0 +1,46 @@ +"""Describe sampled observation exposure and training invested in selected ancestry.""" +import json +import sys +import time +from pathlib import Path +import numpy as np + +R=Path('/workspace/research') +sys.path.insert(0,str(R/'random_capacity')) +from data import Sampler + +started=time.monotonic() +seed=521 +sampler=Sampler(R/'packed_sample',seed=seed,source_weights_from=R/'packed_sample') +rng=np.random.default_rng(seed) +rows=context_points=target_points=0 +for _ in range(320): + 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])) + x,y,p=sampler.sample(64,c,h) + rows+=len(x) + context_points+=int(np.isfinite(x).sum()) + target_points+=int(np.isfinite(y).sum()) +manifest=json.loads(Path('/workspace/submission/model_manifest.json').read_text()) +runs={} +for item in manifest['training_lineage']: + path=Path(item['checkpoint']) + batch=item.get('training_settings',{}).get('batch') + if path.parts[0]!='runs' or not batch: + continue + run=path.parts[1] + step=item.get('step',0) + if step>runs.get(run,{}).get('step',0): + runs[run]=dict(step=step,batch=batch,rows=step*batch,checkpoint=item['checkpoint']) +ancestral_rows=sum(v['rows'] for v in runs.values()) +mean_points=(context_points+target_points)/rows +result=dict(seed=seed,seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False, + sampled_rows=rows,mean_finite_context_points=context_points/rows, + mean_finite_target_points=target_points/rows,mean_finite_points=mean_points, + selected_descriptor=manifest['checkpoint_sha256'],ancestral_runs=runs, + selected_ancestral_rows_before_sign_pairing=ancestral_rows, + fresh96000_batch48_rows=96000*48, + fresh96000_batch48_gross_observation_presentations_estimate=96000*48*mean_points, + note='Gross sampled presentations include overlapping/resampled windows and synthetic values, not unique observations. Ancestral run maxima count compute invested in different branches, including subtracted controls; they are not an equivalent single-model training trajectory. Sign pairing duplicates compute but not distinct sampled rows. No future training recipe is inferred from this audit alone.') +(R/'training_exposure_audit.json').write_text(json.dumps(result,indent=2)) +print(json.dumps({k:v for k,v in result.items() if k!='ancestral_runs'})) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/launch_matched_cutoffs.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/launch_matched_cutoffs.py new file mode 100644 index 0000000000000000000000000000000000000000..6d33e64b8212b250fc38a2990604c80228b94c80 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/launch_matched_cutoffs.py @@ -0,0 +1,14 @@ +"""Keep evaluation controllers alive for the declared queued comparisons.""" +from pathlib import Path +import datetime,json,os,subprocess +R=Path('/workspace/research');jobs={};processes={};env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1') +for name,control,runtime,label in [('lowfreq_windows','overflow_control','postloss_inference','E113'),('seasonal_history','long_seasonal','seasonal_history_inference','E121'),('seasonal_width','seasonal_dispersion','seasonal_width_inference','E129'),('long_seasonal_replication','weekly_replication_control','long_seasonal_inference','E118'),('log_horizon','overflow_control','postloss_inference','E123')]: + path=R/(name+'_matched_cutoffs.log') + with path.open('a') as log: + command=['python3',str(R/'recovery/watch_matched_cutoffs.py'),'--run',name,'--control',control,'--evaluator',str(R/runtime/'evaluate.py'),'--label',label] + p=subprocess.Popen(command,stdout=log,stderr=subprocess.STDOUT,env=env) + processes[label]=p;jobs[label]=dict(pid=p.pid,parent_pid=os.getpid(),command=command,log=str(path),receipt=str(R/(name+'_matched_cutoffs_receipt.json'))) +q=R/'CURRENT_RESEARCH_STATE.json';state=json.loads(q.read_text());state['diagnostics']['matched_cutoff_controllers']=jobs;t=q.with_suffix('.tmp');t.write_text(json.dumps(state,indent=2));os.replace(t,q) +print(json.dumps(jobs),flush=True) +for label,p in processes.items(): + result=p.wait();print(json.dumps(dict(label=label,returncode=result)),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/matched_report.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/matched_report.py new file mode 100644 index 0000000000000000000000000000000000000000..f7755cfc0300a5a18f3e2db1d6d5aa89cda9f0fa --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/matched_report.py @@ -0,0 +1,16 @@ +"""Record matched validation reports, including all configuration-group metrics.""" +import argparse,datetime,json,math +from pathlib import Path +R=Path('/workspace/research');ap=argparse.ArgumentParser() +for key in ['candidate','control','label','out']:ap.add_argument('--'+key,required=True) +ap.add_argument('--cutoffs',default='0');ap.add_argument('--outcome',required=True);a=ap.parse_args() +folders=['evals','backcast_evals','backcast2_evals','backcast3_evals'];rows=[] +for index in map(int,a.cutoffs.split(',')): + folder=folders[index];x=json.loads((R/folder/a.candidate/'report.json').read_text());y=json.loads((R/folder/a.control/'report.json').read_text()) + assert x['n_failed']==y['n_failed']==0 and x['n_configs']==y['n_configs'] + delta={g:{k:math.sqrt(y['groups'][g][k]['rel_mase_gmean']*y['groups'][g][k]['rel_wql_gmean'])-math.sqrt(v['rel_mase_gmean']*v['rel_wql_gmean']) for k,v in entries.items()} for g,entries in x['groups'].items()} + rows.append(dict(cutoff=folder,candidate_skill=x['skill_score'],control_skill=y['skill_score'],delta=x['skill_score']-y['skill_score'],candidate_checkpoint=x['checkpoint_sha256'],control_checkpoint=y['checkpoint_sha256'],candidate_eval_seconds=x.get('eval_seconds'),candidate_groups=x['groups'],control_groups=y['groups'],group_skill_delta=delta)) +result=dict(label=a.label,utc=datetime.datetime.now(datetime.timezone.utc).isoformat(),candidate=a.candidate,control=a.control,rows=rows,mean_delta=sum(v['delta'] for v in rows)/len(rows),positive_cutoffs=sum(v['delta']>0 for v in rows),outcome=a.outcome) +p=Path(a.out);assert not p.exists(),'Refuse duplicate comparison record';p.write_text(json.dumps(result,indent=2)) +with (R/'direct_v1/EXPERIMENTS.md').open('a') as f:f.write('\n'+a.label+': '+json.dumps(result)+'\n') +print(json.dumps({k:v for k,v in result.items() if k!='rows'})) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/median_error_structure.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/median_error_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..83bb24d13841f0266d0947799c682f47e8641474 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/median_error_structure.py @@ -0,0 +1,30 @@ +"""Describe validation median errors without fitting or proposing corrected forecasts.""" +import argparse,json,sys,time +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation') +from ts_io import read_prediction_file,read_truth_file +ap=argparse.ArgumentParser() +for n in ['valid','pred','report','out']:ap.add_argument('--'+n,required=True) +a=ap.parse_args();start=time.monotonic();root=Path(a.valid);report=json.loads(Path(a.report).read_text());rows=[] +for cfg in report['configs']: + cid=cfg['config_id'];y,scale,_=read_truth_file(root/'truth/cases'/(cid+'.h5'));_,q=read_prediction_file(Path(a.pred)/'cases'/(cid+'.h5')) + good=np.isfinite(scale)&(scale>0);valid=np.isfinite(y)&good[...,None];safe=np.where(good,scale,1).astype(np.float64) + err=np.where(valid,(q[:,:,4,:].astype(np.float64)-y.astype(np.float64))/safe[...,None],0.) + n=valid.sum(-1);total=int(n.sum());mae=float(np.abs(err).sum()/total) + signed=float(err.sum()/total);absolute_window_mean=float(np.abs(err.sum(-1)).sum()/total) + assert absolute_window_mean<=mae+1e-10 + lead=[] + for positions in np.array_split(np.arange(y.shape[-1]),4): + mask=valid[...,positions];count=int(mask.sum());values=err[...,positions] + lead.append(dict(count=count,mase=float(np.abs(values).sum()/count),signed_scaled_error=float(values.sum()/count))) + rows.append(dict(config_id=cid,term=cfg['term'],domain=cfg['domain'],frequency=cfg['freq'],horizon=cfg['prediction_length'],mase=mae,scorer_mase=cfg['metrics']['mase'],signed_scaled_error=signed,absolute_window_mean_error=absolute_window_mean,window_mean_error_fraction_of_mae=absolute_window_mean/max(mae,1e-30),lead_quarters=lead)) + assert abs(mae-cfg['metrics']['mase'])<1e-6*max(1,mae) +groups={} +for key in ['term','domain','frequency']: + groups[key]={} + for value in sorted({row[key] for row in rows}): + selected=[row for row in rows if row[key]==value] + groups[key][value]=dict(configs=len(selected),mean_window_mean_error_fraction=float(np.mean([row['window_mean_error_fraction_of_mae'] for row in selected])),mean_signed_error_over_mae=float(np.mean([row['signed_scaled_error']/max(row['mase'],1e-30) for row in selected])),mean_lead_quarter_mase_ratio=[float(np.mean([row['lead_quarters'][i]['mase']/max(row['mase'],1e-30) for row in selected])) for i in range(4)]) +result=dict(checkpoint_sha256=report['checkpoint_sha256'],groups=groups,configs=rows,seconds=time.monotonic()-start,optimizer_updates=0,new_inference=False,note='Validation-only descriptive analysis. Absolute per-window mean error is a Jensen lower bound on MAE, not a recoverable correction or attributable causal component. Groups average configurations equally; lead ratios are descriptive, not the benchmark metric. No parameter fitting or forecast modification.') +Path(a.out).write_text(json.dumps(result,indent=2));print(json.dumps({k:v for k,v in result.items() if k!='configs'})) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/pack_composition.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/pack_composition.py new file mode 100644 index 0000000000000000000000000000000000000000..0a023de983f7c0860043b58def56406e3fd27eb9 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/pack_composition.py @@ -0,0 +1,32 @@ +"""Read-only comparison of source/length composition in the two allowed packs.""" +import json,time +from pathlib import Path +import numpy as np +R=Path('/workspace/research');started=time.monotonic();old=R/'packed_sample';new=R/'packed_stratified_full' +a=json.loads((old/'meta.json').read_text());b=json.loads((new/'meta.json').read_text());assert a['dirs']==b['dirs'];names=a['dirs'] +weights=[] +for n in names: + w=min((old/(n+'.bin')).stat().st_size//4,20000000)**.25 + if n.startswith(('era5_','cmip6_')):w*=.35 + if n.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) +weights=np.array(weights)/sum(weights);bins=np.array([16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131073]) +rows=[];aggregate={k:np.zeros(len(bins)-1) for k in ['old','full']} +for n,w in zip(names,weights): + row={'source':n,'conditional_real_source_probability':float(w)} + for k,root in [('old',old),('full',new)]: + lengths=np.diff(np.load(root/(n+'.offsets.npy'),mmap_mode='r')) + hist=np.histogram(lengths,bins=bins)[0]/len(lengths);aggregate[k]+=w*hist + row[k]={'series':len(lengths),'points':int(lengths.sum()),'mean_length':float(lengths.mean()),'median_length':float(np.median(lengths)), + 'fraction_below64':float(np.mean(lengths<64)),'fraction_below256':float(np.mean(lengths<256)), + 'fraction_at_least20480':float(np.mean(lengths>=20480)),'length_bin_probabilities':hist.tolist()} + row['weighted_length_distribution_l1']=float(w*np.abs(np.array(row['old']['length_bin_probabilities'])-row['full']['length_bin_probabilities']).sum()) + row['mixed_frequency_rows_in_full']=b['receipts'][n]['mixed_frequency_rows_in_candidates'];row['full_frequencies']=b['receipts'][n]['kept_frequencies'];rows.append(row) +result=dict(kind='per-source uniform-series sampling composition; no series values or validation labels read', + length_bins=bins.tolist(),conditional_real_length_bin_probabilities={k:v.tolist() for k,v in aggregate.items()}, + source_probabilities_unchanged=True,min_length_both=16,max_crop_length_both=131072, + mixed_frequency_sources=[r['source'] for r in rows if r['mixed_frequency_rows_in_full']],sources=rows, + seconds=time.monotonic()-started,optimizer_updates=0) +(R/'pack_composition_comparison.json').write_text(json.dumps(result,indent=2)) +print(json.dumps({k:v for k,v in result.items() if k!='sources'})) +for row in sorted(rows,key=lambda r:-r['weighted_length_distribution_l1'])[:12]:print(json.dumps({k:v for k,v in row.items() if k not in ['old','full']},separators=(',',':')), 'mean_length',row['old']['mean_length'],row['full']['mean_length']) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/quantile_coverage.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/quantile_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..d7f4958ae772a15c4a580eed59bb9257b065154d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/quantile_coverage.py @@ -0,0 +1,59 @@ +"""Validation-only quantile coverage, with separate strict/inclusive coverage at atoms.""" +import argparse +import json +import sys +import time +from pathlib import Path + +import numpy as np + +sys.path.insert(0,'/workspace/evaluation') +from ts_io import read_prediction_file, read_truth_file + +parser = argparse.ArgumentParser() +parser.add_argument('--valid',required=True) +parser.add_argument('--pred',required=True) +parser.add_argument('--report',required=True) +parser.add_argument('--out',required=True) +args = parser.parse_args() +started = time.monotonic() +root = Path(args.valid) +index = json.loads((root/'input/index.json').read_text()) +report = json.loads(Path(args.report).read_text()) +levels = np.arange(1,10)/10 +rows = [] +for cfg in index['configs']: + relative = Path('cases')/(cfg['config_id']+'.h5') + y,scale,_ = read_truth_file(root/'truth'/relative) + _,q = read_prediction_file(Path(args.pred)/relative) + valid = np.isfinite(y) + assert q.shape==(*y.shape[:2],9,y.shape[-1]) and np.isfinite(q).all() + count = int(valid.sum()) + assert count>0 + strict = ((y[:,:,None,:] anneal_from_step + assert 0 < anneal_final_lr <= anneal_from_lr + progress=max(0.,min(1.,(step-anneal_from_step)/(steps-anneal_from_step))) + return anneal_final_lr+.5*(anneal_from_lr-anneal_final_lr)*(1+math.cos(math.pi*progress)) + warm_step=step-reset_at if reset_at>=0 and step>reset_at else step + return peak*min(1,warm_step/400)*(.2+.4*(1+math.cos(math.pi*step/steps))) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/seasonal_history_support.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/seasonal_history_support.py new file mode 100644 index 0000000000000000000000000000000000000000..84314b30b22a4a761447fc5ee1cffb9301e725b9 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/seasonal_history_support.py @@ -0,0 +1,23 @@ +"""Context-metadata diagnostic of potential 8-cycle support, with no targets read.""" +import importlib.util,json,time +from pathlib import Path +import h5py,numpy as np +R=Path('/workspace/research');started=time.monotonic() +spec=importlib.util.spec_from_file_location('support_model',R/'long_seasonal/model.py');m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m) +root=Path('/workspace/data/valid/input');index=json.loads((root/'index.json').read_text());rows=[] +for cfg in index['configs']: + with h5py.File(root/'cases'/(cfg['config_id']+'.h5'),'r') as f:lengths=np.asarray(f['context_length']) + h=cfg['prediction_length'];periods=m.periods_for_freq(cfg['freq']);row={k:cfg[k] for k in ['config_id','freq','term','domain']};row['periods']=periods;row['n_instances']=len(lengths) + for cap in [4096,16384]: + support=[];cycles=[] + for p in periods: + count=np.clip(1+(np.minimum(lengths,cap)[:,None]-p+np.arange(h)[None,:]%p)//p,0,16) + support.append(float(np.mean((count>=8)&(p>=2))));cycles.append(float(np.mean(np.where(p>=2,count,0)))) + row[str(cap)]={'phase_support_fraction':support,'mean_available_cycles':cycles} + row['support_gain_sum']=sum(row['16384']['phase_support_fraction'])-sum(row['4096']['phase_support_fraction']);rows.append(row) +changed=[r for r in rows if r['support_gain_sum']>0] +result=dict(kind='optimistic potential support before missing-value masks; not measured forecast improvement',input_metadata_only=True,validation_targets_read=False,optimizer_updates=0,configs=rows, + changed_configurations=len(changed),changed_domains=sorted(set(r['domain'] for r in changed)),seconds=time.monotonic()-started) +(R/'seasonal_history_support.json').write_text(json.dumps(result,indent=2)) +print(json.dumps({k:v for k,v in result.items() if k!='configs'})) +for r in sorted(changed,key=lambda x:x['support_gain_sum'],reverse=True)[:20]:print(json.dumps(r)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/snapshot.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/snapshot.py new file mode 100644 index 0000000000000000000000000000000000000000..9e28a9c484f4afe4e605e8ffd7a53d25831b1d87 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/snapshot.py @@ -0,0 +1,99 @@ +"""Write a compact authoritative research recovery index without touching training state.""" +import datetime +import json +import os +from pathlib import Path + +R=Path('/workspace/research');p=R/'CURRENT_RESEARCH_STATE.json' +s=json.loads(p.read_text()) +s['snapshot_utc']=datetime.datetime.now(datetime.timezone.utc).isoformat() +receipt=json.loads((R/'recovery3_launch_receipt.json').read_text()) +s['runs']={} +for name,job in receipt['jobs'].items(): + run=R/'runs'/name + log=Path(job['log']) + records=[] + for line in log.read_text().splitlines(): + try: + record=json.loads(line) + if 'step' in record or 'completed_step' in record:records.append(record) + except json.JSONDecodeError:pass + s['runs'][name]={'config':json.loads((run/'config.json').read_text()) if (run/'config.json').exists() else None, + 'last_phase_record':records[-1] if records else None, + 'phase_log':str(log),'supervisor_receipt':str(R/'recovery3_launch_receipt.json'), + 'latest_saved_ema':str(max(run.glob('ema*.pt'))) if list(run.glob('ema*.pt')) else None, + 'complete_recovery_checkpoint':str(run/'recovery.pt') if (run/'recovery.pt').exists() else None, + 'pid_at_snapshot':job['pid'],'returncode':job.get('returncode'), + 'note':'Check actual live process and checkpoint state before resuming; this is only a snapshot.'} +s['queues']={name:{'status':q['status'],'dependency':q['dependency'],'command':q['command'], + 'required_checkpoints':q['required_checkpoints']} + for name,q in receipt['queues'].items()} +s.pop('prepared_not_launched',None) +s['deferred_unqueued']={'E72':'temporal_mixup, prepared and checked but not queued','ideas':'RESEARCH_IDEAS.md, no jobs attached'} +s['completed_since_previous_recovery']={ + 'E67_control12000':{'skill':.37724286394256845,'training_loop_seconds':2794.8358458959847}, + 'E67_paired12000':{'skill':.377427077277383,'training_loop_seconds':2794.867385860998}, + 'E63_expanded146M':'Stopped8501, complete recovery retained; allocation moved to E73; inconclusive data scaling', + 'E61_slowAR':'Complete12000; E76 used6000 correction, final transfer rejected', + 'E65_recent_normalization':'Complete12000; E81 equal ensemble rejected', + 'E58_small_control':'Complete32000', + 'E58_wide146M':'Complete32000; no gain over37Mcontrol; do not resume', + 'E71_patch8':'Complete12000; selected6000 used in E87/E96/E102 ensembles', + 'E69_volatility':'Complete12000; final below matched control; no transfer', + 'E89_patch8_control':'Complete12000; final0.380847096,loop2729.052105s; selected starting E71parent remains stronger', + 'E89_fullpatch4':'Complete12000,main0.381640078; E96 used6000, E103final cached alternative mixed; loop5066.016522s', + 'E93_split_patch':'Complete12000,main0.381711986; selected final is E102 published thirdmember; loop3153.565149s', + 'E92_robust_normalization':'Complete12000,final0.377099312 belowcontrol; rejected;E97started', + 'E90_metric_scale':'Complete12000; final0.377373344 ties/slightly trailsE80; no selection; loop2702.166704s', + 'E84_coarse':'Complete12000; daily gain but weekly regression; not selected', + 'E88_late_patch8_slowAR':'Complete12000; small9k gain lost atfinal; rejected', + 'E80_overflow':'Complete12000; finaltiesoriginal; selected3k compositeE91rejected', + 'E78_multiscaleAR':'Complete12000; no gain over single slowAR', + 'E86_protected_graft':'Complete8000; below own initialization; no publication', + 'E75_postloss':'Stopped3653 deliberately; immutable snapshot retained; E98 separately declared completion active in another output, original stopfile remains', + 'E73_independent_graft':'Stopped8683 after negative8000; replaced by E86; stopfile remains', + 'E95_stratified_corpus':'Complete12000,final0.377983250,earliermixed; E105collision destroyed only1000weights and optimizer recovery;2k..12k preserved; do not resume', + 'E97_weekly_synth':'Complete12000,final0.380439539; E112final weekly correction now published; loop2600.472750s', + 'E105_stratified_volume':'Complete12000,final0.377529200,earlier0.336713522/0.359535697/0.390349158 mixed; corrected continuationloop2013.982814s plus original incident phase', + 'E106_spectral_synth':'Complete12000,final0.377641399,earlier0.337647555/0.361626447/0.385497870, average matched gap negligible; loop2206.272278s; E114fixed6000transfers in selection', + 'E98_postloss_completion':'Complete12000,final0.376034254 below3000 andcontrol; rejected,loop1995.386513s', + 'E99_early_cooldown':'Complete36000,final0.363306598 trails original36k0.364859034; rejected,loop1603.635706s', + 'E77_pairedslowAR':'Complete12000;6000 strongest main/earlier comparison'} +s['external_receipts']=[str(R/'postloss_recovery3_receipt.json'),str(R/'random_capacity_512_queue.json'),str(R/'random_capacity_1024_queue.json'),str(R/'multiscale_ar_queue.json'),str(R/'overflow_control_queue.json'),str(R/'coarse_aggregate_queue.json'),str(R/'patch8_long_memory_queue.json'),str(R/'wide_graft_frozen_queue.json'),str(R/'patch4_candidate_queue.json'),str(R/'patch4_control_queue.json'),str(R/'metric_scale_queue.json'),str(R/'robust_normalization_queue.json'),str(R/'split_patch_queue.json'),str(R/'random_capacity_1024_halflr_queue.json'),str(R/'stratified_corpus_queue.json'),str(R/'weekly_synth_queue.json'),str(R/'postloss_completion_queue.json'),str(R/'random_capacity_512_anneal_queue.json'),str(R/'distill_ensemble_queue.json'),str(R/'stratified_volume_queue.json'),str(R/'spectral_synth_queue.json'),str(R/'long_seasonal_queue.json'),str(R/'random_capacity_full_queue.json'),str(R/'weekly_replication_control_queue.json'),str(R/'weekly_replication_candidate_queue.json'),str(R/'lowfreq_windows_queue.json'),str(R/'phase_joint_queue.json'),str(R/'long_seasonal_replication_queue.json'),str(R/'seasonal_dispersion_queue.json'),str(R/'seasonal_history_queue.json'),str(R/'random_capacity_original_ar_queue.json'),str(R/'log_horizon_queue.json'),str(R/'compiled_teacher_trial_queue.json'),str(R/'seasonal_width_queue.json'),str(R/'random_capacity_long_seasonal_queue.json'),str(R/'visibility_curriculum_queue.json'),str(R/'direct_trend_head_queue.json'),str(R/'random_capacity_deep_queue.json'),str(R/'ensemble_gate_queue.json'),str(R/'capacity_patch8_control_queue.json'),str(R/'capacity_patch8_candidate_queue.json')] +queue_pids={'random_capacity_512_queue.json':965,'random_capacity_1024_queue.json':967, + 'multiscale_ar_queue.json':1678,'overflow_control_queue.json':1676, + 'coarse_aggregate_queue.json':3086,'patch8_long_memory_queue.json':3739, + 'wide_graft_frozen_queue.json':3931,'patch4_candidate_queue.json':4078, + 'patch4_control_queue.json':4080} +s['external_jobs']={} +for receipt_name in s['external_receipts']: + receipt_path=Path(receipt_name) + if not receipt_path.exists():continue + item=json.loads(receipt_path.read_text());command=item.get('command',[]) + if '--out' not in command:continue + run=Path(command[command.index('--out')+1]);log=Path(item.get('log',str(receipt_path).replace('_queue.json','_train.log'))) + last=None + if log.exists(): + for line in log.read_text().splitlines(): + try: + record=json.loads(line) + if isinstance(record,dict) and ('step' in record or 'completed_step' in record):last=record + except json.JSONDecodeError:pass + queue_pid=item.get('launcher_pid',queue_pids.get(receipt_path.name)) + children_file=Path(f'/proc/{queue_pid}/task/{queue_pid}/children') if queue_pid else None + children=list(map(int,children_file.read_text().split())) if children_file and children_file.exists() else [] + checkpoints=list(run.glob('ema*.pt')) + s['external_jobs'][run.name]={'receipt':str(receipt_path),'status':item.get('status'), + 'queue_pid_at_snapshot':queue_pid,'child_pids_at_snapshot':children, + 'last_phase_record':last,'log':str(log), + 'latest_saved_ema':str(max(checkpoints)) if checkpoints else None, + 'complete_recovery_checkpoint':str(run/'recovery.pt') if (run/'recovery.pt').exists() else None, + 'command':command,'note':'PIDs are only a snapshot; check actual processes and serialized state before recovery.'} +s['compiler_environment']={'OPENBLAS_NUM_THREADS':'1','OMP_NUM_THREADS':'1','TORCHINDUCTOR_COMPILE_THREADS':'2','MAX_JOBS':'2','PYTHONPATH':str(R/'compiler_support'),'TRITON_CACHE_MANAGER':'sibling_cache:SiblingFileCacheManager','TRITON_CACHE_DIR':'/tmp/timeseries-triton-cache','TORCHINDUCTOR_CACHE_DIR':'/tmp/timeseries-inductor-cache'} +for job in s['external_jobs'].values(): + job['environment']=s['compiler_environment'] if '--compile-loss' in job['command'] else {'OPENBLAS_NUM_THREADS':'1','OMP_NUM_THREADS':'1'} +s['compiler_cache_backup']=str(R/'compiler_cache_backup') +for stale in ['pending','pending_actions','active_experiments','next_experiments','prepared_experiments']: + s.pop(stale,None) +tmp=p.with_suffix('.tmp');tmp.write_text(json.dumps(s,indent=2));os.replace(tmp,p) +print(s['snapshot_utc']) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/synthetic_window_audit.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/synthetic_window_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..5a6455bbd9926f9d342ee1a24ca825328a9e7e1f --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/synthetic_window_audit.py @@ -0,0 +1,63 @@ +"""Compare actual allowed/synthetic training-window dynamics without validation data.""" +import datetime +import json +from pathlib import Path +import sys +import time +import types +import numpy as np + +R=Path('/workspace/research') +sys.path.insert(0,str(R/'overflow_control')) +source=(R/'overflow_control/data.py').read_text() +needle='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)' +assert source.count(needle)==1 +instrumented=source.replace(needle,needle+';self.audit_synthetic=np.zeros(batch,bool)') +needle='if r.random()=16 and len(target)>=4: + k=min(16,n//4,len(target)) + # Descriptive finite-observation means, not a proposed inference feature. + scale=max(float(np.std(values)),float(np.mean(np.abs(values)))*1e-4,1e-4) + past=(float(np.mean(values[-k:]))-float(np.mean(values[-2*k:-k])))/scale + future=(float(np.mean(target[:k].astype(np.float64)))-float(np.mean(values[-k:])))/scale + item.update(past_change=float(np.clip(past,-20,20)),future_change=float(np.clip(future,-20,20))) + groups.setdefault(frequency+'_'+kind,[]).append(item);counts+=1 +summary={} +for name,rows in groups.items(): + c=np.array([x['context'] for x in rows]);h=np.array([x['target'] for x in rows]) + valid=[x for x in rows if x['past_change'] is not None] + past=np.array([x['past_change'] for x in valid]);future=np.array([x['future_change'] for x in valid]) + summary[name]=dict(rows=len(rows),median_finite_context=float(np.median(c)), + context_at_most128=float(np.mean(c<=128)),context_above512=float(np.mean(c>512)), + median_finite_target=float(np.median(h)),dynamic_rows=len(valid), + median_abs_recent_change=float(np.median(np.abs(past))), + median_abs_future_change=float(np.median(np.abs(future))), + recent_future_change_correlation=float(np.corrcoef(past,future)[0,1])) +result=dict(seed=seed,rows=counts,batches=160,groups=summary,seconds=time.monotonic()-started, + generated_utc=datetime.datetime.now(datetime.timezone.utc).isoformat(), + instrumentation_first640_rows_and_rng_bitwise=True,optimizer_updates=0, + validation_data_read=False,decision='Descriptive audit only. E113 remains unchanged; no new generator selected.') +(R/'synthetic_window_audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/train.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/train.py new file mode 100644 index 0000000000000000000000000000000000000000..6c435174dc1783fe2151c4a2df9093074a38a317 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/train.py @@ -0,0 +1,257 @@ +"""Resumable continuation of our existing permitted-corpus experiments.""" +import argparse,copy,fcntl,inspect,json,math,os,sys,time +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import numpy as np +import torch + +ap=argparse.ArgumentParser() +ap.add_argument('--code-dir',required=True);ap.add_argument('--packed',required=True) +ap.add_argument('--source-weights-from');ap.add_argument('--out',required=True) +ap.add_argument('--initialize-from',required=True);ap.add_argument('--initialize-ema') +ap.add_argument('--start-step',type=int,default=0);ap.add_argument('--resume') +ap.add_argument('--steps',type=int,required=True);ap.add_argument('--batch',type=int,required=True) +ap.add_argument('--lr',type=float,required=True);ap.add_argument('--seed',type=int,required=True) +ap.add_argument('--context',type=int);ap.add_argument('--sample-context',type=int,default=4096) +ap.add_argument('--save-every',type=int,default=1000);ap.add_argument('--stop-file') +ap.add_argument('--recovery-every',type=int,default=250) +ap.add_argument('--halt-after',type=int) +ap.add_argument('--loss-mode',choices=['individual','paired']) +ap.add_argument('--compile-loss',action='store_true') +ap.add_argument('--reset-at',type=int,default=-1);ap.add_argument('--reset-seed',type=int,default=179) +ap.add_argument('--anneal-from-step',type=int);ap.add_argument('--anneal-from-lr',type=float) +ap.add_argument('--anneal-final-lr',type=float) +ap.add_argument('--teacher-package');ap.add_argument('--teacher-coefficient',type=float) +ap.add_argument('--compile-teacher',action='store_true') +ap.add_argument('--visibility-curriculum',action='store_true') +ap.add_argument('--gate-package') +a=ap.parse_args() +# Hold a process-lifetime lock before loading a model or touching GPU state. +_run_out=Path(a.out);_run_out.mkdir(parents=True,exist_ok=True) +_run_lock=open(_run_out/'.training.lock','a') +try:fcntl.flock(_run_lock,fcntl.LOCK_EX|fcntl.LOCK_NB) +except BlockingIOError:raise SystemExit('Another trainer already owns this output directory: '+str(_run_out)) +if not a.resume: + _saved=list(_run_out.glob('ema*.pt'))+list(_run_out.glob('step*.pt')) + if (_run_out/'recovery.pt').exists():_saved.append(_run_out/'recovery.pt') + if _saved: + raise SystemExit('Refusing fresh training into an output with saved checkpoints; use a new directory or explicit --resume: '+str(_run_out)) +sys.path.insert(0,a.code_dir) +from model import DirectForecaster,loss_fn +from data import Sampler +from schedules import learning_rate +torch.set_num_threads(2);torch.manual_seed(a.seed);torch.backends.cuda.matmul.allow_tf32=True +out=Path(a.out);out.mkdir(parents=True,exist_ok=True);a.trainable_scope='all' +if Path(a.code_dir).name in ('long_memory_synth','paired_long_memory','multiscale_ar','random_capacity','patch8_long_memory','distill_ensemble','random_capacity_long_seasonal','visibility_curriculum','random_capacity_deep'):a.synthetic_ar_time_constants=[1,10000] +if Path(a.code_dir).name in ('full_paired','patch8','temporal_mixup','postloss','paired_long_memory','multiscale_ar','random_capacity','overflow_control','coarse_aggregate','patch8_long_memory','patch4','metric_scale','robust_normalization','split_patch','weekly_synth','distill_ensemble'):a.requested_horizon_seed=a.seed+300003 +if Path(a.code_dir).name=='multiscale_ar': + a.synthetic_ar_components=4;a.multiscale_ar_seed=a.seed+700003 +if Path(a.code_dir).name=='volatility_synth':a.stochastic_volatility_seed=a.seed+500003 +if Path(a.code_dir).name=='coarse_aggregate': + a.coarse_aggregation_seed=a.seed+900003;a.coarse_aggregation_probability=.2;a.coarse_aggregation_frequencies=['D','W'] +if Path(a.code_dir).name=='temporal_mixup':a.temporal_mixup_seed=a.seed+600003 +if Path(a.code_dir).name=='postloss': + a.fixed_postprocessing_loss=True;a.normalization_overflow_fallback=True +if Path(a.code_dir).name in ('overflow_control','metric_scale','random_capacity','weekly_synth','distill_ensemble'):a.normalization_overflow_fallback=True +if Path(a.code_dir).name=='weekly_synth': + a.weekly_synthetic_seed=a.seed+1000003;a.weekly_replacement_probability=1/11 +if Path(a.code_dir).name=='spectral_synth': + a.spectral_synthetic_seed=a.seed+1100003;a.spectral_replacement_probability=.5 + a.spectral_length_scale=[1,10000];a.spectral_families=['Matern0.5','Matern1.5','Matern2.5','RBF'] + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True +if Path(a.code_dir).name in ('long_seasonal','phase_joint','seasonal_dispersion','seasonal_history','seasonal_width','direct_trend_head','random_capacity_long_seasonal','visibility_curriculum','random_capacity_deep','ensemble_gate'): + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True +if Path(a.code_dir).name=='random_capacity_original_ar': + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True + a.synthetic_ar_coefficient_law='uniform(0.2,0.995), original generator; unchanged AR branch probability and asymptotic variance scaling' +if Path(a.code_dir).name=='log_horizon': + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True + a.requested_horizon_law='half full; half geometric quantile remap of the original uniform integer endpoint draw from min(16,max(1,H//4)) to H, then patch16 rounding; identical RNG consumption' +if Path(a.code_dir).name=='seasonal_history': + a.learned_seasonal_history_context=16384;a.recent_encoder_and_rule_context=4096 + a.history_extension_rule='extend originally full4096 real contexts before the same cutoff, preserving original recent contexts, targets, aggregation, sampler RNG and horizon RNG; synthetic extra prefix missing' +if Path(a.code_dir).name in ('lowfreq_windows','lowfreq_age'): + a.requested_horizon_seed=a.seed+300003;a.normalization_overflow_fallback=True + a.lowfreq_window_seed=a.seed+1200003;a.lowfreq_window_probability=.5 + a.lowfreq_window_rule='period2=1,period1<=52;finite-target endpoint;log-uniform horizon4..min(H,max(8,2p),span-8) with available-length fallback;context cap min(C,max(64,32p));at least4finite history' +if Path(a.code_dir).name=='lowfreq_age': + a.synthetic_generation_origin='For successfully shortened selected low-frequency synthetic rows only, use the first nc+nh observations of the same generated path, split at nc; unchanged masks, lengths, periods, real/unselected rows and all RNG streams; no regeneration or extra draws' +if Path(a.code_dir).name=='metric_scale':a.loss_seasonality='lag1 for exact daily[7,365] and weekly[52,1] period pairs; unchanged otherwise' +if Path(a.code_dir).name=='robust_normalization':a.normalization_kind='finite median plus/minus6 mean absolute deviations winsorized mean/RMS, float64; original normalized history clipped30' +if Path(a.code_dir).name=='wide_graft_frozen':a.trainable_scope='new feature stream and cross-stream blocks; inherited parameter blocks frozen' +if a.visibility_curriculum: + assert Path(a.code_dir).name=='visibility_curriculum' and not a.teacher_package and not a.gate_package + from visibility import visible_batch + a.visibility_curriculum_rule='steps1..16000:lastC/4,firstmax(16,H/4);16001..32000:lastC/2,firstmax(16,H/2);32001..96000:unchanged; sample/prefetch full original windows and crop only current loss arrays' +ck=torch.load(a.resume or a.initialize_from,map_location='cpu',weights_only=False) +# Keep immutable branch ancestry across a later restart from this run's own recovery. +lineage_parents=list(ck.get('parent_checkpoints',[])) +if a.initialize_ema:lineage_parents.append(a.initialize_ema) +if a.resume and Path(a.resume).parent.resolve()!=out.resolve():lineage_parents.append(a.resume) +previous_args=ck.get('args',{}) +previous_resume=previous_args.get('resume') +if previous_resume and Path(previous_resume).parent.resolve()!=Path(previous_args.get('out',a.out)).resolve(): + lineage_parents.append(previous_resume) +lineage_parents=list(dict.fromkeys(lineage_parents)) +config=dict(ck['config']) +if a.context:config['max_context']=a.context +model=DirectForecaster(**config).cuda();model.load_state_dict(ck['model']) +teacher=None;teacher_predict=None;experts=None +if Path(a.code_dir).name=='distill_ensemble': + assert a.teacher_package and a.teacher_coefficient is not None +if a.teacher_package: + assert Path(a.code_dir).name=='distill_ensemble' + from teacher import OwnEnsembleTeacher + with torch.random.fork_rng(devices=[torch.cuda.current_device()]): + teacher=OwnEnsembleTeacher(a.teacher_package) + if ck.get('args',{}).get('teacher_descriptor_sha256'): + assert ck['args']['teacher_descriptor_sha256']==teacher.descriptor_sha256 + assert ck['args']['teacher_coefficient']==a.teacher_coefficient + a.teacher_descriptor_sha256=teacher.descriptor_sha256 + a.teacher_checkpoint_sha256=teacher.member_hashes + a.teacher_target_kind='equal average of own frozen E96 raw normalized sign-paired neural quantiles, before postprocessing' + teacher_predict=teacher + if a.compile_teacher: + torch._dynamo.config.recompile_limit=64 + teacher_predict=torch.compile(teacher.__call__,fullgraph=True,dynamic=False) +else: + assert not a.compile_teacher, '--compile-teacher requires a declared own-model teacher' + +if Path(a.code_dir).name=='ensemble_gate':assert a.gate_package and a.loss_mode=='paired' +if a.gate_package: + assert Path(a.code_dir).name=='ensemble_gate' and not a.teacher_package and not a.compile_loss + from experts import FrozenExperts + from model import FEATURE_NAMES + torch.backends.cuda.matmul.allow_tf32=False + with torch.random.fork_rng(devices=[torch.cuda.current_device()]): + experts=FrozenExperts(a.gate_package) + if ck.get('args',{}).get('fixed_expert_descriptor_sha256'): + assert ck['args']['fixed_expert_descriptor_sha256']==experts.descriptor_sha256 + assert ck['args']['fixed_expert_checkpoint_sha256']==experts.member_hashes + a.fixed_expert_descriptor_sha256=experts.descriptor_sha256 + a.fixed_expert_checkpoint_sha256=experts.member_hashes + a.expert_forecast_kind='four own frozen E130 raw-scale final forecasts, including exact packaged per-member transformations' + a.gate_weight_rule='0.125+0.5*softmax; same positive per-lead weight across all quantiles' + a.gate_features=FEATURE_NAMES + a.trainable_scope='6340 gate parameters only; four experts frozen and excluded from optimizer and EMA' + a.fixed_postprocessing_loss=True + a.gate_precision='FP32 gate, BF16 frozen experts, TF32 disabled' + assert sum(p.numel() for p in model.parameters())==6340 + +protector=None +if Path(a.code_dir).name=='wide_graft_frozen': + from frozen import FreezeInherited + protector=FreezeInherited(model) + a.protected_parameters=protector.inherited_numel +if a.compile_loss: + torch._dynamo.config.recompile_limit=64 + objective=torch.compile(loss_fn,fullgraph=True,dynamic=False) +else:objective=loss_fn +multipliers=ck.get('lr_multipliers',{}) +def optimizer(): + groups=[] + for mult in sorted(set(multipliers.values())|{1.}): + params=[p for n,p in model.named_parameters() if multipliers.get(n,1.)==mult] + if params:groups.append({'params':params,'lr':a.lr*mult,'lr_multiplier':mult,'weight_decay':.05/mult}) + return torch.optim.AdamW(groups,betas=(.9,.95),fused=True) +opt=optimizer() +if a.resume: + start_step=ck['step'];opt.load_state_dict(ck['optimizer']) + ema={k:v.cuda() for k,v in ck['ema_state'].items()} +else: + start_step=a.start_step + ema_ck=torch.load(a.initialize_ema,map_location='cpu',weights_only=False) if a.initialize_ema else ck + ema={k:v.cuda().clone() for k,v in ema_ck['model'].items()} +del ck +def make_sampler(seed): + kwargs={'seed':seed} + if 'source_weights_from' in inspect.signature(Sampler).parameters:kwargs['source_weights_from']=a.source_weights_from + return Sampler(a.packed,**kwargs),np.random.default_rng(seed) +stream_seed=a.reset_seed if a.reset_at>=0 and start_step>=a.reset_at else a.seed +sampler,rng=make_sampler(stream_seed) +def next_batch(): + c=int(rng.choice([512,1024,2048,a.sample_context],p=[.1,.15,.35,.4])) + h=int(rng.choice([32,128,512,1024],p=[.1,.2,.2,.5])) + x,y,p=sampler.sample(a.batch,c,h) + return x[:,-model.max_context:].copy(),y,p +pool=ThreadPoolExecutor(1) +if a.resume: + recovery=torch.load(a.resume,map_location='cpu',weights_only=False) + rng.bit_generator.state=recovery['batch_rng_state'];sampler.rng.bit_generator.state=recovery['sampler_rng_state'] + for name,state in recovery.get('sampler_rng_states',{}).items():getattr(sampler,name).bit_generator.state=state + torch.set_rng_state(recovery['torch_rng_state']);torch.cuda.set_rng_state_all(recovery['cuda_rng_state']) + pending=recovery['prefetched_batch'];del recovery + future=pool.submit(lambda:pending) +else:future=pool.submit(next_batch) +parameters=sum(p.numel() for p in model.parameters()) +(out/'config.json').write_text(json.dumps({**vars(a),'model':model.config,'parameters':parameters},indent=2)) +print(json.dumps({'parameters':parameters,'starting_step':start_step,'stream_seed':stream_seed,'restored_complete_training_state':bool(a.resume)}),flush=True) +started=time.monotonic();losses=[] +def atomic_save(obj,path): + torch.save(obj,str(path)+'.tmp');os.replace(str(path)+'.tmp',path) +def save(step,include_selection_weights=True): + global future + pending_batch=future.result() + common={'config':model.config,'step':step,'args':vars(a),'lr_multipliers':multipliers, + 'parent_checkpoints':list(dict.fromkeys(lineage_parents+(teacher.checkpoints if teacher else [])+(experts.checkpoints if experts else [])))} + if include_selection_weights: + for prefix,state in [('step',model.state_dict()),('ema',ema)]: + atomic_save({**common,'model':state,'ema':prefix=='ema'},out/f'{prefix}{step:06d}.pt') + atomic_save({**common,'model':model.state_dict(),'optimizer':opt.state_dict(),'ema_state':ema, + 'prefetched_batch':pending_batch,'batch_rng_state':copy.deepcopy(rng.bit_generator.state), + 'sampler_rng_state':copy.deepcopy(sampler.rng.bit_generator.state), + 'sampler_rng_states':{name:copy.deepcopy(value.bit_generator.state) for name,value in vars(sampler).items() if isinstance(value,np.random.Generator)}, + 'torch_rng_state':torch.get_rng_state(),'cuda_rng_state':torch.cuda.get_rng_state_all()},out/'recovery.pt') + future=pool.submit(lambda:pending_batch) +for step in range(start_step+1,a.steps+1): + if a.reset_at>=0 and step==a.reset_at+1 and start_step=a.halt_after) + selection_checkpoint=step%a.save_every==0 or step==a.steps or stop + # Persist a complete state before a fresh/resumed job warms its remaining compiled shapes. + if selection_checkpoint or step%a.recovery_every==0 or step==start_step+1: + save(step,include_selection_weights=selection_checkpoint) + if stop:break +pool.shutdown() +print(json.dumps({'completed_step':step,'training_process_loop_seconds':time.monotonic()-started}),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/watch_matched_cutoffs.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/watch_matched_cutoffs.py new file mode 100644 index 0000000000000000000000000000000000000000..3bd2f95022f87dbe1c349575c0ec77662a2d4d6e --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/recovery/watch_matched_cutoffs.py @@ -0,0 +1,34 @@ +"""Complete declared primary/durability comparisons; never select a model automatically.""" +import argparse,datetime,json,os,subprocess,time +from pathlib import Path +R=Path('/workspace/research');ap=argparse.ArgumentParser() +for key in ['run','control','evaluator','label']:ap.add_argument('--'+key,required=True) +ap.add_argument('--control-evaluator');ap.add_argument('--steps',default='6000,12000');a=ap.parse_args();start=time.monotonic() +receipt=R/(a.run+'_matched_cutoffs_receipt.json') +state=dict(pid=os.getpid(),status='running',run=a.run,control=a.control,steps=[],started_utc=datetime.datetime.now(datetime.timezone.utc).isoformat()) +def save(): + state['seconds']=time.monotonic()-start;tmp=receipt.with_suffix('.tmp');tmp.write_text(json.dumps(state,indent=2));os.replace(tmp,receipt) +def call(label,command): + state['status']=label;save();t=time.monotonic();result=subprocess.run(command);state['steps'].append(dict(label=label,returncode=result.returncode,seconds=time.monotonic()-t));save() + if result.returncode:state['status']='failed';save();raise SystemExit(result.returncode) +for step in map(int,a.steps.split(',')): + name=a.run+'_ema'+str(step);report=R/'evals'/name/'report.json';state['status']='waiting for main'+str(step);save() + while not report.exists(): + queue=R/(a.run+'_queue.json') + if queue.exists() and json.loads(queue.read_text()).get('status')=='failed':state['status']='training failed';save();raise SystemExit(1) + time.sleep(3) + time.sleep(1) + call('earlier cutoffs'+str(step),['python3',str(R/'evaluate_cutoffs.py'),'--name',name,'--weights',str(R/'runs'/a.run/f'ema{step:06d}.pt'),'--evaluator',a.evaluator,'--cutoffs','1,2,3']) + control_name=a.control+'_ema'+str(step) + if any(not (R/folder/control_name/'report.json').exists() for folder in ['evals','backcast_evals','backcast2_evals','backcast3_evals']): + assert a.control_evaluator,'Missing matched control reports; pass --control-evaluator for their declared evaluation' + call('control cutoffs'+str(step),['python3',str(R/'evaluate_cutoffs.py'),'--name',control_name,'--weights',str(R/'runs'/a.control/f'ema{step:06d}.pt'),'--evaluator',a.control_evaluator]) + out=R/(a.run+str(step//1000)+'k_four_cutoff_comparison.json') + if out.exists(): + cached=json.loads(out.read_text());assert cached['candidate']==name and cached['control']==a.control+'_ema'+str(step) and len(cached['rows'])==4 + for row,folder in zip(cached['rows'],['evals','backcast_evals','backcast2_evals','backcast3_evals']): + assert row['candidate_checkpoint']==json.loads((R/folder/name/'report.json').read_text())['checkpoint_sha256'] + assert row['control_checkpoint']==json.loads((R/folder/(a.control+'_ema'+str(step))/'report.json').read_text())['checkpoint_sha256'] + state['steps'].append(dict(label='reused verified matched comparison'+str(step),returncode=0,seconds=0));save();continue + call('matched comparison'+str(step),['python3',str(R/'recovery/matched_report.py'),'--candidate',name,'--control',a.control+'_ema'+str(step),'--label',a.label+' '+str(step)+' four-cutoff comparison','--cutoffs','0,1,2,3','--out',str(out),'--outcome',f'Declared comparison checkpoints {a.steps}. No transfer formula or automatic publication is selected by this controller.']) +state['status']='complete; research review required';save();print(json.dumps(state),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_dispersion/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_dispersion/check.py new file mode 100644 index 0000000000000000000000000000000000000000..c18b58905262b5ac8df12ab86f2f03e5ce285356 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_dispersion/check.py @@ -0,0 +1,101 @@ +"""E119 exact initialization and independent seasonal dispersion arithmetic.""" +import argparse +import hashlib +import importlib.util +import json +import sys +import time +from pathlib import Path +import numpy as np +import torch + +R=Path('/workspace/research') +sys.path.insert(0,str(R/'seasonal_dispersion')) +from model import DirectForecaster,centered_seasonal_difference,loss_fn +from data import Sampler +ap=argparse.ArgumentParser();ap.add_argument('--gpu',action='store_true');a=ap.parse_args() +torch.set_num_threads(2);torch.manual_seed(577);started=time.monotonic() +spec=importlib.util.spec_from_file_location('dispersion_control',R/'long_seasonal/model.py') +code=importlib.util.module_from_spec(spec);spec.loader.exec_module(code) +parent_path=R/'long_seasonal_initial.pt';parent=torch.load(parent_path,map_location='cpu',weights_only=False) +config=dict(parent['config'],seasonal_dispersion_features=True) +candidate=DirectForecaster(**config) +missing,unexpected=candidate.load_state_dict(parent['model'],strict=False) +assert missing==['dispersion_query.weight'] and not unexpected +assert torch.count_nonzero(candidate.dispersion_query.weight)==0 +assert all(torch.equal(v,candidate.state_dict()[k]) for k,v in parent['model'].items()) +assert all(p.requires_grad for p in candidate.parameters()) +control=code.DirectForecaster(**parent['config']);control.load_state_dict(parent['model']) +assert (R/'seasonal_dispersion/data.py').read_bytes()==(R/'long_seasonal/data.py').read_bytes() + +if a.gpu: + import fcntl + lock=open(R/'.evaluation.lock','a');fcntl.flock(lock,fcntl.LOCK_EX) + torch.backends.cuda.matmul.allow_tf32=False + candidate,control=candidate.cuda(),control.cuda() + rng=np.random.default_rng(587) + ctx=torch.tensor(rng.normal(size=(8,512)).astype(np.float32),device='cuda');ctx[0,:23]=float('nan');ctx[1]=0 + periods=torch.tensor([[24,168],[7,365],[12,1],[52,1],[4,1],[1,1],[96,672],[2,14]],device='cuda') + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16): + expected=control(ctx,periods,128);actual=candidate(ctx,periods,128) + assert all(torch.equal(v,w) for v,w in zip(expected,actual)) + del control,ctx,periods,expected,actual + torch.cuda.empty_cache();torch.cuda.reset_peak_memory_stats() + sampler=Sampler(R/'packed_sample',seed=587,source_weights_from=R/'packed_sample') + tensors=[torch.from_numpy(v).cuda() for v in sampler.sample(64,4096,1024)] + placeholders=[torch.zeros_like(p) for p in candidate.parameters() for _ in range(3)] + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(candidate,*tensors,paired=True) + loss.backward();assert torch.isfinite(loss) + assert all(p.grad is not None and torch.isfinite(p.grad).all() for p in candidate.parameters()) + keys=['dispersion_query.weight','long_query.weight','long_head.weight','head.weight'] + gradients={k:float(dict(candidate.named_parameters())[k].grad.norm()) for k in keys} + assert all(v>0 for v in gradients.values()) + result=dict(seed=587,gpu_initial_function_bitwise_equal=True,max_shape=[64,4096,1024], + loss=float(loss.detach()),selected_gradient_norms=gradients,all_parameters_trainable=True, + reserved_mib=torch.cuda.max_memory_reserved()/2**20,allocated_mib=torch.cuda.max_memory_allocated()/2**20, + includes_ema_and_adam_placeholders=True,seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False) + (R/'seasonal_dispersion_gpu_checks.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));raise SystemExit() + +rng=np.random.default_rng(577) +z=rng.normal(size=(6,128)).astype(np.float32);valid=rng.random(z.shape)>.12 +valid[4]=False;z[5]=0;z[~valid]=0 +periods=np.array([[4,7],[2,3],[12,1],[24,168],[4,8],[4,8]],dtype=np.int64) +delta,extra,dispersion=centered_seasonal_difference(torch.from_numpy(z),torch.from_numpy(valid),torch.from_numpy(periods),29) +old_delta,old_extra=code.centered_seasonal_difference(torch.from_numpy(z),torch.from_numpy(valid),torch.from_numpy(periods),29) +assert torch.equal(delta,old_delta) and torch.equal(extra,old_extra) +expected=np.zeros((6,29,4),dtype=np.float32) +for row in range(6): + for j,period in enumerate(periods[row]): + for t in range(29): + observations,recent=[],[] + for cycle in range(16): + end=max(0,128-cycle*period);start=max(0,128-(cycle+1)*period) + index=128-period+t%period-cycle*period + if index<0 or not valid[row,index]:continue + centered=float(z[row,index])-z[row,start:end][valid[row,start:end]].mean(dtype=np.float64) + observations.append(centered) + if cycle<4:recent.append(centered) + if period>=2 and len(observations)>=8 and len(recent)>=2: + expected[row,t,2*j]=np.log1p(np.std(recent,ddof=1)) + expected[row,t,2*j+1]=np.log1p(np.std(observations,ddof=1)) +assert np.max(np.abs(dispersion.numpy()-expected))<1e-6 +assert torch.isfinite(dispersion).all() and torch.count_nonzero(dispersion[4:])==0 +z0=torch.tensor(rng.normal(size=(1,64)).astype(np.float32));offsets=torch.tensor(rng.normal(size=(1,16,1)).astype(np.float32)) +z1=(z0.view(1,16,4)+offsets).view(1,64);p=torch.tensor([[4,4]]);ones=torch.ones_like(z0,dtype=torch.bool) +v0=centered_seasonal_difference(z0,ones,p,16)[2];v1=centered_seasonal_difference(z1,ones,p,16)[2] +assert torch.max(torch.abs(v0-v1))<1e-6 +for c,h in [(32,6),(128,29),(512,128)]: + ctx=torch.tensor(rng.normal(size=(6,c)).astype(np.float32));ctx[0,:c//3]=float('nan');ctx[1]=0;ctx[2]=float('nan') + with torch.inference_mode():expected=control(ctx,torch.from_numpy(periods),h);actual=candidate(ctx,torch.from_numpy(periods),h) + assert all(torch.equal(v,w) for v,w in zip(expected,actual)) +out=R/'seasonal_dispersion_initial.pt';assert not out.exists() +checkpoint=dict(model=candidate.state_dict(),config=config,step=0,args=dict(packed=str(R/'packed_sample'),seed=577), + parent_checkpoints=[str(parent_path)],conversion=dict(method='zero-initialized phase-specific cycle-centered standard-deviation query', + parent_sha256=hashlib.sha256(parent_path.read_bytes()).hexdigest(),initial_function_bitwise_equal=True)) +torch.save(checkpoint,out) +result=dict(seed=577,independent_feature_arithmetic=True,centered_cycle_offset_invariance=True, + old_features_bitwise_equal=True,initial_function_bitwise_equal=True,inherited_weights_bitwise_equal=True, + all_parameters_trainable=True,sampler_byte_identical=True,added_parameters=candidate.dispersion_query.weight.numel(), + total_parameters=sum(p.numel() for p in candidate.parameters()),checkpoint_sha256=hashlib.sha256(out.read_bytes()).hexdigest(), + seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False) +(R/'seasonal_dispersion_checks.json').write_text(json.dumps(result,indent=2));print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_dispersion/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_dispersion/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_dispersion/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_dispersion/durability.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_dispersion/durability.py new file mode 100644 index 0000000000000000000000000000000000000000..41afa5f1fbc5794764bfee688e8e0ae52d2b82e3 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_dispersion/durability.py @@ -0,0 +1,20 @@ +"""E119 final durability and the predeclared conditional E128 transfer12000.""" +import json,os,subprocess,time +from pathlib import Path +R=Path('/workspace/research');start=time.monotonic();receipt=R/'seasonal_dispersion_durability_receipt.json' +state=dict(pid=os.getpid(),status='waiting for final12000 main report',steps=[]) +def save(): + state['seconds']=time.monotonic()-start;tmp=receipt.with_suffix('.tmp');tmp.write_text(json.dumps(state,indent=2));os.replace(tmp,receipt) +def call(label,command): + state['status']=label;save();t=time.monotonic();subprocess.run(command,check=True);state['steps'].append(dict(label=label,seconds=time.monotonic()-t));save() +save() +while not (R/'evals/seasonal_dispersion_ema12000/report.json').exists():time.sleep(3) +time.sleep(1) +call('earlier final cutoffs',['python3',str(R/'evaluate_cutoffs.py'),'--name','seasonal_dispersion_ema12000','--weights',str(R/'runs/seasonal_dispersion/ema012000.pt'),'--evaluator',str(R/'seasonal_dispersion_inference/evaluate.py'),'--cutoffs','1,2,3']) +call('matched final comparison',['python3',str(R/'recovery/matched_report.py'),'--candidate','seasonal_dispersion_ema12000','--control','long_seasonal_ema12000','--label','E119 dispersion12000 durability','--cutoffs','0,1,2,3','--out',str(R/'seasonal_dispersion12k_comparison.json'),'--outcome','Predeclared E12812000 transfer requires at least3of4 positive and positive mean; no coefficient selection.']) +result=json.loads((R/'seasonal_dispersion12k_comparison.json').read_text());state['matched_gate_passed']=result['positive_cutoffs']>=3 and result['mean_delta']>0;save() +if not state['matched_gate_passed']: + state['status']='complete; matched gate failed, no12000 transfer';save();raise SystemExit() +call('fixed matched merge12000',['python3',str(R/'seasonal_dispersion_transfer/merge.py'),'--base',str(R/'long_seasonal_transfer12k.pt'),'--candidate',str(R/'runs/seasonal_dispersion/ema012000.pt'),'--control',str(R/'runs/long_seasonal/ema012000.pt'),'--out',str(R/'seasonal_dispersion_transfer12k.pt')]) +call('fixed12000 standalone and ensemble diagnostics',['python3',str(R/'seasonal_dispersion_transfer/run12.py')]) +state['status']='complete; review ensemble gate';save();print(json.dumps(state),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_dispersion/launch.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_dispersion/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..4d8da258bf409fff7e3f5f62fa820bf333e9a2f7 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_dispersion/launch.py @@ -0,0 +1,42 @@ +"""Queue E119 after the jointly trained phase-feature comparison finishes.""" +def main(): + import json + import os + import subprocess + from pathlib import Path + R = Path('/workspace/research') + checks = json.loads((R/'seasonal_dispersion_checks.json').read_text()) + gpu = json.loads((R/'seasonal_dispersion_gpu_checks.json').read_text()) + assert checks['initial_function_bitwise_equal'] and checks['sampler_byte_identical'] + assert checks['independent_feature_arithmetic'] and checks['all_parameters_trainable'] + assert gpu['gpu_initial_function_bitwise_equal'] and gpu['all_parameters_trainable'] + assert gpu['optimizer_updates'] == 0 and not gpu['validation_data_read'] + name = 'seasonal_dispersion' + run = R/'runs'/name + packed = R/'packed_sample' + env = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1') + command = ['python3', str(R/'recovery/train.py'), '--code-dir', str(R/name), + '--packed', str(packed), '--source-weights-from', str(packed), '--out', str(run), + '--initialize-from', str(R/'seasonal_dispersion_initial.pt'), '--steps', '12000', + '--batch', '64', '--lr', '.00002', '--seed', '197', '--loss-mode', 'paired', + '--stop-file', str(R/(name+'.stop'))] + assert command[command.index('--out')+1] == str(run) + with (R/(name+'_queue.log')).open('w') as qlog, (R/(name+'_watch.log')).open('w') as wlog: + queued = subprocess.Popen(['python3',str(R/'queued_train.py'), + '--label','E119 learned phase-specific dispersion seed197', + '--log',str(R/(name+'_train.log')),'--receipt',str(R/(name+'_queue.json')), + '--wait-pid','16340','--require-checkpoint',str(R/'runs/phase_joint/ema012000.pt'), + '--',*command], stdout=qlog,stderr=subprocess.STDOUT,env=env) + watch = subprocess.Popen(['python3',str(R/'watch_evaluate.py'),'--run',str(run), + '--evaluator',str(R/'seasonal_dispersion_inference/evaluate.py'),'--name',name, + '--expected-packed',str(packed),'--steps','1000,3000,6000,12000'], + stdout=wlog,stderr=subprocess.STDOUT,env=env) + print(json.dumps({'queue_pid':queued.pid,'watch_pid':watch.pid}),flush=True) + result = queued.wait() + if result: + watch.terminate() + watch.wait() + raise SystemExit(result) + +if __name__ == '__main__': + main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_dispersion/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_dispersion/model.py new file mode 100644 index 0000000000000000000000000000000000000000..79839282b194492635d02db0867c0db60200ee03 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_dispersion/model.py @@ -0,0 +1,268 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + + +def centered_seasonal_difference(z, valid, periods, horizon): + b, c = z.shape + time = torch.arange(horizon, device=z.device)[None, :] + sums = F.pad((z * valid).cumsum(-1), (1, 0)) + counts = F.pad(valid.float().cumsum(-1), (1, 0)) + deltas, extras, dispersion = [], [], [] + for j in range(2): + period = periods[:, j:j+1].clamp(min=1) + anchor = c - period + time % period + centered, masks = [], [] + for cycle in range(16): + end = (c - cycle * period).clamp(min=0, max=c) + start = (c - (cycle + 1) * period).clamp(min=0, max=c) + count = counts.gather(1, end) - counts.gather(1, start) + mean = (sums.gather(1, end) - sums.gather(1, start)) / count.clamp(min=1) + index = anchor - cycle * period + safe = index.clamp(min=0, max=c-1) + present = (index >= 0) & valid.gather(1, safe) + centered.append(z.gather(1, safe) - mean) + masks.append(present) + values = torch.stack(centered) + seen = torch.stack(masks) + n4 = seen[:4].sum(0) + n16 = seen.sum(0) + mean4 = (values[:4] * seen[:4]).sum(0) / n4.clamp(min=1) + mean16 = (values * seen).sum(0) / n16.clamp(min=1) + active = (period >= 2) & (n4 >= 2) & (n16 >= 8) + delta = torch.where(active, mean16 - mean4, 0.) + support = torch.where(active, n16.float() / 16, 0.) + deltas.append(delta) + extras.extend([delta, support]) + variance4 = (((values[:4] - mean4).square() * seen[:4]).sum(0) / (n4 - 1).clamp(min=1)) + variance16 = (((values - mean16).square() * seen).sum(0) / (n16 - 1).clamp(min=1)) + dispersion.extend([torch.where(active, variance4.sqrt().log1p(), 0.), + torch.where(active, variance16.sqrt().log1p(), 0.)]) + return torch.stack(deltas, -1), torch.stack(extras, -1), torch.stack(dispersion, -1) + + + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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,long_seasonal_features=True,seasonal_dispersion_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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,long_seasonal_features=long_seasonal_features,seasonal_dispersion_features=seasonal_dispersion_features) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + self.long_query=nn.Linear(patch*4,d,bias=False) if long_seasonal_features else None + self.long_head=nn.Linear(d,patch*2) if long_seasonal_features else None + if long_seasonal_features: + nn.init.zeros_(self.long_query.weight) + nn.init.zeros_(self.long_head.weight);nn.init.zeros_(self.long_head.bias) + assert long_seasonal_features or not seasonal_dispersion_features + self.dispersion_query=nn.Linear(patch*4,d,bias=False) if seasonal_dispersion_features else None + if self.dispersion_query is not None:nn.init.zeros_(self.dispersion_query.weight) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + if self.long_query is not None:long_delta,long_extra,dispersion_extra=centered_seasonal_difference(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + hidden=self.norm(q) + out=self.head(hidden).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + if self.long_head is not None: + gates=self.long_head(hidden).view(b,h,2).float().tanh() + median=median+(gates*long_delta).sum(-1) + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_width/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_width/check.py new file mode 100644 index 0000000000000000000000000000000000000000..a7fc656ca584892be9a9602177757199b5d2004f --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_width/check.py @@ -0,0 +1,84 @@ +"""E129 unchanged initialization and direct bounded-width arithmetic checks.""" +import argparse,hashlib,importlib.util,json,math,sys,time +from pathlib import Path +import numpy as np +import torch +R=Path('/workspace/research');sys.path.insert(0,str(R/'seasonal_width')) +from model import DirectForecaster,centered_seasonal_difference,seasonal_width_multiplier,loss_fn +from data import Sampler +ap=argparse.ArgumentParser();ap.add_argument('--gpu',action='store_true');a=ap.parse_args() +torch.set_num_threads(2);torch.manual_seed(661);started=time.monotonic() +spec=importlib.util.spec_from_file_location('seasonal_width_control',R/'seasonal_dispersion/model.py');code=importlib.util.module_from_spec(spec);spec.loader.exec_module(code) +parent_path=R/'seasonal_dispersion_initial.pt';parent=torch.load(parent_path,map_location='cpu',weights_only=False) +config=dict(parent['config'],seasonal_width_features=True) +candidate=DirectForecaster(**config);missing,unexpected=candidate.load_state_dict(parent['model'],strict=False) +assert set(missing)=={'width_head.weight','width_head.bias'} and not unexpected +assert all(torch.count_nonzero(candidate.state_dict()[k])==0 for k in missing) +assert all(torch.equal(v,candidate.state_dict()[k]) for k,v in parent['model'].items()) +assert all(p.requires_grad for p in candidate.parameters()) +assert (R/'seasonal_width/data.py').read_bytes()==(R/'seasonal_dispersion/data.py').read_bytes() +assert (R/'seasonal_width/model.py').read_bytes()==(R/'seasonal_width_inference/model.py').read_bytes() +control=code.DirectForecaster(**parent['config']);control.load_state_dict(parent['model']) +if a.gpu: + import fcntl + lock=open(R/'.evaluation.lock','a');tick=time.monotonic();fcntl.flock(lock,fcntl.LOCK_EX);wait=time.monotonic()-tick + torch.backends.cuda.matmul.allow_tf32=False + candidate,control=candidate.cuda(),control.cuda();rng=np.random.default_rng(673) + ctx=torch.tensor(rng.normal(size=(8,512)).astype(np.float32),device='cuda');ctx[0,:23]=float('nan');ctx[1]=0 + periods=torch.tensor([[24,168],[7,365],[12,1],[52,1],[4,1],[1,1],[96,672],[2,14]],device='cuda') + target=torch.tensor(rng.normal(size=(8,128)).astype(np.float32),device='cuda') + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16): + expected=control(ctx,periods,128);actual=candidate(ctx,periods,128) + loss0=code.loss_fn(control,ctx,target,periods,paired=True);loss1=loss_fn(candidate,ctx,target,periods,paired=True) + assert all(torch.equal(v,w) for v,w in zip(expected,actual)) and torch.equal(loss0,loss1) + del control,ctx,target,periods,expected,actual,loss0,loss1 + torch.cuda.empty_cache();torch.cuda.reset_peak_memory_stats();free_before=torch.cuda.mem_get_info()[0]/2**20 + sampler=Sampler(R/'packed_sample',seed=673,source_weights_from=R/'packed_sample') + tensors=[torch.from_numpy(v).cuda() for v in sampler.sample(64,4096,1024)] + placeholders=[torch.zeros_like(p) for p in candidate.parameters() for _ in range(3)] + with torch.autocast('cuda',dtype=torch.bfloat16):loss=loss_fn(candidate,*tensors,paired=True) + loss.backward();assert torch.isfinite(loss) + assert all(p.grad is not None and torch.isfinite(p.grad).all() for p in candidate.parameters()) + gradients={k:float(dict(candidate.named_parameters())[k].grad.norm()) for k in ['width_head.weight','width_head.bias','dispersion_query.weight','long_head.weight','head.weight']} + assert all(v>0 for v in gradients.values()) + result=dict(seed=673,gpu_initial_function_bitwise_equal=True,gpu_initial_loss_bitwise_equal=True,max_shape=[64,4096,1024],loss=float(loss.detach()),selected_gradient_norms=gradients,all_parameters_trainable=True,reserved_mib=torch.cuda.max_memory_reserved()/2**20,allocated_mib=torch.cuda.max_memory_allocated()/2**20,free_before_mib=free_before,includes_ema_and_adam_placeholders=True,lock_wait_seconds=wait,seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False) + (R/'seasonal_width_gpu_checks.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));raise SystemExit() +rng=np.random.default_rng(661);z=rng.normal(size=(6,128)).astype(np.float32);valid=rng.random(z.shape)>.12;valid[4]=False;z[5]=0;z[~valid]=0 +periods=np.array([[4,7],[2,3],[12,1],[24,168],[4,8],[4,8]],dtype=np.int64) +tensors=[torch.from_numpy(x) for x in [z,valid,periods]] +actual=centered_seasonal_difference(*tensors,29);old=code.centered_seasonal_difference(*tensors,29) +assert all(torch.equal(v,w) for v,w in zip(actual[:3],old)) +expected=np.zeros((6,29,2),dtype=np.float32) +for row in range(6): + for j,period in enumerate(periods[row]): + for t in range(29): + observations=[];recent=0 + for cycle in range(16): + end=max(0,128-cycle*period);start=max(0,128-(cycle+1)*period);index=128-period+t%period-cycle*period + if index<0 or not valid[row,index]:continue + observations.append(float(z[row,index])-z[row,start:end][valid[row,start:end]].mean(dtype=np.float64)) + if cycle<4:recent+=1 + if period>=2 and len(observations)>=8 and recent>=2:expected[row,t,j]=np.log1p(np.std(observations,ddof=1))-np.log(2.) +assert np.max(np.abs(actual[3].numpy()-expected))<1e-6 +assert torch.count_nonzero(actual[3][4])==0 and torch.all(actual[3][5]==-math.log(2.)) +raw=rng.normal(size=expected.shape).astype(np.float32)*30 +factor=seasonal_width_multiplier(torch.from_numpy(raw),actual[3]).numpy() +reference=np.exp(np.clip((np.tanh(raw)*expected).sum(-1),-np.log(4.),np.log(4.))) +assert np.max(np.abs(factor-reference))<1e-6 and np.all((factor>=.25)&(factor<=4)) +for c,h in [(32,6),(128,29),(512,128)]: + ctx=torch.tensor(rng.normal(size=(6,c)).astype(np.float32));ctx[0,:c//3]=float('nan');ctx[1]=0;ctx[2]=float('nan') + with torch.inference_mode():q0,mu0,s0=control(ctx,torch.from_numpy(periods),h);q1,mu1,s1=candidate(ctx,torch.from_numpy(periods),h) + assert torch.equal(q0,q1) and torch.equal(mu0,mu1) and torch.equal(s0,s1) + with torch.no_grad():candidate.width_head.bias.view(16,2)[:]=torch.tensor([2.,-.7]) + with torch.inference_mode():q2,_,_=candidate(ctx,torch.from_numpy(periods),h) + zz,v,_,_=candidate.standardize(ctx);wd=centered_seasonal_difference(zz,v,torch.from_numpy(periods),h)[3] + multiplier=seasonal_width_multiplier(torch.tensor([2.,-.7]).expand(6,h,2),wd) + wanted=q0[:,:,4,None]+(q0-q0[:,:,4,None])*multiplier[:,:,None] + assert torch.max(torch.abs(q2-wanted))<2e-6 and torch.equal(q0[:,:,4],q2[:,:,4]) + assert torch.isfinite(q2).all() and torch.all(q2[:,:,1:]>=q2[:,:,:-1]) + with torch.no_grad():candidate.width_head.bias.zero_() +out=R/'seasonal_width_initial.pt';assert not out.exists() +checkpoint=dict(model=candidate.state_dict(),config=config,step=0,args=dict(packed=str(R/'packed_sample'),seed=661),parent_checkpoints=[str(parent_path)],conversion=dict(method='zero-initialized direct seasonal width head',parent_sha256=hashlib.sha256(parent_path.read_bytes()).hexdigest(),initial_function_bitwise_equal=True)) +torch.save(checkpoint,out) +result=dict(seed=661,initial_function_bitwise_equal=True,inherited_features_and_weights_bitwise_equal=True,independent_width_arithmetic=True,bounded_multiplier=[.25,4.],unchanged_median_for_fixed_hidden=True,finite_ordered=True,sampler_byte_identical=True,all_parameters_trainable=True,added_parameters=sum(v.numel() for v in candidate.width_head.parameters()),total_parameters=sum(p.numel() for p in candidate.parameters()),checkpoint_sha256=hashlib.sha256(out.read_bytes()).hexdigest(),seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False) +(R/'seasonal_width_checks.json').write_text(json.dumps(result,indent=2));print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_width/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_width/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_width/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_width/launch.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_width/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..4ab2570be7d55f94acc25ee268dd91c2e1f0f6cb --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_width/launch.py @@ -0,0 +1,42 @@ +"""Queue E129 after the older-history seasonal comparison finishes.""" +def main(): + import json + import os + import subprocess + from pathlib import Path + R = Path('/workspace/research') + checks = json.loads((R/'seasonal_width_checks.json').read_text()) + gpu = json.loads((R/'seasonal_width_gpu_checks.json').read_text()) + assert checks['initial_function_bitwise_equal'] and checks['sampler_byte_identical'] + assert checks['independent_width_arithmetic'] and checks['all_parameters_trainable'] + assert gpu['gpu_initial_function_bitwise_equal'] and gpu['all_parameters_trainable'] + assert gpu['optimizer_updates'] == 0 and not gpu['validation_data_read'] + name = 'seasonal_width' + run = R/'runs'/name + packed = R/'packed_sample' + env = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1') + command = ['python3', str(R/'recovery/train.py'), '--code-dir', str(R/name), + '--packed', str(packed), '--source-weights-from', str(packed), '--out', str(run), + '--initialize-from', str(R/'seasonal_width_initial.pt'), '--steps', '12000', + '--batch', '64', '--lr', '.00002', '--seed', '197', '--loss-mode', 'paired', + '--stop-file', str(R/(name+'.stop'))] + assert command[command.index('--out')+1] == str(run) + with (R/(name+'_queue.log')).open('w') as qlog, (R/(name+'_watch.log')).open('w') as wlog: + queued = subprocess.Popen(['python3',str(R/'queued_train.py'), + '--label','E129 direct learned seasonal uncertainty head seed197', + '--log',str(R/(name+'_train.log')),'--receipt',str(R/(name+'_queue.json')), + '--wait-pid','20306','--require-checkpoint',str(R/'runs/seasonal_history/ema012000.pt'), + '--',*command], stdout=qlog,stderr=subprocess.STDOUT,env=env) + watch = subprocess.Popen(['python3',str(R/'watch_evaluate.py'),'--run',str(run), + '--evaluator',str(R/'seasonal_width_inference/evaluate.py'),'--name',name, + '--expected-packed',str(packed),'--steps','1000,3000,6000,12000'], + stdout=wlog,stderr=subprocess.STDOUT,env=env) + print(json.dumps({'queue_pid':queued.pid,'watch_pid':watch.pid}),flush=True) + result = queued.wait() + if result: + watch.terminate() + watch.wait() + raise SystemExit(result) + +if __name__ == '__main__': + main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_width/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_width/model.py new file mode 100644 index 0000000000000000000000000000000000000000..0fb76d7fe91edd7ea32a5e4cf8ea092b570edcfe --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_width/model.py @@ -0,0 +1,279 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + + +def centered_seasonal_difference(z, valid, periods, horizon): + b, c = z.shape + time = torch.arange(horizon, device=z.device)[None, :] + sums = F.pad((z * valid).cumsum(-1), (1, 0)) + counts = F.pad(valid.float().cumsum(-1), (1, 0)) + deltas, extras, dispersion, width_deltas = [], [], [], [] + for j in range(2): + period = periods[:, j:j+1].clamp(min=1) + anchor = c - period + time % period + centered, masks = [], [] + for cycle in range(16): + end = (c - cycle * period).clamp(min=0, max=c) + start = (c - (cycle + 1) * period).clamp(min=0, max=c) + count = counts.gather(1, end) - counts.gather(1, start) + mean = (sums.gather(1, end) - sums.gather(1, start)) / count.clamp(min=1) + index = anchor - cycle * period + safe = index.clamp(min=0, max=c-1) + present = (index >= 0) & valid.gather(1, safe) + centered.append(z.gather(1, safe) - mean) + masks.append(present) + values = torch.stack(centered) + seen = torch.stack(masks) + n4 = seen[:4].sum(0) + n16 = seen.sum(0) + mean4 = (values[:4] * seen[:4]).sum(0) / n4.clamp(min=1) + mean16 = (values * seen).sum(0) / n16.clamp(min=1) + active = (period >= 2) & (n4 >= 2) & (n16 >= 8) + delta = torch.where(active, mean16 - mean4, 0.) + support = torch.where(active, n16.float() / 16, 0.) + deltas.append(delta) + extras.extend([delta, support]) + variance4 = (((values[:4] - mean4).square() * seen[:4]).sum(0) / (n4 - 1).clamp(min=1)) + variance16 = (((values - mean16).square() * seen).sum(0) / (n16 - 1).clamp(min=1)) + width_deltas.append(torch.where(active, variance16.sqrt().log1p() - math.log(2.), 0.)) + dispersion.extend([torch.where(active, variance4.sqrt().log1p(), 0.), + torch.where(active, variance16.sqrt().log1p(), 0.)]) + return torch.stack(deltas, -1), torch.stack(extras, -1), torch.stack(dispersion, -1), torch.stack(width_deltas, -1) + + + +def seasonal_width_multiplier(raw, delta): + return ((raw.float().tanh() * delta).sum(-1).clamp(-math.log(4.), math.log(4.))).exp() + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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,long_seasonal_features=True,seasonal_dispersion_features=True,seasonal_width_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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,long_seasonal_features=long_seasonal_features,seasonal_dispersion_features=seasonal_dispersion_features,seasonal_width_features=seasonal_width_features) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + self.long_query=nn.Linear(patch*4,d,bias=False) if long_seasonal_features else None + self.long_head=nn.Linear(d,patch*2) if long_seasonal_features else None + if long_seasonal_features: + nn.init.zeros_(self.long_query.weight) + nn.init.zeros_(self.long_head.weight);nn.init.zeros_(self.long_head.bias) + assert long_seasonal_features or not seasonal_dispersion_features + self.dispersion_query=nn.Linear(patch*4,d,bias=False) if seasonal_dispersion_features else None + if self.dispersion_query is not None:nn.init.zeros_(self.dispersion_query.weight) + assert seasonal_dispersion_features or not seasonal_width_features + self.width_head=nn.Linear(d,patch*2) if seasonal_width_features else None + if self.width_head is not None: + nn.init.zeros_(self.width_head.weight);nn.init.zeros_(self.width_head.bias) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + if self.long_query is not None:long_delta,long_extra,dispersion_extra,width_delta=centered_seasonal_difference(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + hidden=self.norm(q) + out=self.head(hidden).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + if self.long_head is not None: + gates=self.long_head(hidden).view(b,h,2).float().tanh() + median=median+(gates*long_delta).sum(-1) + widths=F.softplus(out[:,:,10:]).clamp(max=20) + if self.width_head is not None: + multiplier=seasonal_width_multiplier(self.width_head(hidden).view(b,h,2),width_delta) + widths=widths*multiplier[:,:,None] + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_width_transfer/assemble.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_width_transfer/assemble.py new file mode 100644 index 0000000000000000000000000000000000000000..91bcb5ee6127595d7a2a32cfca638ebd8f2b533d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_width_transfer/assemble.py @@ -0,0 +1,12 @@ +"""Assemble only a width-treatment candidate that passed its declared diagnostics.""" +import argparse,json,subprocess +from pathlib import Path +R=Path('/workspace/research');ap=argparse.ArgumentParser();ap.add_argument('--duration',type=int,choices=[6,12],required=True);a=ap.parse_args();d=a.duration +selection=json.loads((R/'seasonal_width_transfer_receipt.json').read_text());result=next(v for v in selection['results'] if v['duration']==d);assert result['selection_gate_passed'] and result['positive_cutoffs']>=3 and result['mean_delta']>0 +command=['python3',str(R/'publish_full_paired.py'),'--weights',str(R/f'seasonal_width_transfer{d}k.pt'),'--report',str(R/'evals'/f'seasonal_width_transfer{d}k/report.json'),'--runtime-dir',str(R/'seasonal_width_inference'),'--out',str(R/f'candidate-width-transfer{d}k')] +for name in ['postloss','long_memory_synth','overflow_control','weekly_synth','spectral_synth','spectral_transfer','long_seasonal','seasonal_dispersion','seasonal_width','seasonal_width_transfer']:command+=['--extra-training-code',name] +subprocess.run(command,check=True) +command=['python3',str(R/'four_member_ensemble/publish.py')] +for name in [f'candidate-width-transfer{d}k','candidate-patch8-6k-complete','candidate-split-patch-12k-complete','candidate-fresh146m-48k']:command+=['--member',str(R/name)] +command+=['--out',str(R/f'candidate-width{d}-ensemble')];subprocess.run(command,check=True) +subprocess.run(['python3',str(R/'seasonal_width_transfer/validate.py'),'--duration',str(d)],check=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_width_transfer/check_runtime.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_width_transfer/check_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..0b4b2787b2b3367603c9c0df2a5c7fc73a91988b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_width_transfer/check_runtime.py @@ -0,0 +1,23 @@ +"""New width member and quartet replay against unchanged E130 synthetic inputs/members.""" +import argparse,fcntl,hashlib,json,shutil,subprocess,sys,time +from pathlib import Path +import numpy as np +sys.path.insert(0,'/workspace/evaluation');from ts_io import read_prediction_file +R=Path('/workspace/research');ap=argparse.ArgumentParser();ap.add_argument('--duration',type=int,choices=[6,12],required=True);a=ap.parse_args();started=time.monotonic() +root=R/f'width{a.duration}_fixture';reference=R/'fresh_capacity4_fixture';package=R/f'candidate-width{a.duration}-ensemble';member=R/f'candidate-width-transfer{a.duration}k' +root.mkdir(exist_ok=True);shutil.copytree(reference/'input',root/'input',dirs_exist_ok=True) +for p in (root/'input').rglob('*'): + if p.is_file():assert hashlib.sha256(p.read_bytes()).digest()==hashlib.sha256((reference/'input'/p.relative_to(root/'input')).read_bytes()).digest() +descriptor=json.loads((package/'config.json').read_text());control=json.loads((R/'candidate-fresh-capacity4-ensemble/config.json').read_text());assert descriptor['members'][1:]==control['members'][1:] +lock=open(R/'.evaluation.lock','a');fcntl.flock(lock,fcntl.LOCK_EX) +for label,source,asset in [('standalone0',member,'weights.pt'),('ensemble',package,'config.json')]: + with (root/(label+'.log')).open('w') as log:subprocess.run(['python3',str(source/'predict.py'),str(root/'input'),str(root/label),'--weights',str(source/asset),'--batch','4'],stdout=log,stderr=subprocess.STDOUT,check=True) +rows=[] +for cfg in json.loads((root/'input/index.json').read_text())['configs']: + cid=cfg['config_id'];_,expected=read_prediction_file(root/'standalone0/cases'/(cid+'.h5'));expected=expected.copy() + for i in range(1,4):expected+=read_prediction_file(reference/f'standalone{i}/cases'/(cid+'.h5'))[1] + expected/=4;mean,actual=read_prediction_file(root/'ensemble/cases'/(cid+'.h5')) + assert np.array_equal(expected,actual) and np.array_equal(mean,actual[:,:,4]) and np.isfinite(actual).all() and np.all(np.diff(actual,axis=2)>=0) + rows.append(dict(config_id=cid,instances=cfg['n_instances'],bitwise_composition=True,finite_ordered=True)) +result=dict(duration=a.duration,descriptor_sha256=hashlib.sha256((package/'config.json').read_bytes()).hexdigest(),members=[v['weights_sha256'] for v in descriptor['members']],checks=rows,unchanged_member_references_reused=str(reference),input_files_bitwise_identical=True,seconds=time.monotonic()-started) +(R/f'width{a.duration}_runtime_checks.json').write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_width_transfer/merge.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_width_transfer/merge.py new file mode 100644 index 0000000000000000000000000000000000000000..04b124b615cfba7243c3d938b8d7540bf3d2c01c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_width_transfer/merge.py @@ -0,0 +1,32 @@ +"""E139 transfer only the width-treatment difference, with two distinct zero extensions.""" +import argparse,hashlib,importlib.util,json,sys,time +from pathlib import Path +import numpy as np +import torch +R=Path('/workspace/research');ap=argparse.ArgumentParser() +for key in ['base','candidate','control','out']:ap.add_argument('--'+key,required=True) +a=ap.parse_args();torch.set_num_threads(2);torch.manual_seed(769);started=time.monotonic() +paths=[Path(a.base),Path(a.candidate),Path(a.control)];base,candidate,control=[torch.load(p,map_location='cpu',weights_only=False) for p in paths] +base_extra={'dispersion_query.weight','width_head.weight','width_head.bias'};control_extra={'width_head.weight','width_head.bias'} +assert set(candidate['model'])==set(base['model'])|base_extra==set(control['model'])|control_extra +c=dict(candidate['config']);assert c.pop('seasonal_width_features') is True;assert c==control['config'];assert c.pop('seasonal_dispersion_features') is True;assert c==base['config'] +sys.path.insert(0,str(R/'seasonal_width'));from model import DirectForecaster +extended=DirectForecaster(**candidate['config']);missing,unexpected=extended.load_state_dict(base['model'],strict=False) +assert set(missing)==base_extra and not unexpected and all(torch.count_nonzero(extended.state_dict()[k])==0 for k in base_extra) +spec=importlib.util.spec_from_file_location('width_transfer_base',R/'long_seasonal/model.py');module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module) +original=module.DirectForecaster(**base['config']);original.load_state_dict(base['model']);rng=np.random.default_rng(769);periods=torch.tensor([[24,168],[7,365],[52,1],[1,1]]) +for c,h in [(32,6),(512,128)]: + ctx=torch.tensor(rng.normal(size=(4,c)).astype(np.float32));ctx[0,:c//3]=float('nan');ctx[1]=0;ctx[2]=float('nan') + with torch.inference_mode():left=original(ctx,periods,h);right=extended(ctx,periods,h) + assert all(torch.equal(v,w) for v,w in zip(left,right)) +weights={k:v.clone() for k,v in extended.state_dict().items()} +for k in weights: + if k in control_extra:weights[k].copy_(candidate['model'][k]) + else:weights[k].add_(candidate['model'][k]-control['model'][k]) +assert all(torch.isfinite(v).all() for v in weights.values());extended.load_state_dict(weights) +with torch.inference_mode():quant,mu,scale=extended(ctx,periods,128) +assert torch.isfinite(quant).all() and torch.all(quant[:,:,1:]>=quant[:,:,:-1]) +out=Path(a.out);assert not out.exists() +conversion=dict(method='matched direct-width-head training delta, separately zero-extending base and control',formula='zero_extend(E117first)+E129-zero_extend(E119)',coefficient=1.,base_zero_parameters=sorted(base_extra),control_zero_parameters=sorted(control_extra),dispersion_query='candidate-minus-control only; no E128 correction',parent_hashes={str(p):hashlib.sha256(p.read_bytes()).hexdigest() for p in paths},base_extension_forward_bitwise_equal=True,finite_ordered_fixture=True,check_seed=769,seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False) +ck=dict(model=weights,config=candidate['config'],step=0,args=dict(packed=base['args']['packed']),parent_checkpoints=[str(p) for p in paths],conversion=conversion);torch.save(ck,out) +result=dict(conversion,checkpoint_sha256=hashlib.sha256(out.read_bytes()).hexdigest(),parameters=sum(v.numel() for v in weights.values()));out.with_suffix('.json').write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_width_transfer/promote.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_width_transfer/promote.py new file mode 100644 index 0000000000000000000000000000000000000000..5bfd16861ed4594c178012b066b2614104e505b5 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_width_transfer/promote.py @@ -0,0 +1,40 @@ +"""Publish an E139 candidate only after complete replay, exact composition and current-best checks.""" +import argparse,datetime,hashlib,json,os,subprocess +from pathlib import Path +R=Path('/workspace/research');ap=argparse.ArgumentParser();ap.add_argument('--duration',type=int,choices=[6,12],required=True);a=ap.parse_args();d=a.duration;name=f'width{d}_ensemble';package=R/f'candidate-width{d}-ensemble';report=R/f'valid-report-width{d}-ensemble.json' +read=lambda p:json.loads(p.read_text()) +result=read(report);suite=read(R/(name+'_validation_receipt.json'));selection=next(v for v in read(R/'seasonal_width_transfer_receipt.json')['results'] if v['duration']==d) +assert suite['status']=='complete' and all(x['returncode']==0 for x in suite['steps']) +assert selection['selection_gate_passed'] and selection['positive_cutoffs']>=3 and selection['mean_delta']>0 +relocation=read(R/(name+'_package_checks.json'));assert len(relocation)==1 and all(x['bitwise_equal_after_relocation'] and x['finite_and_monotone'] for x in relocation) +composition=read(R/(name+'_composition_checks.json'));assert len(composition['comparisons'])==3 and all(x['bitwise_equal_to_fixed_member_average'] for x in composition['comparisons']) +synthetic=read(R/f'width{d}_runtime_checks.json');assert len(synthetic['checks'])==2 and all(x['bitwise_composition'] and x['finite_ordered'] for x in synthetic['checks']) +validated=read(package/'model_manifest.json');assert validated['checkpoint_sha256']==synthetic['descriptor_sha256']==result['checkpoint_sha256'] +assert len(validated['members'])==4 and validated['ensemble_weights']==[.25]*4 and validated['pretrained_assets']==[] +old=read(Path('/workspace/submission/validation_report.json'));old_manifest=read(Path('/workspace/submission/model_manifest.json'));state=read(R/'CURRENT_RESEARCH_STATE.json');prior=state['published'] +assert old_manifest['checkpoint_sha256']==prior['checkpoint_sha256'] +assert result['n_failed']==0 and result['n_configs']==97 and result['n_instances']==151170 and result['skill_score']>old['skill_score'] +cutoffs=['valid_screen','valid_backcast','valid_backcast2','valid_backcast3'];probes=[read(R/(name+'_'+c+'.json')) for c in cutoffs] +current_skills=[prior['main_skill']]+prior['earlier_skills'];differences=[x['skill_score']-y for x,y in zip(probes,current_skills)] +assert len(differences)==4 and sum(x>0 for x in differences)>=3 and sum(differences)>0 +members=[R/f'candidate-width-transfer{d}k',R/'candidate-patch8-6k-complete',R/'candidate-split-patch-12k-complete',R/'candidate-fresh146m-48k'] +for i,source in enumerate(members): + m=read(source/'model_manifest.json');assert m['weights_sha256']==validated['members'][i]['weights_sha256'] and m['runtime_code_sha256']['model.py']==validated['runtime_code_sha256'][f'model{i}.py'] + assert (source/'provenance/recovery/schedules.py').exists() +for path in (R/'four_member_ensemble/runtime').iterdir(): + if path.name in validated['runtime_code_sha256']:assert hashlib.sha256(path.read_bytes()).hexdigest()==validated['runtime_code_sha256'][path.name] +comparison=read(R/(name+'_comparison.json')) +outcome=f"Matched width-treatment correction at {d*1000} steps improves full skill from {old['skill_score']:.12f} to {result['skill_score']:.12f}. All97configs151170instances pass. Inference {result['inference_seconds']:.3f}s on shared H100. Relocation and actual-member real/extreme synthetic composition are bitwise exact. Validation selection only, not held-out reward." +subprocess.run(['python3',str(R/'direct_v1/record.py'),str(report),'--label',f'E139 direct-width treatment{d*1000} equal-quarter full replay selected','--outcome',outcome],check=True) +with (R/'direct_v1/EXPERIMENTS.md').open('a') as f:f.write('\nE139 complete suite '+json.dumps(suite)+'. Synthetic checks '+json.dumps(synthetic)+'. Descriptive comparison '+json.dumps({k:v for k,v in comparison.items() if k!='configs'})+'. Current-publication diagnostic deltas '+json.dumps(differences)+'. Every member forecasts every instance. E101teacher and E138experts remain their immutable declared snapshots.\n') +command=['python3',str(R/'four_member_ensemble/publish.py')] +for source in members:command+=['--member',str(source)] +command+=['--report',str(report),'--out','/workspace/submission'];subprocess.run(command,check=True) +published=read(Path('/workspace/submission/model_manifest.json'));assert published['checkpoint_sha256']==validated['checkpoint_sha256'] and published['runtime_code_sha256']==validated['runtime_code_sha256'] +now=datetime.datetime.now(datetime.timezone.utc).isoformat();state=read(R/'CURRENT_RESEARCH_STATE.json');state.setdefault('previous_published',[]).append(state['published']) +state['published']=dict(experiment=f'E139 width-treatment{d*1000} firstmember/E71/E93/E79wide48000 equal quarters',package='/workspace/submission',checkpoint_sha256=result['checkpoint_sha256'],parameters=published['parameters'],main_skill=probes[0]['skill_score'],earlier_skills=[x['skill_score'] for x in probes[1:]],full_validation_skill=result['skill_score'],full_report=str(report),status='published after full replay and all checks',publisher=command[1],publisher_arguments=command[2:],published_utc=now,journal_refreshed_utc=now,validation_receipt=str(R/(name+'_validation_receipt.json')),package_checks=str(R/(name+'_package_checks.json')),composition_checks=str(R/(name+'_composition_checks.json')),synthetic_checks=str(R/f'width{d}_runtime_checks.json'),notes='Validation only. All members trained here; fixed equal quarters. E101teacher E96 and E138expert E130 snapshots stay immutable.') +state['selection_probes']['E139'].setdefault('duration_results',{})[str(d*1000)]=dict(status='published',full_skill=result['skill_score'],descriptor=result['checkpoint_sha256'],published_utc=now) +state['next_candidate']=dict(experiment='E132 final fourthmember, E139 width durability, E138 learned gate; active matched architecture/data studies',status='continue research') +p=R/'CURRENT_RESEARCH_STATE.json';tmp=p.with_suffix('.tmp');tmp.write_text(json.dumps(state,indent=2));os.replace(tmp,p) +with (R/'SESSION_20261023_PROGRESS.md').open('a') as f:f.write('\n'+now+': E139 width'+str(d*1000)+' atomically published. '+outcome+' Descriptor'+result['checkpoint_sha256']+'.\n') +print(json.dumps(dict(utc=now,skill=result['skill_score'],descriptor=result['checkpoint_sha256'],parameters=published['parameters'])),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_width_transfer/run.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_width_transfer/run.py new file mode 100644 index 0000000000000000000000000000000000000000..9f35156c37f33a35c2e6005cbfae1e6de2676101 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_width_transfer/run.py @@ -0,0 +1,36 @@ +"""E139 fixed width-treatment transfers at primary6k and conditional12k durability.""" +import datetime,hashlib,json,os,subprocess,time +from pathlib import Path +R=Path('/workspace/research');start=time.monotonic();receipt=R/'seasonal_width_transfer_receipt.json' +state=dict(pid=os.getpid(),status='running',steps=[],results=[],started_utc=datetime.datetime.now(datetime.timezone.utc).isoformat()) +def save(): + state['seconds']=time.monotonic()-start;tmp=receipt.with_suffix('.tmp');tmp.write_text(json.dumps(state,indent=2));os.replace(tmp,receipt) +def call(label,command): + state['status']=label;save();t=time.monotonic();result=subprocess.run(command);state['steps'].append(dict(label=label,returncode=result.returncode,seconds=time.monotonic()-t));save() + if result.returncode:state['status']='failed';save();raise SystemExit(result.returncode) +for duration in [6,12]: + step=duration*1000;comparison=R/f'seasonal_width{duration}k_four_cutoff_comparison.json';state['status']='waiting matched width gate'+str(duration);save() + while not comparison.exists():time.sleep(3) + time.sleep(1);d=json.loads(comparison.read_text());assert d['candidate']==f'seasonal_width_ema{step}' and d['control']==f'seasonal_dispersion_ema{step}' + if d['positive_cutoffs']<3 or d['mean_delta']<=0: + state['status']='complete; matched source gate failed'+str(duration);save() + with (R/'direct_v1/EXPERIMENTS.md').open('a') as f:f.write('\nE139source gate failed for'+str(duration)+'k; no additional transfer constructed. '+json.dumps(state)+'\n') + raise SystemExit() + name=f'seasonal_width_transfer{duration}k';weights=R/(name+'.pt') + if not weights.exists():call('literal matched merge'+str(duration),['python3',str(R/'seasonal_width_transfer/merge.py'),'--base',str(R/'long_seasonal_transfer12k.pt'),'--candidate',str(R/'runs/seasonal_width'/f'ema{step:06d}.pt'),'--control',str(R/'runs/seasonal_dispersion'/f'ema{step:06d}.pt'),'--out',str(weights)]) + merge=json.loads(weights.with_suffix('.json').read_text());assert hashlib.sha256(weights.read_bytes()).hexdigest()==merge['checkpoint_sha256'] + for parent,digest in merge['parent_hashes'].items():assert hashlib.sha256(Path(parent).read_bytes()).hexdigest()==digest + call('first member four cutoffs'+str(duration),['python3',str(R/'evaluate_cutoffs.py'),'--name',name,'--weights',str(weights),'--evaluator',str(R/'seasonal_width_inference/evaluate.py')]) + rows=[] + for cutoff,folder in [('valid_screen','evals'),('valid_backcast','backcast_evals'),('valid_backcast2','backcast2_evals'),('valid_backcast3','backcast3_evals')]: + call('record first '+str(duration)+' '+cutoff,['python3',str(R/'direct_v1/record.py'),str(R/folder/name/'report.json'),'--label',f'E139 width-treatment transfer{step} '+cutoff,'--outcome','Fixed zero-extended E117first + E129 - zero-extended E119, coefficient1. No E128dispersion correction; no optimizer update. Equal-quarter ensemble selected separately.']) + out=R/(f'width{duration}_ensemble_'+cutoff+'.json');command=['python3',str(R/'equal_ensemble_probe.py'),'--valid',str(R/cutoff),'--out',str(out)] + for member in [name,'patch8_ema6000','split_patch_ema12000','random_capacity_1024_ema48000']:command+=['--pred',str(R/folder/member)] + call('fixed equal quarters '+str(duration)+' '+cutoff,command) + a=json.loads(out.read_text());b=json.loads((R/('fresh_capacity4_ensemble_'+cutoff+'.json')).read_text()) + rows.append(dict(cutoff=cutoff,skill=a['skill_score'],control_skill=b['skill_score'],delta=a['skill_score']-b['skill_score'],groups=a['groups'],member_checkpoint_hashes=a['member_checkpoint_hashes'],cpu_seconds=a['cpu_seconds'])) + result=dict(duration=duration,rows=rows,positive_cutoffs=sum(v['delta']>0 for v in rows),mean_delta=sum(v['delta'] for v in rows)/4) + result['selection_gate_passed']=result['positive_cutoffs']>=3 and result['mean_delta']>0 + state['results'].append(result);save() + with (R/'direct_v1/EXPERIMENTS.md').open('a') as f:f.write('\nE139 fixed width-treatment equal-quarter ensemble diagnostics: '+json.dumps(result)+'. Full replay/runtime checks and comparison to current publication required before any promotion.\n') +state['status']='complete; research review required';save();print(json.dumps(state),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_width_transfer/validate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_width_transfer/validate.py new file mode 100644 index 0000000000000000000000000000000000000000..1cc073a620db92b2d7b1c3c564834d5ecf95f8ef --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/seasonal_width_transfer/validate.py @@ -0,0 +1,13 @@ +"""Full public replay and independent composition for E139; no automatic promotion.""" +import argparse,json,subprocess,time +from pathlib import Path +R=Path('/workspace/research');ap=argparse.ArgumentParser();ap.add_argument('--duration',type=int,choices=[6,12],required=True);a=ap.parse_args();d=a.duration;started=time.monotonic() +package=R/f'candidate-width{d}-ensemble';report=R/f'valid-report-width{d}-ensemble.json';pred=R/f'valid-pred-width{d}-ensemble';firstpred=R/f'composition-pred-width-transfer{d}k';receipt=R/f'width{d}_ensemble_validation_receipt.json' +steps=[('synthetic_composition',['python3',str(R/'seasonal_width_transfer/check_runtime.py'),'--duration',str(d)]),('relocation',['python3',str(R/'verify_package_examples.py'),'--package',str(package),'--receipt',str(R/f'width{d}_ensemble_package_checks.json')]),('full_public_replay',['python3',str(R/'run_package_validation.py'),'--package',str(package),'--out',str(pred),'--report',str(report)]),('independent_first_member',['python3',str(R/'run_composition_member.py'),'--package',str(R/f'candidate-width-transfer{d}k'),'--out',str(firstpred),'--receipt',str(R/f'width{d}_composition_replay.json')]),('composition',['python3',str(R/'check_ensemble_composition.py'),'--pred',str(pred),'--member',str(firstpred),'--member',str(R/'valid-pred-patch8-6k'),'--member',str(R/'composition-pred-split-patch-12k'),'--member',str(R/'composition-pred-fresh146m48'),'--out',str(R/f'width{d}_ensemble_composition_checks.json')]),('descriptive_comparison',['python3',str(R/'compare_reports.py'),'--candidate',str(report),'--parent',str(R/'valid-report-fresh-capacity4-ensemble.json'),'--out',str(R/f'width{d}_ensemble_comparison.json')])] +state=dict(package=str(package),status='running',steps=[]) +for label,command in steps: + state['current_step']=label;receipt.write_text(json.dumps(state,indent=2));tick=time.monotonic();result=subprocess.run(command);state['steps'].append(dict(name=label,returncode=result.returncode,seconds=time.monotonic()-tick)) + if result.returncode: + state.update(status='failed',seconds=time.monotonic()-started);receipt.write_text(json.dumps(state,indent=2));raise SystemExit(result.returncode) +r=json.loads(report.read_text());assert r['n_failed']==0 and r['n_configs']==97 and r['n_instances']==151170 +state.update(status='complete',seconds=time.monotonic()-started,skill=r['skill_score']);receipt.write_text(json.dumps(state,indent=2));print(json.dumps(state),flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/spectral_synth/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/spectral_synth/check.py new file mode 100644 index 0000000000000000000000000000000000000000..18b155db82902843efdf6df4164d5ed87f249a47 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/spectral_synth/check.py @@ -0,0 +1,79 @@ +"""Check spectral covariance and unchanged control streams without validation data.""" +import copy +import hashlib +import importlib.util +import json +import sys +import time +from pathlib import Path + +import numpy as np + +R = Path('/workspace/research') +sys.path.insert(0, str(R / 'spectral_synth')) +from data import Sampler +from spectral import gaussian_residual, spectral_density + +spec = importlib.util.spec_from_file_location('spectral_control_data', R / 'overflow_control/data.py') +control_code = importlib.util.module_from_spec(spec) +spec.loader.exec_module(control_code) +started = time.monotonic() +seed = 499 +candidate = Sampler(R / 'packed_sample', seed=seed, source_weights_from=R / 'packed_sample') +control = control_code.Sampler(R / 'packed_sample', seed=seed, source_weights_from=R / 'packed_sample') +rng = np.random.default_rng(seed) +rows = synthetic_rows = replaced_rows = 0 +for _ in range(120): + c = int(rng.choice([512, 1024, 2048, 4096])) + h = int(rng.choice([32, 128, 512, 1024])) + expected = control.sample(64, c, h) + actual = candidate.sample(64, c, h) + replacements = np.array(candidate.last_spectral_rows, dtype=int) + unchanged = np.ones(64, dtype=bool) + unchanged[replacements] = False + for x, y in zip(expected, actual): + assert np.array_equal(x[unchanged], y[unchanged], equal_nan=True) + assert set(replacements) <= set(candidate.last_synthetic_rows) + assert np.array_equal(expected[2], actual[2]) + for x, y in zip(expected[:2], actual[:2]): + assert np.array_equal(np.isfinite(x), np.isfinite(y)) + assert candidate.rng.bit_generator.state == control.rng.bit_generator.state + assert candidate.horizon_rng.bit_generator.state == control.horizon_rng.bit_generator.state + rows += 64 + synthetic_rows += len(candidate.last_synthetic_rows) + replaced_rows += len(replacements) +sampler_seconds = time.monotonic() - started +states = {n: copy.deepcopy(v.bit_generator.state) for n, v in vars(candidate).items() + if isinstance(v, np.random.Generator)} +next_batch = candidate.sample(64, 4096, 1024) +for name, state in states.items(): + getattr(candidate, name).bit_generator.state = state +replayed = candidate.sample(64, 4096, 1024) +assert all(np.array_equal(x, y, equal_nan=True) for x, y in zip(next_batch, replayed)) + +covariances = [] +for family in range(4): + values = np.stack([gaussian_residual(512, rng, length_scale=8, family=family) + for _ in range(1024)]) + expected = np.fft.irfft(spectral_density(2048, 8, family), n=2048) + observed = [float(np.mean(values * values))] + observed += [float(np.mean(values[:, lag:] * values[:, :-lag])) for lag in [1, 8, 32]] + wanted = expected[[0, 1, 8, 32]] + assert np.max(np.abs(np.array(observed) - wanted)) < .045 + covariances.append(dict(family=family, observed=observed, theoretical=wanted.tolist())) +for family in range(4): + for n in [8, 40, 5120]: + for scale in [1., 1e4]: + assert np.isfinite(gaussian_residual(n, rng, scale, family)).all() +model_hash = hashlib.sha256((R / 'spectral_synth/model.py').read_bytes()).hexdigest() +assert model_hash == hashlib.sha256((R / 'overflow_control/model.py').read_bytes()).hexdigest() +result = dict(seed=seed, rows=rows, original_synthetic_rows=synthetic_rows, + replaced_spectral_rows=replaced_rows, probability=.5, + original_and_horizon_rng_bitwise_preserved=True, + unmodified_rows_bitwise_preserved=True, periods_and_finite_masks_unchanged=True, + all_numpy_rng_recovery_exact=True, model_sha256=model_hash, + model_bitwise_unchanged=True, covariance_checks=covariances, + sampler_comparison_seconds=sampler_seconds, seconds=time.monotonic()-started, + optimizer_updates=0, validation_data_read=False) +(R / 'spectral_synth_checks.json').write_text(json.dumps(result, indent=2)) +print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/spectral_synth/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/spectral_synth/data.py new file mode 100644 index 0000000000000000000000000000000000000000..bf91f33740715be702c2772f3cca89b656cea4dc --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/spectral_synth/data.py @@ -0,0 +1,102 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq +from spectral import gaussian_residual + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + if self.spectral_rng.random()8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + self.spectral_rng=np.random.default_rng(seed+1100003) + self.spectral_probability=.5 + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/spectral_synth/launch.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/spectral_synth/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..0134693b620294a3fb18eed15e107d649a0cc487 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/spectral_synth/launch.py @@ -0,0 +1,29 @@ +"""Queue spectral synthetic residuals after postloss completion finishes.""" +def main(): + import json + import os + import subprocess + from pathlib import Path + R=Path('/workspace/research') + checks=json.loads((R/'spectral_synth_checks.json').read_text()) + assert checks['original_and_horizon_rng_bitwise_preserved'] and checks['unmodified_rows_bitwise_preserved'] + assert checks['all_numpy_rng_recovery_exact'] and checks['model_bitwise_unchanged'] + env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1') + command=['python3',str(R/'recovery/train.py'),'--code-dir',str(R/'spectral_synth'), + '--packed',str(R/'packed_sample'),'--source-weights-from',str(R/'packed_sample'), + '--out',str(R/'runs/spectral_synth'),'--initialize-from',str(R/'horizon_delta12k.pt'), + '--steps','12000','--batch','64','--lr','.00002','--seed','197','--loss-mode','paired', + '--stop-file',str(R/'spectral_synth.stop')] + with (R/'spectral_synth_queue.log').open('w') as qlog,(R/'spectral_synth_watch.log').open('w') as wlog: + queued=subprocess.Popen(['python3',str(R/'queued_train.py'),'--label','E106 spectral synthetic residuals seed197', + '--log',str(R/'spectral_synth_train.log'),'--receipt',str(R/'spectral_synth_queue.json'), + '--wait-pid','10664','--require-checkpoint',str(R/'runs/postloss_completion/recovery.pt'), + '--',*command],stdout=qlog,stderr=subprocess.STDOUT,env=env) + watch=subprocess.Popen(['python3',str(R/'watch_evaluate.py'),'--run',str(R/'runs/spectral_synth'), + '--evaluator',str(R/'postloss_inference/evaluate.py'),'--name','spectral_synth', + '--expected-packed',str(R/'packed_sample'),'--steps','1000,3000,6000,12000'],stdout=wlog,stderr=subprocess.STDOUT,env=env) + print({'queue_pid':queued.pid,'watch_pid':watch.pid},flush=True) + result=queued.wait() + if result:watch.terminate() + watch.wait();raise SystemExit(result) +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/spectral_synth/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/spectral_synth/model.py new file mode 100644 index 0000000000000000000000000000000000000000..3532e5063bd8b5013f6b6e35703707ffef66e00b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/spectral_synth/model.py @@ -0,0 +1,213 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/spectral_synth/spectral.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/spectral_synth/spectral.py new file mode 100644 index 0000000000000000000000000000000000000000..f7358c3ec944849ea619ef2e73697775b48d408c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/spectral_synth/spectral.py @@ -0,0 +1,27 @@ +"""Locally generated finite stationary Gaussian fields with varied smoothness.""" +import numpy as np + + +def spectral_density(size, length_scale, family): + omega = 2 * np.pi * np.fft.rfftfreq(size) + if family == 3: + density = np.exp(-.5 * (length_scale * omega) ** 2) + else: + nu = [.5, 1.5, 2.5][family] + density = (1 + (length_scale * omega) ** 2 / (2 * nu)) ** (-nu - .5) + # Real FFT has one DC and one Nyquist coefficient, two of each interior bin. + variance = (density[0] + density[-1] + 2 * density[1:-1].sum()) / size + return density / variance + + +def gaussian_residual(n, rng, length_scale=None, family=None): + """The covariance is the discrete inverse Fourier transform of the declared PSD.""" + if length_scale is None: + length_scale = 10 ** rng.uniform(0, 4) + if family is None: + family = int(rng.integers(4)) + size = 1 << (max(16, 4 * n) - 1).bit_length() + density = spectral_density(size, length_scale, family) + white = rng.normal(size=size) + field = np.fft.irfft(np.fft.rfft(white) * np.sqrt(density), n=size) + return field[:n].astype(np.float32) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/spectral_transfer/run.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/spectral_transfer/run.py new file mode 100644 index 0000000000000000000000000000000000000000..b12c03e56acc3688932c441fd31aa259136f1bc1 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/spectral_transfer/run.py @@ -0,0 +1,55 @@ +"""E114: two predeclared coefficient-one spectral-prior transfers; selection only.""" +import hashlib +import json +import os +import subprocess +import time +from pathlib import Path + +R = Path('/workspace/research') +env = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1') +started = time.monotonic() +receipt = {'experiment': 'E114', 'status': 'running', 'steps': []} +receipt_path = R / 'spectral_transfer_receipt.json' + +def run(label, command): + receipt['current_step'] = label + receipt_path.write_text(json.dumps(receipt, indent=2)) + print(json.dumps({'starting': label}), flush=True) + t0 = time.monotonic() + result = subprocess.run(command, env=env, check=False) + receipt['steps'].append({'name': label, 'seconds': time.monotonic()-t0, + 'returncode': result.returncode}) + if result.returncode: + receipt.update(status='failed', seconds=time.monotonic()-started) + receipt_path.write_text(json.dumps(receipt, indent=2)) + raise SystemExit(result.returncode) + +add = R/'spectral_add_delta6k.pt' +replace = R/'spectral_replace_delta6k.pt' +assert not add.exists() and not replace.exists(), 'Refuse to overwrite fixed candidates' +run('add_spectral_delta', ['python3', str(R/'partial_delta/merge.py'), + '--base', str(R/'weekly_slow_ar_delta6k.pt'), + '--candidate', str(R/'runs/spectral_synth/ema006000.pt'), + '--control', str(R/'runs/overflow_control/ema006000.pt'), '--out', str(add)]) +run('remove_old_slow_ar_delta', ['python3', str(R/'partial_delta/merge.py'), + '--base', str(add), '--candidate', str(R/'runs/partial_targets/ema006000.pt'), + '--control', str(R/'runs/long_memory_synth_recovery/ema006000.pt'), '--out', str(replace)]) +receipt['candidate_hashes'] = {p.stem: hashlib.sha256(p.read_bytes()).hexdigest() for p in [add, replace]} +for weights in [add, replace]: + run(weights.stem+'_four_cutoffs', ['python3', str(R/'evaluate_cutoffs.py'), + '--name', weights.stem, '--weights', str(weights), + '--evaluator', str(R/'postloss_inference/evaluate.py')]) + for cutoff, folder in [('valid_screen','evals'), ('valid_backcast','backcast_evals'), + ('valid_backcast2','backcast2_evals'), ('valid_backcast3','backcast3_evals')]: + run(weights.stem+'_'+cutoff+'_record', ['python3', str(R/'direct_v1/record.py'), + str(R/folder/weights.stem/'report.json'), '--label', 'E114 '+weights.stem+' '+cutoff, + '--outcome', 'Fixed coefficient-one spectral transfer; additive and old-slow-AR replacement are the two predeclared ablations. No optimization. Ensemble selection recorded separately.']) + command = ['python3', str(R/'equal_ensemble_probe.py'), '--valid', str(R/cutoff), + '--out', str(R/(weights.stem+'_ensemble_'+cutoff+'.json'))] + for name in [weights.stem, 'patch8_ema6000', 'split_patch_ema12000']: + command += ['--pred', str(R/folder/name)] + run(weights.stem+'_'+cutoff+'_ensemble', command) +receipt.update(status='complete', seconds=time.monotonic()-started) +receipt_path.write_text(json.dumps(receipt, indent=2)) +print(json.dumps(receipt), flush=True) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/weekly_synth/check.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/weekly_synth/check.py new file mode 100644 index 0000000000000000000000000000000000000000..1797c7ca37791de3ac143f64843434ad7beda0ba --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/weekly_synth/check.py @@ -0,0 +1,45 @@ +"""Verify the weekly-only data change without using validation or optimizer steps.""" +import copy +import hashlib +import importlib.util +import json +import sys +import time +from pathlib import Path +import numpy as np + +R=Path('/workspace/research') +sys.path.insert(0,str(R/'weekly_synth')) +from data import Sampler +spec=importlib.util.spec_from_file_location('weekly_control_data',R/'overflow_control/data.py') +control_code=importlib.util.module_from_spec(spec);spec.loader.exec_module(control_code) +started=time.monotonic();seed=467 +candidate=Sampler(R/'packed_sample',seed=seed,source_weights_from=R/'packed_sample') +control=control_code.Sampler(R/'packed_sample',seed=seed,source_weights_from=R/'packed_sample') +rng=np.random.default_rng(seed);rows=synthetic_rows=weekly_rows=0 +for _ in range(120): + c=int(rng.choice([512,1024,2048,4096]));h=int(rng.choice([32,128,512,1024])) + expected=control.sample(64,c,h);actual=candidate.sample(64,c,h) + replacements=np.array(candidate.last_weekly_rows,dtype=int) + unchanged=np.ones(64,dtype=bool);unchanged[replacements]=False + for x,y in zip(expected,actual): + assert np.array_equal(x[unchanged],y[unchanged],equal_nan=True) + assert set(candidate.last_weekly_rows)<=set(candidate.last_synthetic_rows) + assert np.all(actual[2][replacements]==np.array([52,1])) + for x,y in zip(expected[:2],actual[:2]): + assert np.array_equal(np.isfinite(x),np.isfinite(y)) + assert candidate.rng.bit_generator.state==control.rng.bit_generator.state + assert candidate.horizon_rng.bit_generator.state==control.horizon_rng.bit_generator.state + rows+=64;synthetic_rows+=len(candidate.last_synthetic_rows);weekly_rows+=len(replacements) +states={n:copy.deepcopy(v.bit_generator.state) for n,v in vars(candidate).items() if isinstance(v,np.random.Generator)} +next_batch=candidate.sample(64,4096,1024) +for name,state in states.items():getattr(candidate,name).bit_generator.state=state +replayed=candidate.sample(64,4096,1024) +assert all(np.array_equal(x,y,equal_nan=True) for x,y in zip(next_batch,replayed)) +model_hash=hashlib.sha256((R/'weekly_synth/model.py').read_bytes()).hexdigest() +assert model_hash==hashlib.sha256((R/'overflow_control/model.py').read_bytes()).hexdigest() +result=dict(seed=seed,rows=rows,original_synthetic_rows=synthetic_rows,replaced_weekly_rows=weekly_rows, + probability=1/11,original_and_horizon_rng_bitwise_preserved=True,unmodified_rows_bitwise_preserved=True, + finite_masks_unchanged=True,all_numpy_rng_recovery_exact=True,model_sha256=model_hash, + model_bitwise_unchanged=True,seconds=time.monotonic()-started,optimizer_updates=0,validation_data_read=False) +(R/'weekly_synth_checks.json').write_text(json.dumps(result,indent=2));print(json.dumps(result)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/weekly_synth/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/weekly_synth/data.py new file mode 100644 index 0000000000000000000000000000000000000000..81f0f018cb212a6e2125543e0d4efa2f31b9d8fb --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/weekly_synth/data.py @@ -0,0 +1,113 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + self.weekly_rng=np.random.default_rng(seed+1000003) + self.weekly_probability=1/11 + def synthetic(self,n,p): + # Always consume the control generator first, preserving its complete RNG stream. + original=super().synthetic(n,p) + if self.weekly_rng.random()>=self.weekly_probability: + return original + original_rng=self.rng + try: + self.rng=self.weekly_rng + result=super().synthetic(n,[52,1]) + finally: + self.rng=original_rng + p[:]=[52,1] + self.last_weekly_rows.append(self._synthetic_row) + return result + + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/weekly_synth/launch.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/weekly_synth/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..ef36b1e3de2ad1cc424019100da141536161d07a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/weekly_synth/launch.py @@ -0,0 +1,29 @@ +"""Queue weekly synthetic coverage after robust-normalization training finishes.""" +def main(): + import json + import os + import subprocess + from pathlib import Path + R=Path('/workspace/research') + checks=json.loads((R/'weekly_synth_checks.json').read_text()) + assert checks['original_and_horizon_rng_bitwise_preserved'] and checks['unmodified_rows_bitwise_preserved'] + assert checks['all_numpy_rng_recovery_exact'] and checks['model_bitwise_unchanged'] + env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1') + command=['python3',str(R/'recovery/train.py'),'--code-dir',str(R/'weekly_synth'), + '--packed',str(R/'packed_sample'),'--source-weights-from',str(R/'packed_sample'), + '--out',str(R/'runs/weekly_synth'),'--initialize-from',str(R/'horizon_delta12k.pt'), + '--steps','12000','--batch','64','--lr','.00002','--seed','197','--loss-mode','paired', + '--stop-file',str(R/'weekly_synth.stop')] + with (R/'weekly_synth_queue.log').open('w') as qlog,(R/'weekly_synth_watch.log').open('w') as wlog: + queued=subprocess.Popen(['python3',str(R/'queued_train.py'),'--label','E97 weekly synthetic coverage seed197', + '--log',str(R/'weekly_synth_train.log'),'--receipt',str(R/'weekly_synth_queue.json'), + '--wait-pid','9354','--require-checkpoint',str(R/'runs/robust_normalization/recovery.pt'), + '--',*command],stdout=qlog,stderr=subprocess.STDOUT,env=env) + watch=subprocess.Popen(['python3',str(R/'watch_evaluate.py'),'--run',str(R/'runs/weekly_synth'), + '--evaluator',str(R/'postloss_inference/evaluate.py'),'--name','weekly_synth', + '--steps','1000,3000,6000,12000'],stdout=wlog,stderr=subprocess.STDOUT,env=env) + print({'queue_pid':queued.pid,'watch_pid':watch.pid},flush=True) + result=queued.wait() + if result:watch.terminate() + watch.wait();raise SystemExit(result) +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/weekly_synth/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/weekly_synth/model.py new file mode 100644 index 0000000000000000000000000000000000000000..3532e5063bd8b5013f6b6e35703707ffef66e00b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member0/training/weekly_synth/model.py @@ -0,0 +1,213 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + # Rare permitted-corpus rows exceed float32 variance accumulation range. + # Preserve the original arithmetic on every ordinary row. + bad=~torch.isfinite(mu)|~torch.isfinite(scale) + precise=x.double();mean64=precise.sum(-1,keepdim=True)/count + variance64=torch.where(valid,(precise-mean64).square(),0.).sum(-1,keepdim=True)/count + scale64=torch.maximum(variance64.sqrt(),mean64.abs()*1e-4+1e-4) + z64=torch.where(valid,(precise-mean64)/scale64,0.).clamp(-30,30) + z=torch.where(bad,z64.float(),z) + mu=torch.where(bad,mean64.float(),mu);scale=torch.where(bad,scale64.float(),scale) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/model_manifest.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/model_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..ed7d82d53ee418c27f3691dc143ede37891db0ef --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/model_manifest.json @@ -0,0 +1,660 @@ +{ + "name": "direct-seasonal-foundation", + "contract": "timeseries-forecast/v1", + "parameters": 36665488, + "pretrained_assets": [], + "sources_used": [ + "gifteval_pretrain/BEIJING_SUBWAY_30MIN", + "gifteval_pretrain/HZMETRO", + "gifteval_pretrain/LOS_LOOP", + "gifteval_pretrain/PEMS03", + "gifteval_pretrain/PEMS04", + "gifteval_pretrain/PEMS07", + "gifteval_pretrain/PEMS08", + "gifteval_pretrain/PEMS_BAY", + "gifteval_pretrain/Q-TRAFFIC", + "gifteval_pretrain/SHMETRO", + "gifteval_pretrain/alibaba_cluster_trace_2018", + "gifteval_pretrain/australian_electricity_demand", + "gifteval_pretrain/azure_vm_traces_2017", + "gifteval_pretrain/bdg-2_bear", + "gifteval_pretrain/bdg-2_fox", + "gifteval_pretrain/bdg-2_panther", + "gifteval_pretrain/bdg-2_rat", + "gifteval_pretrain/bitcoin_with_missing", + "gifteval_pretrain/borealis", + "gifteval_pretrain/borg_cluster_data_2011", + "gifteval_pretrain/buildings_900k", + "gifteval_pretrain/bull", + "gifteval_pretrain/cdc_fluview_ilinet", + "gifteval_pretrain/cdc_fluview_who_nrevss", + "gifteval_pretrain/china_air_quality", + "gifteval_pretrain/cif_2016_12", + "gifteval_pretrain/cif_2016_6", + "gifteval_pretrain/cmip6_2000", + "gifteval_pretrain/cmip6_2005", + "gifteval_pretrain/cmip6_2010", + "gifteval_pretrain/cockatoo", + "gifteval_pretrain/covid19_energy", + "gifteval_pretrain/covid_mobility", + "gifteval_pretrain/elecdemand", + "gifteval_pretrain/elf", + "gifteval_pretrain/era5_2010", + "gifteval_pretrain/era5_2011", + "gifteval_pretrain/era5_2012", + "gifteval_pretrain/era5_2013", + "gifteval_pretrain/era5_2014", + "gifteval_pretrain/era5_2015", + "gifteval_pretrain/era5_2016", + "gifteval_pretrain/era5_2017", + "gifteval_pretrain/era5_2018", + "gifteval_pretrain/extended_web_traffic_with_missing", + "gifteval_pretrain/favorita_sales", + "gifteval_pretrain/favorita_transactions", + "gifteval_pretrain/gfc12_load", + "gifteval_pretrain/gfc14_load", + "gifteval_pretrain/gfc17_load", + "gifteval_pretrain/godaddy", + "gifteval_pretrain/hog", + "gifteval_pretrain/ideal", + "gifteval_pretrain/kaggle_web_traffic_weekly", + "gifteval_pretrain/kdd2022", + "gifteval_pretrain/largest_2017", + "gifteval_pretrain/largest_2018", + "gifteval_pretrain/largest_2019", + "gifteval_pretrain/largest_2020", + "gifteval_pretrain/largest_2021", + "gifteval_pretrain/lcl", + "gifteval_pretrain/london_smart_meters_with_missing", + "gifteval_pretrain/m1_monthly", + "gifteval_pretrain/m1_quarterly", + "gifteval_pretrain/m1_yearly", + "gifteval_pretrain/m5", + "gifteval_pretrain/monash_m3_monthly", + "gifteval_pretrain/monash_m3_other", + "gifteval_pretrain/monash_m3_quarterly", + "gifteval_pretrain/nn5_daily_with_missing", + "gifteval_pretrain/nn5_weekly", + "gifteval_pretrain/oikolab_weather", + "gifteval_pretrain/pdb", + "gifteval_pretrain/project_tycho", + "gifteval_pretrain/residential_load_power", + "gifteval_pretrain/residential_pv_power", + "gifteval_pretrain/rideshare_with_missing", + "gifteval_pretrain/sceaux", + "gifteval_pretrain/smart", + "gifteval_pretrain/solar_power", + "gifteval_pretrain/spain", + "gifteval_pretrain/subseasonal", + "gifteval_pretrain/subseasonal_precip", + "gifteval_pretrain/sunspot_with_missing", + "gifteval_pretrain/taxi_30min", + "gifteval_pretrain/tourism_quarterly", + "gifteval_pretrain/tourism_yearly", + "gifteval_pretrain/traffic_hourly", + "gifteval_pretrain/traffic_weekly", + "gifteval_pretrain/uber_tlc_daily", + "gifteval_pretrain/uber_tlc_hourly", + "gifteval_pretrain/vehicle_trips_with_missing", + "gifteval_pretrain/wiki-rolling_nips", + "gifteval_pretrain/wind_farms_with_missing", + "gifteval_pretrain/wind_power", + "synthetic:both original and sign-reflected orientations of each sampled allowed or locally generated window; paired quantile loss, seed 197", + "synthetic:both original and sign-reflected orientations of each sampled window, seed 197", + "synthetic:independent sign reflection of sampled allowed-corpus and locally generated windows; seeds 43,47,59,79,89,197", + "synthetic:own direct_v1 Fourier seasons, damped trends, AR noise, changepoints and intermittent demand; seeds 23,43,47,59,79,89,197", + "synthetic:own random requested-horizon prefixes, half of rows retain the full horizon and half use a patch-rounded prefix between one-quarter and the full horizon; independent seed 300200" + ], + "weights_sha256": "308389b7217c080af9eb185559d4ee3cafa0f3e0f8c4dd8f5526b68198c89988", + "config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "training_lineage": [ + { + "checkpoint": "runs/patch8/ema006000.pt", + "sha256": "308389b7217c080af9eb185559d4ee3cafa0f3e0f8c4dd8f5526b68198c89988", + "step": 6000, + "seed": 197, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 2e-05, + "steps": 12000, + "start_step": 0, + "trainable_scope": "all", + "loss_mode": "paired", + "context": null, + "sample_context": 4096, + "compile_loss": false, + "requested_horizon_seed": 300200 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "parents": [ + "patch8_initial.pt" + ] + }, + { + "checkpoint": "patch8_initial.pt", + "sha256": "e7da4d47a9cc984a9423296679d7c9127ef2d679be950b9e8d3758e6fca074cc", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 8, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true, + "partial_target_lengths": true + }, + "conversion": { + "from_checkpoint": "/run-state/workspace/research/horizon_delta12k.pt", + "from_sha256": "22c08571978be31ba57368eb983089a40a44d56d4ae5e17da41afd2a761a258c", + "method": "fold input/query/recency halves by summation; retain first8 output rows; preserve physical position units", + "exact_function_preservation": false + }, + "parents": [ + "horizon_delta12k.pt", + "horizon_delta12k.pt" + ] + }, + { + "checkpoint": "horizon_delta12k.pt", + "sha256": "22c08571978be31ba57368eb983089a40a44d56d4ae5e17da41afd2a761a258c", + "step": 0, + "seed": null, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": {}, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true + }, + "conversion": { + "method": "matched training delta", + "formula": "base + candidate - control", + "coefficient": 1.0, + "parent_hashes": { + "/workspace/research/runs/confidence_query/ema006000.pt": "0bad97e8994aac49ea173443db0a4fa8d72d33f9eb9e2660f06de75f7f1403eb", + "/workspace/research/runs/horizon_jitter/ema012000.pt": "830179d763916a1065fc615d2c5e22f4a3b5b19390dde707ab0f057e13cadff6", + "/workspace/research/runs/large_corpus_control/ema012000.pt": "7f9ba5e01ac59c51a3b63d3067b442e23e15d0abc51ddbcccdd04d6083ae4add" + }, + "seconds": 1.2663014469435439 + }, + "parents": [ + "runs/confidence_query/ema006000.pt", + "runs/horizon_jitter/ema012000.pt", + "runs/large_corpus_control/ema012000.pt" + ] + }, + { + "checkpoint": "runs/confidence_query/ema006000.pt", + "sha256": "0bad97e8994aac49ea173443db0a4fa8d72d33f9eb9e2660f06de75f7f1403eb", + "step": 6000, + "seed": 89, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 64, + "lr": 0.0002, + "steps": 6000 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "confidence_features": true + }, + "parents": [ + "runs/recency_features/ema024000.pt" + ] + }, + { + "checkpoint": "runs/horizon_jitter/ema012000.pt", + "sha256": "830179d763916a1065fc615d2c5e22f4a3b5b19390dde707ab0f057e13cadff6", + "step": 12000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true, + "partial_target_lengths": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/large_corpus_control/ema012000.pt", + "sha256": "7f9ba5e01ac59c51a3b63d3067b442e23e15d0abc51ddbcccdd04d6083ae4add", + "step": 12000, + "seed": 79, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 5e-05, + "steps": 12000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/recency_features/ema012000.pt" + ] + }, + { + "checkpoint": "runs/recency_features/ema024000.pt", + "sha256": "1530fbb577a87ca4eb39da83d6fee9b8ee5bc924202e021e3a7b56493112f564", + "step": 24000, + "seed": 59, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/patch16_trial/ema006000.pt" + ] + }, + { + "checkpoint": "runs/recency_features/ema012000.pt", + "sha256": "8ccb6870a025e1097331a3a288b1183741a413f3460fbf3352d0c589c6a4394c", + "step": 12000, + "seed": 59, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024, + "recency_features": true + }, + "parents": [ + "runs/patch16_trial/ema006000.pt" + ] + }, + { + "checkpoint": "runs/patch16_trial/ema006000.pt", + "sha256": "0ff54447074e0271d2e331c7d3e6e9e0fdd73353e4d8cef0175ff627385f71c3", + "step": 6000, + "seed": 47, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024 + }, + "parents": [ + "patch16_init.pt" + ] + }, + { + "checkpoint": "patch16_init.pt", + "sha256": "d69531bfde5bf801e7f36c515bf15fd0cae0bd84f7d1479d35f4a7b67f26b508", + "step": 6000, + "seed": 43, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 16, + "max_context": 4096, + "max_horizon": 1024 + }, + "conversion": { + "from_checkpoint": "/run-state/workspace/research/runs/large_sign/ema006000.pt", + "from_sha256": "96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547", + "method": "fold input/query halves by summation; retain first 16 output rows; preserve physical positional units" + }, + "parents": [ + "runs/large_sign/ema006000.pt" + ] + }, + { + "checkpoint": "runs/large_sign/ema006000.pt", + "sha256": "96c9d350412c076594f4cc026aaf7396eacc45478f3d402c5d60dcf85dce8547", + "step": 6000, + "seed": 43, + "ema": true, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 256, + "lr": 8e-05, + "steps": 6000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 32, + "max_context": 4096, + "max_horizon": 1024 + }, + "parents": [ + "runs/direct_large/step024000.pt" + ] + }, + { + "checkpoint": "runs/direct_large/step024000.pt", + "sha256": "b7e4f38aebcd2cf38ce484edaad8d19851317fb3b8df485e2faa0d0423cbcb48", + "step": 24000, + "seed": 23, + "ema": false, + "averaged_steps": null, + "packed_corpus": "packed_sample", + "sample_series": 357789, + "source_probability_reference": "packed_sample", + "packed_receipt_sha256": "63520f21e2441047a0eacbc35be0d80ac691bda90ac654094261ecc6da9d11b8", + "training_settings": { + "batch": 128, + "lr": 0.0002, + "steps": 24000, + "context": 4096 + }, + "model_config": { + "d": 512, + "heads": 8, + "enc_layers": 6, + "dec_layers": 4, + "patch": 32, + "max_context": 4096, + "max_horizon": 1024 + }, + "initialization": "random initialization in this workspace" + } + ], + "symmetric_averaging": true, + "seasonal_gate": { + "variance_ratio_threshold": 0.25, + "maximum_weight": 0.98, + "cycles_averaged": 4, + "template_mode": "aligned", + "amplitude_ratio_clip": [ + 0.5, + 2.0 + ], + "latest_cycle_minimum_coverage": 0.75, + "variance_noise_correction": "mean squared seasonal differences / 2" + }, + "continuity": { + "decay_steps": 24, + "variance_ratio_threshold": 0.5, + "maximum_weight": 0.95, + "lookback": 512, + "slope_median_differences": 8 + }, + "notes": "All training lineage originates from random initialization here, using only the declared corpus and locally generated series. Validation was used only for selection and diagnostics. Context transformations are fixed formulas; there is no inference-time fitting or parameter adaptation.", + "runtime_code_sha256": { + "model.py": "c27748fa4b1186b513f76eca26052753b8dcd1794994e5989addaf371ca70f2e", + "infer.sh": "5fe66b4fe9a4787285d830cfd96975701e97286a75ba7c3687bd8891475edf68", + "continuity.py": "dbb08d2229ad80ad00f638b0b9f2f6ca13c663e0fd6730058e5fee8ff54545d5", + "ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "zero_mass.py": "f079d509009bcda409b80eb64467c869b838cfbab11b2bd4c660c2875b6642fe", + "seasonal.py": "b946e63048196ab5ea8b249137d48c80d8510943caccd0f180e4fb86d9b24b37", + "predict.py": "9bde896945a2cd8f892e7eeb6328ed2dfda09293532f3a4a64d929c9943614ef" + }, + "final_training_stage": { + "trainable_scope": "all parameters", + "sign_loss": "paired", + "learning_rate_multipliers": {} + }, + "trend_summary": { + "fixed_averaging_width": 128, + "matches_all_pretraining_context_widths": true, + "independent_of_batch_padding": true + }, + "zero_mass_projection": { + "threshold_in_context_standard_deviations": 0.4, + "nonnegative_context_required": true, + "minimum_exact_zeros": 4, + "minimum_zero_fraction": 0.1, + "context_cap": 4096 + }, + "recency_features": { + "query_projection_parameters": 16384, + "latest_vs_four_cycle_level": true, + "amplitude_ratio_clip": [ + 0.5, + 2.0 + ], + "minimum_observed_cycles": 3 + }, + "confidence_features": { + "query_projection_parameters": 3072, + "backbone_frozen_during_projection_training": true, + "training_objective": "weighted quantile and median loss after averaging both sign orientations", + "statistics": [ + "mean absolute difference", + "root mean square difference" + ], + "lags": "one and the two frequency-derived periods", + "lookback": "512 for lag one; eight cycles for seasonal lags", + "minimum_valid_pairs": 8, + "insufficient_pair_defaults": [ + 1, + 1.4142135623730951 + ], + "statistic_clip": 10, + "transform": "log1p", + "stage_scope": "Frozen-backbone details refer to projection introduction; subsequent updates are recorded in training_lineage.training_settings." + }, + "partial_target_training": { + "available_horizon": "last finite training-label position rounded up to the patch boundary", + "decoder_future_key_mask": true, + "per_row_horizon_metadata": true, + "inference_uses_requested_horizon_only": true + }, + "training_provenance_code_sha256": { + "confidence_query/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "confidence_query/model.py": "b4f11ba2018e2b50879cdc33acf0138301548971508b58035a7c96a29aaa6f2d", + "confidence_query/train.py": "fc8a7555a5a6b0a6f91e80ac8cc9cbbfddaa2b26468c57f49dfb17671b22ce93", + "direct_large/data.py": "6e6db217936f8dd79380d2ceff3eaa8598a44f1b60b17acae7bfde2363116847", + "direct_large/evaluate.py": "eaea99e8cd44c9f7c70a45fa9abf51354ae5449dbad273fcb55e48ad02652223", + "direct_large/model.py": "146d93a3f95b13bda8b1b437bc36621b91356cf946e94f62999f89e7fb348071", + "direct_large/pack.py": "3bcc4ce9eb3361ad741ceebd7efce7a2fb86fb49543f52c72aabd0e3e8cd17ce", + "direct_large/predict.py": "930a9f18f9f5da47c03859698c9d2f5567d1e1c73fd61edac1ed20b3a6f9bb50", + "direct_large/publish.py": "3c167f33e8571731c26f1cb70168eda54ef9cb4c76423dfd374240b75ca5f106", + "direct_large/record.py": "b3b00b0ed14bc3af00c7b1ad97195238ecb8f06e96bc41f0c07913bc3f6ed949", + "direct_large/train.py": "b9ad6b2adddeaf12961b529d6535dd33f6d044a31979b5c9e49dceafbadd3ac0", + "direct_large/ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "direct_large/validation_subset.py": "8d3eb9d3f3aa124368761ef402ff066935c0be31a62b25b8551a45dcb922e28d", + "full_paired/check.py": "90ac1c78846439d51ab8acd62a19bd536c7c394bd02e94f6d5ff17c0af8bd116", + "full_paired/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "full_paired/model.py": "c27748fa4b1186b513f76eca26052753b8dcd1794994e5989addaf371ca70f2e", + "horizon_jitter/data.py": "5044cf648323420095ed6058d29f837c07ff5559b606df8b00cc8d1e95c8b58e", + "horizon_jitter/model.py": "186bb282236f23cc665a012194d26e58f51004c680393352ec053f5308f1240f", + "horizon_jitter/train.py": "4e9cbca1293f18f7eea2c72dba127815c0934a13c86e8f6cc881a749676d41a6", + "large_corpus/data.py": "27c078cb0ed085717a364f556b5ff976fd803d5af37612cf3a03a0a3ca12a678", + "large_corpus/model.py": "e3a1bc01e89a0d6d750ede2cc969272ad01e1ca580b174af7dee00db029f1cf7", + "large_corpus/train.py": "3baca16c3945e6ef241ccbc9c13644539e3c265f71095cbbaa61a3d338e4fafe", + "large_sign/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "large_sign/evaluate.py": "eaea99e8cd44c9f7c70a45fa9abf51354ae5449dbad273fcb55e48ad02652223", + "large_sign/model.py": "3fff6445a1982a1b3c92f06a9b5f1bb627dda6a291b0b2364bcfb1a6457830d7", + "large_sign/pack.py": "3bcc4ce9eb3361ad741ceebd7efce7a2fb86fb49543f52c72aabd0e3e8cd17ce", + "large_sign/predict.py": "930a9f18f9f5da47c03859698c9d2f5567d1e1c73fd61edac1ed20b3a6f9bb50", + "large_sign/publish.py": "3c167f33e8571731c26f1cb70168eda54ef9cb4c76423dfd374240b75ca5f106", + "large_sign/record.py": "b3b00b0ed14bc3af00c7b1ad97195238ecb8f06e96bc41f0c07913bc3f6ed949", + "large_sign/train.py": "a597f40ab87cce04e96dc654d12e56cdf40ffd87f00034d8bc4d56dff4eb7c68", + "large_sign/ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "large_sign/validation_subset.py": "8d3eb9d3f3aa124368761ef402ff066935c0be31a62b25b8551a45dcb922e28d", + "partial_delta/merge.py": "63984a0f46f7d48817037f5bf5a1c9319e45a9b1924cde62c667ac49ce47532e", + "partial_targets/data.py": "27c078cb0ed085717a364f556b5ff976fd803d5af37612cf3a03a0a3ca12a678", + "partial_targets/model.py": "186bb282236f23cc665a012194d26e58f51004c680393352ec053f5308f1240f", + "partial_targets/train.py": "3baca16c3945e6ef241ccbc9c13644539e3c265f71095cbbaa61a3d338e4fafe", + "patch16/convert.py": "11e1d30100ab25311020ac1f4ab8227ec66156836df5de613300867977091c45", + "patch16/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "patch16/evaluate.py": "eaea99e8cd44c9f7c70a45fa9abf51354ae5449dbad273fcb55e48ad02652223", + "patch16/model.py": "8031c597b354eb2cf464140bee40c3ec8dff86c775b5c55c5ce910302b443582", + "patch16/pack.py": "3bcc4ce9eb3361ad741ceebd7efce7a2fb86fb49543f52c72aabd0e3e8cd17ce", + "patch16/predict.py": "930a9f18f9f5da47c03859698c9d2f5567d1e1c73fd61edac1ed20b3a6f9bb50", + "patch16/publish.py": "3c167f33e8571731c26f1cb70168eda54ef9cb4c76423dfd374240b75ca5f106", + "patch16/record.py": "b3b00b0ed14bc3af00c7b1ad97195238ecb8f06e96bc41f0c07913bc3f6ed949", + "patch16/train.py": "3156710f76111a31447cbe638ee27fe2811d060917aa083aab0b5134d98accf8", + "patch16/ts_io.py": "1064d1a95a59e7edd6ed33e9a6d58c83c17fa3886acb1fb54e3652d9326ee436", + "patch16/validation_subset.py": "8d3eb9d3f3aa124368761ef402ff066935c0be31a62b25b8551a45dcb922e28d", + "patch8/convert.py": "9edaa0c8349310b7419d649fb4f21dd3ddb9067ebe984d5df3701a234be73780", + "patch8/data.py": "6537d67ec1d76490015e5bb71a24a0317734ba7bec879628e6547e0a21a2b6e0", + "patch8/memory_check.py": "78e8e5cca960bf1225ec0104980363c82f4c3c13c2d77ed154cea37a5b6f3fd1", + "patch8/model.py": "c27748fa4b1186b513f76eca26052753b8dcd1794994e5989addaf371ca70f2e", + "recency_features/data.py": "b64786d13e8a73646e8e1da25d5073e2e9222eb27830bf55d24f4af14b156b04", + "recency_features/model.py": "e3a1bc01e89a0d6d750ede2cc969272ad01e1ca580b174af7dee00db029f1cf7", + "recency_features/train.py": "a654b9a27b6c27141e1d4e517ab28fcae3f2c23d061742fa2f6c01e3d23c8a00", + "recovery/capacity_curves.py": "2bdc6635705b70a868e115cd13eb529563acacf6f47c71f250a50dce8e943be4", + "recovery/exposure_audit.py": "54c194a626b8876ece84686b39b22360155c9fada7248a393ca9b7d6ee38002b", + "recovery/relaunch_20261022b.py": "f90ddd77928a793c8e151ba74cfa9cc84c8aefad0c0d943a833c74bc07b79313", + "recovery/relaunch_20261023.py": "a4c40c5674b0d05cfe9bb1fffe907f02dec16c53cbddb8b86efbba1b96649097", + "recovery/schedules.py": "7748fd6b2bbbe64037472faf7e6583d03cf339138d2f3c07b1bac9e65bf2d4f5", + "recovery/snapshot.py": "0f241a7e139e47ffff7efea40572205fd84c12efe6fb3c2dccd87c50d678a6c3", + "recovery/train.py": "63bee736565af670877b4cd7c75015fab06a18c66bbe132b0bb3faff5ebd80c7" + } +} diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/direct_large/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/direct_large/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/direct_large/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/full_paired/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/full_paired/data.py new file mode 100644 index 0000000000000000000000000000000000000000..30d82fdb16762eef87bad4277abf3cc957178684 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/full_paired/data.py @@ -0,0 +1,94 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class BaseSampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods + + +def truncate_targets(arrays,rng,patch=16): + """Random requested horizons; corpus windows and the original RNG remain unchanged.""" + ctx,target,periods=arrays + h=target.shape[-1] + active=rng.random(len(target))<.5 + end=rng.integers(max(1,h//4),h+1,size=len(target)) + end=np.where(active,end,h) + end=np.minimum(h,((end+patch-1)//patch)*patch) + target=target.copy() + target[np.arange(h)[None,:]>=end[:,None]]=np.nan + return ctx,target,periods + + +class Sampler(BaseSampler): + def __init__(self,packed,seed=197,synthetic_fraction=.2,source_weights_from=None): + super().__init__(packed,seed,synthetic_fraction,source_weights_from) + self.horizon_rng=np.random.default_rng(seed+300003) + def sample(self,batch,context=2048,horizon=1024): + return truncate_targets(super().sample(batch,context,horizon),self.horizon_rng,patch=16) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/full_paired/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/full_paired/model.py new file mode 100644 index 0000000000000000000000000000000000000000..dedcdff4698028a8ba655865f8425d0dc3ef0dfd --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/full_paired/model.py @@ -0,0 +1,204 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None,future_mask=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else future_mask) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + 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): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.confidence=nn.Linear(6,d,bias=False) + nn.init.zeros_(self.confidence.weight) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=128;recent=avg(k) # Match the training width, independently of padding. + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon,forecast_lengths=None): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + future_mask=None + horizon_meta=torch.full((b,1),math.log1p(max(32,h))/8,device=z.device) + if forecast_lengths is not None: + patch_count=((forecast_lengths+p-1)//p).clamp(min=1,max=h//p) + future_mask=torch.arange(h//p,device=z.device)[None,:]=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + # Fixed normalized difference statistics expose local and seasonal repeatability. + pos=torch.arange(c,device=z.device)[None,:];stats=[] + for j in range(3): + lag=torch.ones((b,1),dtype=torch.long,device=z.device) if j==0 else periods[:,j-1:j] + window=torch.full_like(lag,512) if j==0 else 8*lag + idx=pos-lag;safe=idx.clamp(min=0,max=c-1) + pairs=(idx>=0)&(pos>=c-window)&valid&valid.gather(1,safe) + count=pairs.sum(-1);difference=z-z.gather(1,safe) + absolute=(difference.abs()*pairs).sum(-1)/count.clamp(min=1) + rms=((difference.square()*pairs).sum(-1)/count.clamp(min=1)).sqrt() + absolute=torch.where(count>=8,absolute,1.) + rms=torch.where(count>=8,rms,math.sqrt(2.)) + stats.extend([absolute.clamp(max=10).log1p(),rms.clamp(max=10).log1p()]) + q=q+self.confidence(torch.stack(stats,-1))[:,None] + for layer in self.decoder:q=layer(q,pmask,x,future_mask=future_mask) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods,paired=True): + n=ctx.shape[0] + seen=torch.isfinite(target) + pos=torch.arange(target.shape[-1],device=target.device)[None,:]+1 + lengths=torch.where(seen,pos,0).max(-1).values.clamp(min=1) + q,mu,scale=model(torch.cat((ctx,-ctx),0),periods.repeat(2,1),target.shape[-1],forecast_lengths=lengths.repeat(2)) + if paired: + q=(q[:n]-q[n:].flip(-1))*.5 + mu=mu[:n];scale=scale[:n] + else: + ctx=torch.cat((ctx,-ctx),0) + target=torch.cat((target,-target),0) + periods=periods.repeat(2,1) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/large_corpus/data.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/large_corpus/data.py new file mode 100644 index 0000000000000000000000000000000000000000..a51e912d3c4b63a3ec0cd85133bf0e7aa3429569 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/large_corpus/data.py @@ -0,0 +1,73 @@ +import json,re +from pathlib import Path +import numpy as np +from model import periods_for_freq + +class Sampler: + def __init__(self,packed,seed=17,synthetic_fraction=.2,source_weights_from=None): + self.rng=np.random.default_rng(seed);self.synthetic_fraction=synthetic_fraction + self.root=Path(packed);meta=json.loads((self.root/'meta.json').read_text());self.dirs=meta['dirs'] + self.values=[];self.offsets=[];self.periods=[];self.lengths=[];weights=[] + for name in self.dirs: + records=json.loads((self.root/f'{name}.json').read_text()) + values=np.memmap(self.root/f'{name}.bin',dtype=np.float32,mode='r') + offsets=np.load(self.root/f'{name}.offsets.npy') + self.values.append(values);self.offsets.append(offsets);self.lengths.append(np.diff(offsets)) + self.periods.append(np.array([periods_for_freq(s['freq']) for s in records],np.int64)) + # Temperature 0.25 protects small, distinctive and low-frequency corpora. + weight_points=(Path(source_weights_from)/f'{name}.bin').stat().st_size//4 if source_weights_from else len(values) + w=min(weight_points,20_000_000)**.25 + if name.startswith(('era5_','cmip6_')):w*=.35 + if name.startswith(('m1_','monash_m3_','tourism_')):w*=3 + weights.append(w) + self.probs=np.array(weights)/sum(weights) + + def synthetic(self,n,p): + r=self.rng;t=np.arange(n,dtype=np.float32) + # New generator: damped trends, random Fourier seasonality, AR noise, + # intermittent demand, changepoints, and randomly scaled observation noise. + level=r.normal(0,2);sigma=10**r.uniform(-2,.1) + x=np.full(n,level,np.float32) + if r.random()<.8: + for period in p: + if period<2:continue + for k in range(1,int(r.integers(2,5))): + x+=r.normal()/k*np.sin((2*np.pi*k/period)*t+r.uniform(0,2*np.pi)) + if r.random()<.6: + slope=r.normal(0,.006);tau=10**r.uniform(2,4) + x+=slope*tau*(1-np.exp(-t/tau)) + noise=r.normal(0,sigma,n).astype(np.float32) + if r.random()<.5: + from scipy.signal import lfilter + phi=r.uniform(.2,.995);noise=lfilter([np.sqrt(1-phi*phi)],[1,-phi],noise) + x+=noise + if r.random()<.2: + start=int(r.integers(n));x[start:]+=r.normal(0,1) + if r.random()<.15:x=np.maximum(0,x)*(r.random(n)8 else nc + nh=min(horizon,l-cut);win=self.values[d][off+cut-nc:off+cut+nh].copy() + # Random aggregation teaches the same dynamics at coarser sampling frequencies. + if r.random()<.12 and l>=4*(context+horizon): + 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] + win=raw.reshape(-1,factor).mean(-1);nc=context;nh=horizon + periods[b]=np.maximum(1,np.rint(self.periods[d][i]/factor)).astype(np.int64) + else:periods[b]=self.periods[d][i] + ctx[b,-nc:]=win[:nc];tgt[b,:nh]=win[nc:nc+nh] + if r.random()<.05:ctx[b,r.random(context)<.05]=np.nan + sign=self.rng.choice(np.array([-1.,1.],np.float32),size=(batch,1)) + return ctx*sign,tgt*sign,periods diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/large_corpus/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/large_corpus/model.py new file mode 100644 index 0000000000000000000000000000000000000000..f8271c5b0bf9a5edb961e1c7839761fe50a2e40b --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/large_corpus/model.py @@ -0,0 +1,171 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024,recency_features=True): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.recency=nn.Linear(patch*4,d,bias=False) if recency_features else None + if self.recency is not None:nn.init.zeros_(self.recency.weight) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + if self.recency is not None: + pos=torch.arange(c,device=z.device)[None,:];extras=[] + for j in range(2): + period=periods[:,j:j+1] + recent=valid&(pos>=c-period);pooled=valid&(pos>=c-4*period) + nr=recent.sum(-1,keepdim=True).clamp(min=1);npool=pooled.sum(-1,keepdim=True).clamp(min=1) + mr=(z*recent).sum(-1,keepdim=True)/nr;mp=(z*pooled).sum(-1,keepdim=True)/npool + sr=(((z-mr).square()*recent).sum(-1,keepdim=True)/nr).sqrt() + sp=(((z-mp).square()*pooled).sum(-1,keepdim=True)/npool).sqrt().clamp(min=1e-4) + active=(period>=2)&(npool>=3*period) + shift=torch.where(active,mr-mp,0.).expand(-1,h) + amplitude=torch.where(active,(sr/sp).clamp(.5,2.)-1,0.) + extras.extend([shift,(base[:,:,5+2*j]-mp)*amplitude]) + extra=torch.stack(extras,-1) + q=q+self.recency(extra.reshape(b,h//p,p*4)) + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/large_sign/evaluate.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/large_sign/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..05f086d4d84def4a48165f9e65d2948877675e56 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/large_sign/evaluate.py @@ -0,0 +1,16 @@ +import sys,json,argparse,time,hashlib +from pathlib import Path +import torch +from predict import load_model,run +sys.path.insert(0,'/workspace/evaluation') +from score import score,json_safe + +ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',required=True);ap.add_argument('--valid',default='/workspace/research/valid_screen');ap.add_argument('--baseline',default='/workspace/research/valid_screen/baseline.json');a=ap.parse_args() +torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cuda.matmul.allow_tf32=False +t0=time.time();out=Path(a.out);v=Path(a.valid) +run(load_model(a.weights),v/'input',out) +base=json.loads(Path(a.baseline).read_text())['configs'] +rep=score(v/'truth',out,base) +rep['checkpoint_sha256']=hashlib.sha256(Path(a.weights).read_bytes()).hexdigest();rep['eval_seconds']=time.time()-t0 +(out/'report.json').write_text(json.dumps(json_safe(rep),indent=1)) +print(json.dumps({k:rep[k] for k in ('skill_score','rel_mase_gmean','rel_wql_gmean','n_failed','groups','eval_seconds')},indent=1)) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/large_sign/predict.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/large_sign/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..e20c6630475d6b4fa6906eb4ed9454b7b5aeec2c --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/large_sign/predict.py @@ -0,0 +1,43 @@ +import os,json,sys,time,argparse +from pathlib import Path +import numpy as np +import torch +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from model import DirectForecaster,periods_for_freq +import ts_io + +def load_model(checkpoint,device='cuda'): + ck=torch.load(checkpoint,map_location='cpu',weights_only=False) + model=DirectForecaster(**ck['config']).to(device);model.load_state_dict(ck['model']);model.eval() + return model + +def run(model,inp,out,batch=128,configs=None): + inp,out=Path(inp),Path(out);(out/'cases').mkdir(parents=True,exist_ok=True) + index=json.loads((inp/'index.json').read_text());start=time.time() + for cfg in index['configs']: + cid=cfg['config_id'] + if configs and cid not in configs:continue + case=ts_io.CaseFile(inp/'cases'/f'{cid}.h5');n,d,h=case.n,case.n_variates,case.prediction_length + quant=np.zeros((n,d,9,h),np.float32) + order=np.argsort(np.repeat(case.context_length,d),kind='stable') + for s in range(0,n*d,batch): + ids=order[s:s+batch];l=min(model.max_context,max(int(case.context_length[i//d]) for i in ids)) + ctx=np.full((len(ids),l),np.nan,np.float32) + for j,k in enumerate(ids): + x=case.context(int(k//d))[k%d,-l:];ctx[j,-len(x):]=x + x=torch.from_numpy(ctx).cuda();p=torch.tensor([periods_for_freq(cfg['freq'])]*len(ids),device=x.device) + with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):q=model.predict(x,p,h).float().cpu().numpy() + q=np.nan_to_num(q,nan=0,posinf=1e20,neginf=-1e20) + quant.reshape(n*d,9,h)[ids]=q + ts_io.write_prediction_file(out/'cases'/f'{cid}.h5',quant[:,:,4],quant) + case.close();print(f'{cid}: {n} instances, elapsed {time.time()-start:.1f}s',flush=True) + if (HERE/'model_manifest.json').exists():(out/'model_manifest.json').write_text((HERE/'model_manifest.json').read_text()) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('input');ap.add_argument('output');ap.add_argument('--weights',default=str(HERE/'weights.pt'));ap.add_argument('--batch',type=int,default=128);a=ap.parse_args() + torch.set_num_threads(4);torch.manual_seed(0);torch.backends.cudnn.benchmark=False + torch.backends.cuda.matmul.allow_tf32=False + run(load_model(a.weights),a.input,a.output,a.batch) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/patch16/convert.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/patch16/convert.py new file mode 100644 index 0000000000000000000000000000000000000000..b2cbc8fc919be6a77eca9ab19c4faa06060a2e0d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/patch16/convert.py @@ -0,0 +1,18 @@ +"""Convert only our own trained checkpoint from 32- to 16-point patches. + +Context/query projections fold the two halves by summation, preserving the +embedding of constant features. The output projection keeps the first half. +Attention/MLP weights are inherited unchanged; position units remain 32 points. +""" +import argparse,torch,hashlib +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('--input',required=True);ap.add_argument('--output',required=True);a=ap.parse_args() +ck=torch.load(a.input,map_location='cpu',weights_only=False);state=ck['model'];d=ck['config']['d'];assert ck['config']['patch']==32 +old=state['embed.0.weight'].reshape(d,2,32);state['embed.0.weight']=(old[:,:,:16]+old[:,:,16:]).reshape(d,32) +old=state['query.0.weight'].reshape(d,32,9);state['query.0.weight']=(old[:,:16]+old[:,16:]).reshape(d,16*9) +state['head.weight']=state['head.weight'].reshape(32,18,d)[:16].reshape(16*18,d).clone() +state['head.bias']=state['head.bias'].reshape(32,18)[:16].reshape(16*18).clone() +ck['config']['patch']=16 +ck['conversion']={'from_checkpoint':str(Path(a.input).resolve()),'from_sha256':hashlib.sha256(Path(a.input).read_bytes()).hexdigest(),'method':'fold input/query halves by summation; retain first 16 output rows; preserve physical positional units'} +ck['args']={**ck['args'],'initialize_from':str(Path(a.input).resolve()),'converted':True} +torch.save(ck,a.output) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/patch16/model.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/patch16/model.py new file mode 100644 index 0000000000000000000000000000000000000000..06cce56e2ce671b6683f0246900abfcac06bb3c0 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/patch16/model.py @@ -0,0 +1,154 @@ +"""Direct quantile encoder/decoder, random initialization; fixed history-derived seasonal features.""" +import math +import torch +from torch import nn +from torch.nn import functional as F + +def periods_for_freq(freq): + import re + 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' + if u in ('s','S'):p=(3600/n,86400/n) + elif u in ('T','min'):p=(1440/n,10080/n) + elif u in ('H','h'):p=(24/n,168/n) + elif u=='D':p=(7/n,365/n) + elif u=='B':p=(5/n,260/n) + elif u=='W':p=(52/n,1) + elif u in ('M','MS','ME'):p=(12/n,1) + elif u in ('Q','QS','QE'):p=(4/n,1) + else:p=(1,1) + return [max(1,round(x)) for x in p] + +def positional(pos,d): + freq=torch.exp(torch.arange(0,d,2,device=pos.device).float()*(-math.log(10000)/d)) + a=pos.float()[...,None]*freq + return torch.stack((a.sin(),a.cos()),dim=-1).flatten(-2) + +class Attention(nn.Module): + def __init__(self,d,heads): + super().__init__();self.h=heads;self.q=nn.Linear(d,d);self.kv=nn.Linear(d,2*d);self.out=nn.Linear(d,d) + def forward(self,x,context,mask=None): + b,t,d=x.shape;s=context.shape[1] + q=self.q(x).view(b,t,self.h,d//self.h).transpose(1,2) + k,v=self.kv(context).view(b,s,2,self.h,d//self.h).permute(2,0,3,1,4).unbind(0) + a=F.scaled_dot_product_attention(q,k,v,attn_mask=None if mask is None else mask[:,None,None,:]) + return self.out(a.transpose(1,2).reshape(b,t,d)) + +class Block(nn.Module): + def __init__(self,d,heads,cross=False): + super().__init__();self.norm1=nn.LayerNorm(d);self.attn=Attention(d,heads) + self.norm2=nn.LayerNorm(d);self.ff=nn.Sequential(nn.Linear(d,4*d),nn.GELU(),nn.Linear(4*d,d)) + self.cross=Attention(d,heads) if cross else None + if cross:self.normc=nn.LayerNorm(d);self.normctx=nn.LayerNorm(d) + def forward(self,x,mask=None,context=None): + y=self.norm1(x);x=x+self.attn(y,y,mask if context is None else None) + if self.cross is not None:x=x+self.cross(self.normc(x),self.normctx(context),mask) + return x+self.ff(self.norm2(x)) + +class DirectForecaster(nn.Module): + def __init__(self,d=256,heads=8,enc_layers=4,dec_layers=3,patch=32,max_context=4096,max_horizon=1024): + super().__init__();self.patch=patch;self.d=d;self.max_context=max_context;self.max_horizon=max_horizon + 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) + self.embed=nn.Sequential(nn.Linear(patch*2,d),nn.GELU(),nn.Linear(d,d)) + self.query=nn.Sequential(nn.Linear(patch*9,d),nn.GELU(),nn.Linear(d,d)) + self.metadata=nn.Sequential(nn.Linear(4,d),nn.GELU(),nn.Linear(d,d)) + self.encoder=nn.ModuleList(Block(d,heads) for _ in range(enc_layers)) + self.decoder=nn.ModuleList(Block(d,heads,True) for _ in range(dec_layers)) + self.norm=nn.LayerNorm(d);self.head=nn.Linear(d,patch*18) + nn.init.zeros_(self.head.weight);nn.init.zeros_(self.head.bias) + with torch.no_grad(): + bias=self.head.bias.view(patch,18);bias[:,10:]=math.log(math.expm1(.22)) + bias[:,:9]=torch.tensor([0.,0.,0.,0.,-.5,.5,-.5,.5,-1.]) + + @staticmethod + def standardize(ctx): + valid=torch.isfinite(ctx);x=torch.where(valid,ctx,0.) + count=valid.sum(-1,keepdim=True).clamp(min=1) + mu=x.sum(-1,keepdim=True)/count + var=torch.where(valid,(x-mu).square(),0.).sum(-1,keepdim=True)/count + scale=torch.maximum(var.sqrt(),mu.abs()*1e-4+1e-4) + z=torch.where(valid,(x-mu)/scale,0.).clamp(-30,30) + return z,valid,mu,scale + + @staticmethod + def features(z,valid,periods,h): + b,c=z.shape;dev=z.device + def avg(k): + return (z[:,-k:]*valid[:,-k:]).sum(-1)/valid[:,-k:].sum(-1).clamp(min=1) + last_idx=torch.where(valid,torch.arange(c,device=dev),-1).max(-1).values.clamp(min=0) + last=z.gather(1,last_idx[:,None])[:,0] + small=avg(32);medium=avg(128);level=avg(min(1024,c)) + bases=[x[:,None].expand(-1,h) for x in (last,small,medium,level)] + t=torch.arange(h,device=dev)[None,:] + for j in range(2): + p=periods[:,j:j+1].clamp(min=1) + anchor=c-p+t%p + vals=[];masks=[] + for cycle in range(4): + idx=anchor-cycle*p;safe=idx.clamp(min=0,max=c-1) + ok=(idx>=0)&valid.gather(1,safe) + vals.append(z.gather(1,safe));masks.append(ok) + vals=torch.stack(vals);masks=torch.stack(masks) + avgseason=(vals*masks).sum(0)/masks.sum(0).clamp(min=1) + avgseason=torch.where(masks.any(0),avgseason,level[:,None]) + bases.extend([torch.where(masks[0],vals[0],level[:,None]),avgseason]) + # A damped slope using two recent nonoverlapping means, a fixed transformation. + k=min(128,max(4,c//4));recent=avg(k) + older=(z[:,-2*k:-k]*valid[:,-2*k:-k]).sum(-1)/valid[:,-2*k:-k].sum(-1).clamp(min=1) + slope=((recent-older)/k).clamp(-.03,.03) + trend=recent[:,None]+slope[:,None]*(k*(1-torch.exp(-(t+k/2)/k))) + bases.append(trend) + return torch.stack(bases,-1) + + def forward(self,ctx,periods,horizon): + p=self.patch;h=math.ceil(horizon/p)*p + ctx=ctx[:,-self.max_context:] + ctx=F.pad(ctx,((-ctx.shape[1])%p,0),value=float('nan')) + z,valid,mu,scale=self.standardize(ctx) + b,c=z.shape;nt=c//p + base=self.features(z,valid,periods,h) + x=self.embed(torch.cat((z.view(b,nt,p),valid.view(b,nt,p).float()),-1)) + pmask=valid.view(b,nt,p).any(-1);pmask[:,-1]=True + 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) + emb=self.metadata(meta)[:,None] + x=x+positional((torch.arange(-nt,0,device=z.device)+.5)*p/32-.5,self.d)[None]+emb + for layer in self.encoder:x=layer(x,pmask) + 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 + for layer in self.decoder:q=layer(q,pmask,x) + out=self.head(self.norm(q)).view(b,h,18).float() + median=(out[:,:,:9].softmax(-1)*base).sum(-1)+out[:,:,9] + widths=F.softplus(out[:,:,10:]).clamp(max=20) + low=median[:,:,None]-widths[:,:,:4].flip(-1).cumsum(-1).flip(-1) + high=median[:,:,None]+widths[:,:,4:].cumsum(-1) + quant=torch.cat((low,median[:,:,None],high),-1)[:,:horizon] + return quant,mu,scale + + @torch.no_grad() + def predict(self,ctx,periods,horizon): + q,mu,scale=self(ctx,periods,horizon) + q=q*scale[:,:,None]+mu[:,:,None] + # Positivity is a fixed context rule, as in released foundation forecasters. + positive=((ctx>=0)|~torch.isfinite(ctx)).all(-1) + q=torch.where(positive[:,None,None],q.clamp(min=0),q) + return q.transpose(1,2) + +def loss_fn(model,ctx,target,periods): + q,mu,scale=model(ctx,periods,target.shape[-1]) + valid=torch.isfinite(target) + y=torch.nan_to_num((target-mu)/scale).clamp(-30,30) + err=y[:,:,None]-q + levels=torch.arange(1,10,device=q.device)/10 + # The evaluation gives equal importance to median MASE and average quantile loss. + pin=.5*torch.maximum(levels*err,(levels-1)*err).mean(-1)+.25*err[:,:,4].abs() + per=(pin*valid).sum(-1)/valid.sum(-1).clamp(min=1) + # A context-only seasonal scale makes highly predictable windows count more. + # It is used solely in the training loss; no inference adaptation is introduced. + with torch.no_grad(): + z,seen,_,_=model.standardize(ctx) + n=ctx.shape[-1];pos=torch.arange(n,device=ctx.device)[None,:] + lag=periods[:,0:1].clamp(min=1);idx=pos-lag;safe=idx.clamp(min=0) + pairs=(idx>=0)&seen&seen.gather(1,safe) + count=pairs.sum(-1) + errscale=((z-z.gather(1,safe)).abs()*pairs).sum(-1)/count.clamp(min=1) + errscale=torch.where(count>=8,errscale,1.) + weight=(.25+errscale).reciprocal().clamp(.25,4.) + return (per*weight).sum()/weight.sum() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/patch16/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/patch16/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf95c9aec5936076b881c340edb960786f2d40d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/patch16/publish.py @@ -0,0 +1,31 @@ +"""Assemble a relocatable package, then atomically exchange complete directories.""" +import json,os,shutil,ctypes,hashlib,argparse +from pathlib import Path +import torch +HERE=Path(__file__).resolve().parent + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('--weights',required=True);ap.add_argument('--out',default='/workspace/submission');ap.add_argument('--report',required=True);ap.add_argument('--experiments',default=str(HERE/'EXPERIMENTS.md'));a=ap.parse_args() + final=Path(a.out);staging=final.parent/f'.{final.name}-staging-{os.getpid()}' + shutil.rmtree(staging,ignore_errors=True);staging.mkdir(parents=True) + for file in ('model.py','predict.py','infer.sh','ts_io.py'): + shutil.copy(HERE/file,staging/file) + shutil.copy(a.weights,staging/'weights.pt');shutil.copy('/opt/runtime/requirements.txt',staging/'requirements.txt') + ck=torch.load(a.weights,map_location='cpu',weights_only=False);digest=hashlib.sha256((staging/'weights.pt').read_bytes()).hexdigest() + sources=json.loads(Path('/workspace/research/packed_sample/meta.json').read_text())['dirs'] + manifest={'name':'direct-seasonal-quantile-v1','contract':'timeseries-forecast/v1','parameters':sum(x.numel() for x in ck['model'].values()),'pretrained_assets':[],'sources_used':[f'gifteval_pretrain/{d}' for d in sources]+['synthetic:direct_v1 damped trends, random Fourier seasonality, AR noise, intermittent demand and changepoints; data.py generator seed 17'],'weights_sha256':digest,'training_step':ck['step'],'config':ck['config'],'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.'} + (staging/'model_manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') + (staging/'config.json').write_text(json.dumps(ck['config'],indent=2)+'\n') + shutil.copy(a.experiments,staging/'EXPERIMENTS.md');shutil.copy(a.report,staging/'validation_report.json') + # Include generator/sampler provenance, which is not imported by inference. + (staging/'provenance').mkdir() + for file in ('pack.py','data.py','train.py'):shutil.copy(HERE/file,staging/'provenance'/file) + (staging/'README.md').write_text('# Direct seasonal quantile foundation forecaster\n\nRun `bash infer.sh INPUT_DIR OUTPUT_DIR`. This package contains all inference assets and uses only its supplied input directory. The 6.76M 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.\n\nThe 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.\n') + if final.exists(): + libc=ctypes.CDLL(None,use_errno=True) + if libc.renameat2(-100,os.fsencode(staging),-100,os.fsencode(final),2):raise OSError(ctypes.get_errno(),os.strerror(ctypes.get_errno())) + shutil.rmtree(staging) + else:os.replace(staging,final) + print(json.dumps(manifest,indent=1)) + +if __name__=='__main__':main() diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/patch16/record.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/patch16/record.py new file mode 100644 index 0000000000000000000000000000000000000000..1850a33f46fa3ee4d78cac4a5d6152404801a131 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/member1/training/patch16/record.py @@ -0,0 +1,9 @@ +import argparse,json,math +from pathlib import Path +ap=argparse.ArgumentParser();ap.add_argument('report');ap.add_argument('--label',required=True);ap.add_argument('--outcome',default='Screened for model selection.');a=ap.parse_args() +r=json.loads(Path(a.report).read_text());p=Path(__file__).with_name('EXPERIMENTS.md') +lines=[f'\n## {a.label}',f'- Checkpoint SHA-256: `{r.get("checkpoint_sha256","see model_manifest.json")}`.',f'- Evaluation: {r["n_configs"]} configurations, {r["n_instances"]} instances, {r["n_failed"]} failed configurations; {r.get("eval_seconds","not separately timed")} seconds.',f'- Overall skill {r["skill_score"]:.6f}; relative MASE {r["rel_mase_gmean"]:.6f}; relative WQL {r["rel_wql_gmean"]:.6f}.'] +for group,entries in r['groups'].items(): + lines.append(f'- {group} skill: '+', '.join(f'{k}={1-math.sqrt(v["rel_mase_gmean"]*v["rel_wql_gmean"]):.4f}' for k,v in entries.items())+'.') +lines.append('- Outcome: '+a.outcome) +with p.open('a') as f:f.write('\n'.join(lines)+'\n') diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/publish.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/publish.py new file mode 100644 index 0000000000000000000000000000000000000000..4d8dc6acbf326b792c98ab331aec1d5817571881 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/provenance/publish.py @@ -0,0 +1,108 @@ +"""Assemble and atomically publish a complete six-member, fixed-horizon-rule package.""" +import argparse +import ctypes +import hashlib +import json +import os +import shutil +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ap = argparse.ArgumentParser() +ap.add_argument('--member', action='append', required=True) +ap.add_argument('--out', required=True) +ap.add_argument('--report') +ap.add_argument('--experiments', default='/workspace/research/direct_v1/EXPERIMENTS.md') +a = ap.parse_args() +assert len(a.member) == 6 +final = Path(a.out) +stage = final.parent / f'.{final.name}-staging-{os.getpid()}' +shutil.rmtree(stage, ignore_errors=True) +stage.mkdir(parents=True) + +def digest(path): + h = hashlib.sha256() + with Path(path).open('rb') as f: + for block in iter(lambda: f.read(8 * 1024 * 1024), b''): + h.update(block) + return h.hexdigest() + +for name in ('infer.sh', 'predict.py', 'model.py', 'seasonal.py', 'continuity.py', + 'zero_mass.py', 'ts_io.py'): + shutil.copy2(HERE / 'runtime' / name, stage / name) +shutil.copy2('/opt/runtime/requirements.txt', stage / 'requirements.txt') +shutil.copy2(a.experiments, stage / 'EXPERIMENTS.md') +members, sources, lineage = [], set(), {} +for i, source in enumerate(map(Path, a.member)): + manifest = json.loads((source / 'model_manifest.json').read_text()) + assert manifest['pretrained_assets'] == [] + for shared in ['seasonal.py','continuity.py','zero_mass.py']: + assert digest(source/shared)==digest(stage/shared),'Members must retain identical fixed postprocessing rules' + name = f'member{i}.pt' + model_code = f'model{i}.py' + shutil.copy2(source / 'model.py', stage / model_code) + assert digest(stage / model_code) == manifest['runtime_code_sha256']['model.py'] + shutil.copy2(source / 'weights.pt', stage / name) + assert digest(stage / name) == manifest['weights_sha256'] + members.append({'weights': name, 'weights_sha256': manifest['weights_sha256'], + 'parameters': manifest['parameters'], 'config': manifest['config'], 'model_code': model_code}) + sources.update(manifest['sources_used']) + for item in manifest['training_lineage']: + lineage.setdefault(item['sha256'], item) + dst = stage / 'provenance' / f'member{i}' + dst.mkdir(parents=True) + shutil.copy2(source / 'model_manifest.json', dst / 'model_manifest.json') + shutil.copytree(source / 'provenance', dst / 'training') +shutil.copy2(__file__, stage / 'provenance' / 'publish.py') +for script in HERE.glob('*.py'): + shutil.copy2(script, stage / 'provenance' / ('blend_' + script.name)) +descriptor = {'members': members, 'horizon_threshold': 720, 'blend_coefficient': .5, + 'weights_below_threshold': [.25,.25,.25,.125,0,.125], + 'weights_at_or_above_threshold': [.25,.25,.25,0,.125,.125], + 'composition': 'Every member forecasts every instance. A=(F0+F1+F2+F[4 if H>=720 else3])/4 and B=(F0+F1+F2+F5)/4 are ordered FP32 quarter means after fixed member rules; output=(A+B)/2 in FP32'} +(stage / 'config.json').write_text(json.dumps(descriptor, indent=2) + '\n') +identifier = digest(stage / 'config.json') +manifest = { + 'name': 'direct-seasonal-six-member-equal-blend', 'contract': 'timeseries-forecast/v1', + 'parameters': sum(m['parameters'] for m in members), 'pretrained_assets': [], + 'sources_used': sorted(sources), 'members': members, + 'checkpoint_sha256': identifier, + 'checkpoint_digest_method': 'SHA-256 of config.json, including ordered member weight hashes', + 'training_lineage': list(lineage.values()), 'ensemble_weights_by_horizon': {'below720':[.25,.25,.25,.125,0,.125], 'at_least720':[.25,.25,.25,0,.125,.125]}, + 'every_member_forecasts_every_instance': True, + 'member_history_caps': [{'input_and_summary': m['config']['max_context'], 'encoder_and_normalization': m['config'].get('encoder_context',m['config']['max_context']), 'fixed_rules': m['config'].get('encoder_context',m['config']['max_context'])} for m in members], + 'postprocessing_order': 'each member: sign averaging, positivity, aligned seasonal rule, continuity, zero0.4, finite-value replacement; then form ordered E154 horizon-rule quarter mean and E156 seasonal48 quarter mean, and average those two in FP32 with equal weight', + 'runtime_code_sha256': {p.name: digest(p) for p in stage.iterdir() if p.suffix in ('.py', '.sh')}, + 'notes': 'All members originate from random initialization in this workspace. Only declared pretraining sources and local generators were used. Validation is selection/diagnostics only. No inference-time fitting or parameter adaptation.', +} +(stage / 'model_manifest.json').write_text(json.dumps(manifest, indent=2) + '\n') +if a.report: + report = json.loads(Path(a.report).read_text()) + assert report['checkpoint_sha256'] == identifier + shutil.copy2(a.report, stage / 'validation_report.json') +else: + report = {'status': 'candidate validation pending'} + (stage / 'validation_report.json').write_text(json.dumps(report) + '\n') +if final.resolve() == Path('/workspace/submission').resolve(): + assert a.report and report['n_configs'] == 97 and report['n_instances'] == 151170 + assert report['n_failed'] == 0 +patch_sizes = ', '.join(str(m['config'].get('input_patch', m['config']['patch'])) + '/' + str(m['config']['patch']) for m in members) +(stage / 'README.md').write_text(f'''# Six-member seasonal foundation forecaster + +Run `bash infer.sh INPUT_DIR OUTPUT_DIR`. All runtime assets are included, with versions pinned in requirements.txt. The package contains six locally trained models totaling {manifest['parameters']:,} parameters. Every member forecasts every instance. First form two ordered FP32 quarter means: A uses members0,1,2 plus member3 for horizons below720, or member4 otherwise; B uses members0,1,2,5. The final quantiles are the equal FP32 average (A+B)/2. All six contributions are computed before this fixed composition. This one equal blend was selected on validation, with no coefficient or horizon-threshold sweep and no fitting on input contexts. + +Each member retains its declared context limits, listed in model_manifest.json under member_history_caps. A model with a separate encoder_context uses longer history only for learned seasonal summaries; its encoder, normalization and fixed forecast rules use the shorter declared limit. Their history/forecast patch sizes are {patch_sizes}, in member order. Each member retains its own original model implementation and normalization; overflow handling follows each member's own implementation. Each member uses finite-history normalization and the same fixed sign averaging, positivity, seasonal, continuity and zero-mass rules. The seasonal template aligns four cycles to the latest cycle's mean and amplitude. The trend summary uses a fixed width of 128 observations. The zero projection threshold is 0.4 context standard deviations. No additional zero projection is applied after averaging. There is no inference-time training, fitting or parameter adaptation. + +model_manifest.json declares every source, member hash and training lineage. config.json contains relative member paths and their hashes. The original member manifests and all trainer/generator code are archived in provenance/. No pretrained assets were used. Normalization uses the supplied context and needs no external statistics. + +EXPERIMENTS.md records hypotheses, negative results, compute, group metrics and hashes. validation_report.json records the package evaluation. Validation and earlier-cutoff scores are not the held-out reward scale. +''') +if final.exists(): + libc = ctypes.CDLL(None, use_errno=True) + if libc.renameat2(-100, os.fsencode(stage), -100, os.fsencode(final), 2): + raise OSError(ctypes.get_errno(), os.strerror(ctypes.get_errno())) + shutil.rmtree(stage) +else: + os.replace(stage, final) +print(json.dumps({'out': str(final), 'checkpoint_sha256': identifier, + 'parameters': manifest['parameters']})) diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/requirements.txt b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..ca733199990e5dc8e6a90509cc691f00ab8e9f5d --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/requirements.txt @@ -0,0 +1,12 @@ +# Runtime pins recorded from the contributor's working environment on 2026-09-17 (Python 3.11). +# torch comes from the pytorch/pytorch:2.14.0-cuda12.6-cudnn9-runtime base image (cu130 needs driver >= 580). +torch==2.14.0 +numpy==2.4.6 +h5py==3.16.0 +pandas==2.3.3 +scipy==1.17.1 +pyarrow==25.0.1 +huggingface-hub==0.36.2 +einops==0.8.2 +safetensors==0.8.0 +pytest==9.1.1 diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/seasonal.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/seasonal.py new file mode 100644 index 0000000000000000000000000000000000000000..cd8d8ebbf65c59c69f3d1c537e8cd5cb024d0330 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/seasonal.py @@ -0,0 +1,51 @@ +"""A fixed confidence gate for highly repeatable history; no fitted parameters.""" +import numpy as np + +def apply_gate(ctx,periods,quant,threshold=.25,strength=1.,cycles=4,mode='aligned'): + # Each row uses only its own context. Quantile blending preserves ordering. + b,_,h=quant.shape + out=quant.copy() + for i in range(b): + x=ctx[i];valid=np.isfinite(x) + if not valid.any():continue + x=x[np.flatnonzero(valid)[0]:] + best=None + for p in periods[i]: + p=int(p) + if p<2 or len(x)<3*p:continue + k=min(len(x)//p,8);history=x[-k*p:] + pairs=np.isfinite(history[p:])&np.isfinite(history[:-p]) + if pairs.sum()0) + if mode in ('centered','aligned'): + mu=mu+np.nanmean(seasons[-1])-np.nanmean(mu) + if mode=='aligned' and np.isfinite(seasons[-1]).sum()>=max(2,.75*p): + noise=float(np.mean(err.astype(np.float64)**2)/2) + target_var=max(0.,float(np.nanvar(seasons[-1]))-noise) + template_var=max(0.,float(np.nanvar(mu))-noise/min(k,cycles)) + ratio=float(np.clip(np.sqrt(target_var/max(template_var,1e-12)),.5,2.)) + center=float(np.nanmean(mu));mu=center+(mu-center)*ratio + if mode=='exponential': + w=.5**np.arange(len(recent)-1,-1,-1,dtype=np.float32) + den=(w[:,None]*np.isfinite(recent)).sum(0) + mu=np.divide((w[:,None]*np.nan_to_num(recent)).sum(0),den,out=np.full(p,np.nan,np.float32),where=den>0) + # Error of a season relative to the previous one, corrected for averaging. + sigma=float(np.sqrt(np.mean(err.astype(np.float64)**2)/2*(1+1/min(k,cycles)))) + idx=np.arange(h)%p;median=mu[idx] + z=np.array([-1.2815515655,-.8416212336,-.5244005127,-.2533471031,0,.2533471031,.5244005127,.8416212336,1.2815515655]) + sq=median[None]+z[:,None]*sigma + sq=np.where(np.isfinite(sq),sq,quant[i]) + if np.nanmin(x)>=0:sq=np.maximum(0,sq) + best=(weight,sq) + if best is not None:out[i]=(1-best[0])*quant[i]+best[0]*best[1] + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/ts_io.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/ts_io.py new file mode 100644 index 0000000000000000000000000000000000000000..21312ff6b9a3eada8e4042ebf33ce8147f78db6a --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/ts_io.py @@ -0,0 +1,433 @@ +"""Shared I/O for the timeseries-forecasting task (contract timeseries-forecast/v1). + +Three things live here because the case builder, the grader, the starter and +the reference packages must agree on them exactly: + +1. GIFT-Eval protocol constants and the frequency -> horizon / seasonality + tables, transcribed from gift-eval `src/gift_eval/data.py` at commit + db743860 and gluonts 0.15.1 `time_feature.seasonality`. They are tables, + not runtime derivations, so a pandas alias rename cannot silently change a + horizon or a seasonality. +2. Readers for the Arrow `save_to_disk` layout of Salesforce/GiftEval + (`/[/]data-00000-of-00001.arrow`), implemented with pyarrow + only, and the rolling-window instance generator that reproduces + `Dataset.test_data` / `Dataset.validation_dataset` of gift-eval. +3. The case-file format: one HDF5 file per (dataset, frequency, term) config + holding every forecast instance's context, and one HDF5 prediction file per + config holding the mean and the nine decile forecasts. +""" +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import stat +from pathlib import Path + +import numpy as np + +CONTRACT = "timeseries-forecast/v1" +QUANTILE_LEVELS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) +CONTEXT_CAP = 16384 # observations of history given per instance; the only deviation from GIFT-Eval (see contract.md) +TEST_SPLIT = 0.1 +MAX_WINDOW = 20 +TERM_MULTIPLIER = {"short": 1, "medium": 10, "long": 15} +PRED_LENGTH_MAP = {"M": 12, "W": 8, "D": 30, "H": 48, "T": 48, "S": 60} +M4_PRED_LENGTH_MAP = {"A": 6, "Q": 8, "M": 18, "W": 13, "D": 14, "H": 48} +# gluonts DEFAULT_SEASONALITIES for the base unit; a multiple n gives base // n when it divides, else 1 +BASE_SEASONALITY = {"S": 3600, "T": 1440, "H": 24, "D": 1, "W": 1, "M": 12, "B": 5, "Q": 4, "A": 1} +_UNIT_ALIASES = {"min": "T", "h": "H", "s": "S", "Y": "A", "YE": "A", "QE": "Q", "ME": "M", "MS": "M", "AS": "A", "YS": "A", "QS": "Q"} +_FREQ_RE = re.compile(r"^(\d*)([A-Za-z]+)(?:-([A-Za-z]+))?$") + + +def parse_freq(freq: str) -> tuple[int, str]: + """'15T' -> (15, 'T'); 'W-SUN' -> (1, 'W'); 'A-DEC' -> (1, 'A'); 'h' -> (1, 'H').""" + m = _FREQ_RE.match(freq.strip()) + if not m: + raise ValueError(f"unrecognised frequency {freq!r}") + n = int(m.group(1) or 1) + unit = _UNIT_ALIASES.get(m.group(2), m.group(2)) + if unit not in BASE_SEASONALITY: + raise ValueError(f"unrecognised frequency unit in {freq!r}") + return n, unit + + +def prediction_length(dataset: str, freq: str, term: str) -> int: + _, unit = parse_freq(freq) + table = M4_PRED_LENGTH_MAP if "m4" in dataset else PRED_LENGTH_MAP + return TERM_MULTIPLIER[term] * table[unit] + + +def seasonality(freq: str) -> int: + n, unit = parse_freq(freq) + base = BASE_SEASONALITY[unit] + q, r = divmod(base, n) + return q if r == 0 else 1 + + +def n_windows(dataset: str, min_series_length: int, pred_len: int) -> int: + if "m4" in dataset: + return 1 + w = math.ceil(TEST_SPLIT * min_series_length / pred_len) + return min(max(1, w), MAX_WINDOW) + + +def config_id(dataset: str, freq_unit: str, term: str) -> str: + """Leaderboard key 'electricity/H/short' -> file stem 'electricity__H__short' (the freq subfolder is dropped: keys are unique).""" + return f"{dataset.split('/')[0]}__{freq_unit}__{term}" + + +# gift-eval notebooks: results keys use the frequency sub-folder (or dataset_properties.json for flat datasets) and pretty names +LEADERBOARD_FREQ = {"m4_yearly": "A", "m4_quarterly": "Q", "m4_monthly": "M", "m4_weekly": "W", "m4_daily": "D", "m4_hourly": "H", + "hospital": "M", "covid_deaths": "D", "temperature_rain_with_missing": "D", "car_parts_with_missing": "M", + "restaurant": "D", "bizitobs_application": "10S", "bizitobs_service": "10S"} +LEADERBOARD_NAME = {"saugeenday": "saugeen", "temperature_rain_with_missing": "temperature_rain", + "kdd_cup_2018_with_missing": "kdd_cup_2018", "car_parts_with_missing": "car_parts"} + + +def leaderboard_key(dataset: str, term: str) -> str: + """Key used in the GIFT-Eval results CSVs, e.g. 'electricity/15T/short', 'kdd_cup_2018/H/short', 'loop_seattle/5T/short' (lower-cased).""" + base, _, sub = dataset.partition("/") + freq = sub if sub else LEADERBOARD_FREQ[base] + base = base.lower() + return f"{LEADERBOARD_NAME.get(base, base)}/{freq}/{term}" + + +VALID_MIN_CONTEXT = 8 # a validation window is staged only if at least this many observations precede it + + +# ----------------------------------------------------------------------------- Arrow readers + + +def arrow_path(root: Path, dataset: str) -> Path: + return Path(root) / dataset / "data-00000-of-00001.arrow" + + +def read_arrow_dataset(root: Path, dataset: str): + """Return (item_ids, starts (datetime64[s]), freq, series) for one GIFT-Eval dataset. + + `series` is a list of float32 arrays of shape (D, T); univariate datasets + give D = 1. Missing values are NaN as stored. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + series = [] + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + # multivariate: fixed_size_list> (or list>) -> (D, T) per item + if pa.types.is_fixed_size_list(target.type): + k = target.type.list_size + outer_off = (np.arange(len(target) + 1, dtype=np.int64) + target.offset) * k + else: + outer_off = target.offsets.to_numpy() + inner = target.values + inner_off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + d0, d1 = outer_off[i], outer_off[i + 1] + rows = [flat[inner_off[j]:inner_off[j + 1]] for j in range(d0, d1)] + if len({len(r) for r in rows}) != 1: + raise ValueError(f"{dataset} item {item_ids[i]}: variates of unequal length") + series.append(np.stack(rows)) + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False).astype(np.float32) + for i in range(len(target)): + series.append(flat[off[i]:off[i + 1]][None, :]) + return item_ids, starts, freq, series + + +def read_arrow_index(root: Path, dataset: str): + """Series metadata without building one array per series: (item_ids, starts, freq, lengths, fingerprints). + + The planning passes (cutoff cohorts, validation boundaries) need only lengths and identities, and a dataset can + hold 48,000 series, so they avoid the per-series slicing that `read_arrow_dataset` does. + """ + import pyarrow as pa + + with open(arrow_path(root, dataset), "rb") as f: + table = pa.ipc.open_stream(f).read_all() + item_ids = table.column("item_id").to_pylist() + starts = table.column("start").to_pandas().to_numpy().astype("datetime64[s]") + freq = table.column("freq")[0].as_py() + target = table.column("target").combine_chunks() + if pa.types.is_list(target.type.value_type) or pa.types.is_fixed_size_list(target.type.value_type): + inner = target.values + off = inner.offsets.to_numpy() + flat = inner.values.to_numpy(zero_copy_only=False) + width = target.type.list_size if pa.types.is_fixed_size_list(target.type) else None + if width is None: + outer = target.offsets.to_numpy() + first = outer[:-1] + else: + first = (np.arange(len(target)) + target.offset) * width + else: + off = target.offsets.to_numpy() + flat = target.values.to_numpy(zero_copy_only=False) + first = np.arange(len(target)) + lengths = (off[first + 1] - off[first]).astype(np.int64) + fingerprints = [] + for i, start in enumerate(first): + a, b = off[start], off[start + 1] + head, tail = flat[a:min(a + 32, b)], flat[max(a, b - 32):b] + fingerprints.append((int(lengths[i]), hashlib.sha256(head.tobytes() + tail.tobytes()).hexdigest()[:16])) + return item_ids, starts, freq, lengths, fingerprints + + +def config_table(root: Path, dataset: str, term: str) -> dict: + """Protocol quantities of one (dataset, term) config, read from the Arrow file.""" + item_ids, starts, freq, series = read_arrow_dataset(root, dataset) + n, unit = parse_freq(freq) + lengths = np.array([s.shape[1] for s in series]) + pred_len = prediction_length(dataset, freq, term) + windows = n_windows(dataset, int(lengths.min()), pred_len) + return { + "dataset": dataset, "freq": freq, "freq_unit": unit, "freq_multiple": n, "term": term, + "config_id": config_id(dataset, unit, term), "leaderboard_key": leaderboard_key(dataset, term), + "prediction_length": pred_len, "seasonality": seasonality(freq), "windows": windows, + "n_series": len(series), "n_variates": int(series[0].shape[0]), + "min_length": int(lengths.min()), "max_length": int(lengths.max()), + "n_test_instances": len(series) * windows, "n_valid_instances": len(series), + } + + +def test_cutoffs(length: int, pred_len: int, windows: int) -> list[int]: + """gluonts split(offset=-L*W).generate_instances(L, windows=W, distance=L): cutoff k = T - L*W + k*L.""" + return [length - pred_len * windows + k * pred_len for k in range(windows)] + + +def valid_cutoff(length: int, pred_len: int, windows: int) -> int: + """This config's own validation window: the last horizon of gift-eval's `validation_dataset` prefix, which + `training_dataset` (offset -L*(W+1)) excludes. + + A series usually appears in several configs (terms, and aggregated frequencies of the same meter), whose test + regions start at different times; the earliest of them is the only safe boundary for the agent-visible validation + data. `make_cases.py` therefore stages validation against that boundary and uses this function only as the + per-config upper bound. + """ + return length - pred_len * (windows + 1) + + +def steps_between(start: np.datetime64, freq: str, timestamp: str) -> int: + """How many steps of `freq` separate `start` from `timestamp` (the index of that timestamp in the series grid).""" + import pandas as pd + + multiple, _ = parse_freq(freq) + f = _pandas_freq(freq) + # a Period difference is in base units ('15T' counts minutes), so divide by the multiple to get steps + delta = (pd.Period(pd.Timestamp(timestamp), freq=f) - pd.Period(pd.Timestamp(start), freq=f)).n + return int(delta) // multiple + + +@functools.lru_cache(maxsize=4096) +def _base_period(start: str, freq: str): + import pandas as pd + + return pd.Period(pd.Timestamp(start), freq=_pandas_freq(freq)) + + +def timestamp_after(start: np.datetime64, freq: str, steps: int) -> str: + """ISO timestamp of the observation `steps` after `start` under pandas frequency `freq`.""" + return (_base_period(str(start), freq) + int(steps)).to_timestamp().isoformat() + + +def _pandas_freq(freq: str) -> str: + n, unit = parse_freq(freq) + anchor = freq.split("-")[1] if "-" in freq else "" + new = {"T": "min", "H": "h", "S": "s", "A": "Y", "M": "M", "Q": "Q", "W": "W", "D": "D", "B": "B"}[unit] + return f"{n if n != 1 else ''}{new}{'-' + anchor if anchor else ''}" + + +# ----------------------------------------------------------------------------- case files + + +def write_case_file(path: Path, meta: dict, contexts: list[np.ndarray], item_ids, windows, forecast_starts, history_lengths, cohorts=None): + """contexts: list of (D, T_i) float32 arrays (already capped); history_lengths: uncapped history length per instance; + cohorts: verifier invocation group per instance (see make_cases.py), optional.""" + import h5py + + d = int(meta["n_variates"]) + lengths = np.array([c.shape[1] for c in contexts], dtype=np.int64) + offsets = np.zeros(len(contexts) + 1, dtype=np.int64) + offsets[1:] = np.cumsum(lengths * d) + values = np.concatenate([c.reshape(-1) for c in contexts]).astype(np.float32) if contexts else np.zeros(0, np.float32) + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("values", data=values) + f.create_dataset("offsets", data=offsets) + f.create_dataset("context_length", data=lengths) + f.create_dataset("history_length", data=np.asarray(history_lengths, dtype=np.int64)) + f.create_dataset("item_id", data=np.array(item_ids, dtype=h5py.string_dtype())) + f.create_dataset("window", data=np.asarray(windows, dtype=np.int64)) + f.create_dataset("forecast_start", data=np.array(forecast_starts, dtype=h5py.string_dtype())) + if cohorts is not None: + f.create_dataset("cohort", data=np.asarray(cohorts, dtype=np.int64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + f.attrs["contract"] = CONTRACT + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + + +def write_case_subset(src: "CaseFile", indices, dst: Path): + """Write the instances `indices` of an open CaseFile to a new case file (same attrs, contexts copied).""" + import h5py + + indices = np.asarray(indices, dtype=np.int64) + contexts = [src.context(int(i)) for i in indices] + meta = {k: v for k, v in src.meta.items() if k not in ("contract", "quantile_levels")} + write_case_file(dst, meta, contexts, [src.item_id[i] for i in indices], src.window[indices], + [src.forecast_start[i] for i in indices], src.history_length[indices]) + with h5py.File(dst, "r+") as f: + f.create_dataset("cohort", data=src.cohort[indices]) + f.create_dataset("source_index", data=indices) + + +class CaseFile: + """Read-only view of one staged config: `meta` attrs and `context(i)` -> (D, T_i) float32.""" + + def __init__(self, path: Path): + import h5py + + self.path = Path(path) + self._f = h5py.File(self.path, "r") + self.meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in self._f.attrs.items()} + self.n_variates = int(self.meta["n_variates"]) + self.prediction_length = int(self.meta["prediction_length"]) + self.offsets = self._f["offsets"][()] + self.n = len(self.offsets) - 1 + self.item_id = [s.decode() if isinstance(s, bytes) else s for s in self._f["item_id"][()]] + self.window = self._f["window"][()] + self.context_length = self._f["context_length"][()] + self.forecast_start = [s.decode() if isinstance(s, bytes) else s for s in self._f["forecast_start"][()]] + self.history_length = self._f["history_length"][()] + self.cohort = self._f["cohort"][()] if "cohort" in self._f else np.zeros(self.n, dtype=np.int64) + self.source_index = self._f["source_index"][()] if "source_index" in self._f else np.arange(self.n) + + def context(self, i: int) -> np.ndarray: + v = self._f["values"][self.offsets[i]:self.offsets[i + 1]] + return v.reshape(self.n_variates, -1) + + def contexts(self): + values = self._f["values"][()] + for i in range(self.n): + yield values[self.offsets[i]:self.offsets[i + 1]].reshape(self.n_variates, -1) + + def close(self): + self._f.close() + + +def write_prediction_file(path: Path, mean: np.ndarray, quantiles: np.ndarray, meta: dict | None = None): + """mean (N, D, H) float32; quantiles (N, D, 9, H) float32 ordered by QUANTILE_LEVELS.""" + import h5py + + mean = np.asarray(mean, dtype=np.float32) + quantiles = np.asarray(quantiles, dtype=np.float32) + 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): + raise ValueError(f"bad prediction shapes mean={mean.shape} quantiles={quantiles.shape}") + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("mean", data=mean) + f.create_dataset("quantiles", data=quantiles) + f.attrs["quantile_levels"] = np.array(QUANTILE_LEVELS) + f.attrs["contract"] = CONTRACT + for k, v in (meta or {}).items(): + f.attrs[k] = v + + +PREDICTION_DATASETS = ("mean", "quantiles") + + +def open_package_h5(path, names=PREDICTION_DATASETS): + """Open an HDF5 file a package wrote, refusing anything but a regular file whose `names` are plain datasets. + + The verifier reads package output with its own privileges, outside every isolation mode, so it must not follow + anything the package put in the file: an external or soft link, a virtual dataset or external raw storage can + point at the held-out labels and would be resolved here. A FIFO or device in place of the file would block.""" + import h5py + + st = os.lstat(path) + if not stat.S_ISREG(st.st_mode): + raise ValueError("not a regular file (symlinks, FIFOs and devices are refused)") + f = h5py.File(path, "r") + try: + for name in names: + link = f.get(name, getlink=True) + if link is None: + raise KeyError(f"no {name!r} dataset") + if not isinstance(link, h5py.HardLink): + raise ValueError(f"{name!r} is a {type(link).__name__}; only plain datasets are read") + d = f[name] + if not isinstance(d, h5py.Dataset) or d.is_virtual or d.external: + raise ValueError(f"{name!r} is not a plain dataset (virtual or external storage is refused)") + except Exception: + f.close() + raise + return f + + +def prediction_shapes(path: Path): + """(mean shape, quantiles shape, attrs) without reading the arrays, so a mis-declared file cannot exhaust memory.""" + with open_package_h5(path) as f: + attrs = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return tuple(f["mean"].shape), tuple(f["quantiles"].shape), attrs + + +def read_prediction_file(path: Path, expect: tuple | None = None): + """Read mean and quantiles. `expect` is the required mean shape (N, D, H); the file is rejected before it is read.""" + with open_package_h5(path) as f: + got_m, got_q = tuple(f["mean"].shape), tuple(f["quantiles"].shape) + want_q = None if expect is None else (expect[0], expect[1], len(QUANTILE_LEVELS), expect[2]) + if expect is not None and (got_m != tuple(expect) or got_q != want_q): + raise ValueError(f"bad shapes mean={got_m} quantiles={got_q} expected {tuple(expect)} / {want_q}") + return f["mean"][()], f["quantiles"][()] + + +def write_truth_file(path: Path, labels: np.ndarray, seasonal_error: np.ndarray, meta: dict): + """labels (N, D, H) float32 with NaN where the benchmark has missing targets; seasonal_error (N, D) float64.""" + import h5py + + Path(path).parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("labels", data=np.asarray(labels, dtype=np.float32)) + f.create_dataset("seasonal_error", data=np.asarray(seasonal_error, dtype=np.float64)) + for k, v in meta.items(): + f.attrs[k] = json.dumps(v) if isinstance(v, (dict, list)) else v + + +def read_truth_file(path: Path): + import h5py + + with h5py.File(path, "r") as f: + meta = {k: (v.item() if hasattr(v, "item") and np.ndim(v) == 0 else v) for k, v in f.attrs.items()} + return f["labels"][()], f["seasonal_error"][()], meta + + +def seasonal_error(history: np.ndarray, m: int) -> np.ndarray: + """gluonts 0.15.1 seasonal error on the full (uncapped) history, per variate. + + Reproduces `gluonts.model.evaluation._get_data_batch` with + `mask_invalid_label=True`: the history is a masked array, so the mean of + |x[t] - x[t-m]| runs over the pairs where both observations are finite. + If m > T the lag is 1 (gluonts.ev.ts_stats.seasonal_error). A variate with + no valid pair gets NaN. + """ + t = history.shape[-1] + lag = m if m <= t else 1 + if t <= lag: + return np.full(history.shape[0], np.nan) + x = history.astype(np.float64) + diff = np.abs(x[:, lag:] - x[:, :-lag]) + valid = np.isfinite(diff) + count = valid.sum(axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + out = np.where(valid, diff, 0.0).sum(axis=-1) / count + out[count == 0] = np.nan + return out diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/validation_report.json b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/validation_report.json new file mode 100644 index 0000000000000000000000000000000000000000..796bc2b8be0244ae038da2046e127d3667e55709 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/validation_report.json @@ -0,0 +1,4892 @@ +{ + "contract": "timeseries-forecast/v1", + "split": "valid", + "reward": 0.38583178623319037, + "skill_score": 0.38583178623319037, + "rel_mase_gmean": 0.7346415432839528, + "rel_wql_gmean": 0.5134512174677245, + "n_configs": 97, + "n_failed": 0, + "n_instances": 151170, + "n_instances_scored": 151170, + "n_partial": 0, + "failures": [], + "groups": { + "term": { + "long": { + "n_configs": 21, + "rel_mase_gmean": 0.7364914654931061, + "rel_wql_gmean": 0.4855885856144318 + }, + "medium": { + "n_configs": 21, + "rel_mase_gmean": 0.7011238985772719, + "rel_wql_gmean": 0.49453270816249795 + }, + "short": { + "n_configs": 55, + "rel_mase_gmean": 0.7471400091845541, + "rel_wql_gmean": 0.5320790314159187 + } + }, + "domain": { + "Econ/Fin": { + "n_configs": 6, + "rel_mase_gmean": 0.8907256382120787, + "rel_wql_gmean": 0.8451670045418355 + }, + "Energy": { + "n_configs": 32, + "rel_mase_gmean": 0.892526963541049, + "rel_wql_gmean": 0.643957267552437 + }, + "Healthcare": { + "n_configs": 5, + "rel_mase_gmean": 0.540668761839018, + "rel_wql_gmean": 0.47531465645280946 + }, + "Nature": { + "n_configs": 15, + "rel_mase_gmean": 0.7958185189253236, + "rel_wql_gmean": 0.3877369778804494 + }, + "Sales": { + "n_configs": 4, + "rel_mase_gmean": 0.8197807404849302, + "rel_wql_gmean": 0.5017501285589074 + }, + "Transport": { + "n_configs": 15, + "rel_mase_gmean": 0.6355679306392307, + "rel_wql_gmean": 0.4321860254364469 + }, + "Web/CloudOps": { + "n_configs": 20, + "rel_mase_gmean": 0.5631114826403955, + "rel_wql_gmean": 0.4427598865526952 + } + }, + "frequency": { + "A": { + "n_configs": 1, + "rel_mase_gmean": 0.6770281900062816, + "rel_wql_gmean": 0.7208022429771983 + }, + "D": { + "n_configs": 15, + "rel_mase_gmean": 0.7528564853966223, + "rel_wql_gmean": 0.5103645101840805 + }, + "H": { + "n_configs": 31, + "rel_mase_gmean": 0.7291626066873291, + "rel_wql_gmean": 0.49325199857505014 + }, + "M": { + "n_configs": 5, + "rel_mase_gmean": 0.9384028023959284, + "rel_wql_gmean": 0.7793118598975827 + }, + "Q": { + "n_configs": 1, + "rel_mase_gmean": 0.7905339382323439, + "rel_wql_gmean": 0.8258039902488685 + }, + "S": { + "n_configs": 6, + "rel_mase_gmean": 0.6582508633257881, + "rel_wql_gmean": 0.5038908974522515 + }, + "T": { + "n_configs": 30, + "rel_mase_gmean": 0.6842027266977074, + "rel_wql_gmean": 0.45816194264890703 + }, + "W": { + "n_configs": 8, + "rel_mase_gmean": 0.8797100750175781, + "rel_wql_gmean": 0.6563796399341337 + } + }, + "variates": { + "multivariate": { + "n_configs": 43, + "rel_mase_gmean": 0.7093610794643139, + "rel_wql_gmean": 0.511389745409696 + }, + "univariate": { + "n_configs": 54, + "rel_mase_gmean": 0.7554150954717557, + "rel_wql_gmean": 0.5150987016790656 + } + } + }, + "quantile_crossing_fraction_mean": 0.0, + "configs": [ + { + "config_id": "m4_yearly__A__short", + "leaderboard_key": "m4_yearly/A/short", + "dataset": "m4_yearly", + "term": "short", + "freq": "A-DEC", + "prediction_length": 6, + "seasonality": 1, + "n_variates": 1, + "n_instances": 22728, + "domain": "Econ/Fin", + "n_cohorts": 3, + "skipped_series": 235, + "dropped_containers": 11, + "status": "ok", + "baseline": { + "mase": 4.730803330645802, + "wql": 0.15602350647819704 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 22728, + "instances": 22728, + "fraction": 1.0 + }, + "metrics": { + "mase": 3.2028872162228157, + "wql": 0.11246209342665187, + "wsql_by_level": [ + 0.0629797288242861, + 0.09713362229318, + 0.11912301465174661, + 0.1321441736303147, + 0.13779856230207296, + 0.13766277303393182, + 0.12996706933077104, + 0.11302219800719643, + 0.08232769876636702 + ], + "n_valid_labels": 136368, + "n_masked_labels": 0, + "mae_median": 715.2996800440981, + "n_mase_elements": 136356, + "n_seasonal_error_zero": 2, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6770281900062816, + "wql": 0.7208022429771983 + } + }, + { + "config_id": "m4_quarterly__Q__short", + "leaderboard_key": "m4_quarterly/Q/short", + "dataset": "m4_quarterly", + "term": "short", + "freq": "Q-DEC", + "prediction_length": 8, + "seasonality": 4, + "n_variates": 1, + "n_instances": 23905, + "domain": "Econ/Fin", + "n_cohorts": 3, + "dropped_containers": 95, + "status": "ok", + "baseline": { + "mase": 1.5909093331240343, + "wql": 0.0995990835037221 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 23905, + "instances": 23905, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.2576678204851346, + "wql": 0.08224932058250396, + "wsql_by_level": [ + 0.04789694594363365, + 0.07300361691913311, + 0.08844262075114954, + 0.09754692752512678, + 0.10141599794705092, + 0.10016956900001385, + 0.09378486491806749, + 0.08054806961185199, + 0.05743527262650844 + ], + "n_valid_labels": 191240, + "n_masked_labels": 0, + "mae_median": 577.4921275829626, + "n_mase_elements": 191232, + "n_seasonal_error_zero": 1, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7905339382323439, + "wql": 0.8258039902488685 + } + }, + { + "config_id": "m4_monthly__M__short", + "leaderboard_key": "m4_monthly/M/short", + "dataset": "m4_monthly", + "term": "short", + "freq": "M", + "prediction_length": 18, + "seasonality": 12, + "n_variates": 1, + "n_instances": 47501, + "domain": "Econ/Fin", + "n_cohorts": 3, + "dropped_containers": 499, + "status": "ok", + "baseline": { + "mase": 1.2366691185612824, + "wql": 0.11781121192744513 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 47501, + "instances": 47501, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9857917865521678, + "wql": 0.09177855204080637, + "wsql_by_level": [ + 0.0531961051762946, + 0.08119339597090887, + 0.09887631585944051, + 0.1093650144816192, + 0.11400882688863363, + 0.11256991619273435, + 0.10463656329128045, + 0.08919011047300453, + 0.0629707200333412 + ], + "n_valid_labels": 855018, + "n_masked_labels": 0, + "mae_median": 540.5941750733381, + "n_mase_elements": 855018, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7971346350906049, + "wql": 0.7790307097199615 + } + }, + { + "config_id": "m4_weekly__W__short", + "leaderboard_key": "m4_weekly/W/short", + "dataset": "m4_weekly", + "term": "short", + "freq": "W-SUN", + "prediction_length": 13, + "seasonality": 1, + "n_variates": 1, + "n_instances": 355, + "domain": "Econ/Fin", + "n_cohorts": 2, + "dropped_containers": 4, + "status": "ok", + "baseline": { + "mase": 2.895128591740639, + "wql": 0.06508715280630521 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 355, + "instances": 355, + "fraction": 1.0 + }, + "metrics": { + "mase": 3.1745546301250473, + "wql": 0.04943774922000183, + "wsql_by_level": [ + 0.025648288086289193, + 0.04014270894960607, + 0.050787975007433046, + 0.05769669854227741, + 0.06179986817109491, + 0.0631295189426402, + 0.059760440454056915, + 0.0508088326181348, + 0.03516541220848391 + ], + "n_valid_labels": 4615, + "n_masked_labels": 0, + "mae_median": 321.65943887861425, + "n_mase_elements": 4615, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.0965159334136552, + "wql": 0.7595623266410976 + } + }, + { + "config_id": "m4_daily__D__short", + "leaderboard_key": "m4_daily/D/short", + "dataset": "m4_daily", + "term": "short", + "freq": "D", + "prediction_length": 14, + "seasonality": 1, + "n_variates": 1, + "n_instances": 4204, + "domain": "Econ/Fin", + "n_cohorts": 2, + "dropped_containers": 23, + "status": "ok", + "baseline": { + "mase": 3.2161164077095057, + "wql": 0.02310161661155265 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 4204, + "instances": 4204, + "fraction": 1.0 + }, + "metrics": { + "mase": 3.2830825382423448, + "wql": 0.021799201652276612, + "wsql_by_level": [ + 0.013722210042686906, + 0.019855462848644322, + 0.02360551284771078, + 0.02578253026360292, + 0.0266850826307855, + 0.026380022314851544, + 0.02459104928270583, + 0.020872801907412676, + 0.014698142732089027 + ], + "n_valid_labels": 58856, + "n_masked_labels": 0, + "mae_median": 170.977948493019, + "n_mase_elements": 58842, + "n_seasonal_error_zero": 1, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.0208220480988535, + "wql": 0.9436223455191128 + } + }, + { + "config_id": "m4_hourly__H__short", + "leaderboard_key": "m4_hourly/H/short", + "dataset": "m4_hourly", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 414, + "domain": "Econ/Fin", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.22836124915778, + "wql": 0.034474947608819397 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 414, + "instances": 414, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.2845939915602163, + "wql": 0.037805022444418385, + "wsql_by_level": [ + 0.01909220146888026, + 0.0318682834743777, + 0.04061958460154832, + 0.04567152941048537, + 0.04804351768631572, + 0.04785569343548227, + 0.044516582277849256, + 0.037186724044254646, + 0.02539108560057192 + ], + "n_valid_labels": 19872, + "n_masked_labels": 0, + "mae_median": 361.91184725925694, + "n_mase_elements": 19872, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.0457786684829011, + "wql": 1.096594050653382 + } + }, + { + "config_id": "electricity__T__short", + "leaderboard_key": "electricity/15T/short", + "dataset": "electricity/15T", + "term": "short", + "freq": "15T", + "prediction_length": 48, + "seasonality": 96, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0916823579221513, + "wql": 0.06198863606457304 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9737929495879218, + "wql": 0.04839941847000929, + "wsql_by_level": [ + 0.030679617152502538, + 0.04672392874674479, + 0.056645193909203806, + 0.06182314721207977, + 0.06285467156255108, + 0.05946210017794236, + 0.05144185264615135, + 0.03962177688165307, + 0.026342477941254844 + ], + "n_valid_labels": 17712, + "n_masked_labels": 48, + "mae_median": 63.84479549216959, + "n_mase_elements": 17712, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 0.8920112544837551, + "wql": 0.7807788901758062 + } + }, + { + "config_id": "electricity__T__medium", + "leaderboard_key": "electricity/15T/medium", + "dataset": "electricity/15T", + "term": "medium", + "freq": "15T", + "prediction_length": 480, + "seasonality": 96, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.5099936923797364, + "wql": 0.12054261982000446 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.956088972271555, + "wql": 0.08950853656219808, + "wsql_by_level": [ + 0.041824804697460506, + 0.06681136058502342, + 0.0849995936332816, + 0.09908396969716943, + 0.10941118218735049, + 0.1140905079298702, + 0.1119936606562434, + 0.10106767338199088, + 0.07629407629139268 + ], + "n_valid_labels": 177120, + "n_masked_labels": 480, + "mae_median": 78.6908469824693, + "n_mase_elements": 177120, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 0.6331741497308955, + "wql": 0.7425467995954725 + } + }, + { + "config_id": "electricity__T__long", + "leaderboard_key": "electricity/15T/long", + "dataset": "electricity/15T", + "term": "long", + "freq": "15T", + "prediction_length": 720, + "seasonality": 96, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0941077605435365, + "wql": 0.107564338522276 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8799012253808064, + "wql": 0.08610598977770022, + "wsql_by_level": [ + 0.040173823315783744, + 0.06453474428997279, + 0.08169153510214935, + 0.09399887750728698, + 0.10342364834851257, + 0.1080426432031735, + 0.10733843645107621, + 0.09850455891174409, + 0.07724564086960277 + ], + "n_valid_labels": 265680, + "n_masked_labels": 720, + "mae_median": 74.57325627638801, + "n_mase_elements": 265680, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 0.8042180643556395, + "wql": 0.8005068497666458 + } + }, + { + "config_id": "electricity__H__short", + "leaderboard_key": "electricity/H/short", + "dataset": "electricity/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9861593153062442, + "wql": 0.06763119078713985 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0307791694479302, + "wql": 0.0745592394481557, + "wsql_by_level": [ + 0.04679530028445879, + 0.06768139629823479, + 0.08186649798948242, + 0.08987039097796966, + 0.09305891979997066, + 0.09165721661744479, + 0.084936851155257, + 0.07054650342360197, + 0.04462007848698125 + ], + "n_valid_labels": 17712, + "n_masked_labels": 48, + "mae_median": 282.62278028696863, + "n_mase_elements": 17712, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 1.0452460910211345, + "wql": 1.10243866151671 + } + }, + { + "config_id": "electricity__H__medium", + "leaderboard_key": "electricity/H/medium", + "dataset": "electricity/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.2478422873379948, + "wql": 0.12311153060577013 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9677436147416012, + "wql": 0.07822776065841053, + "wsql_by_level": [ + 0.04237776334871591, + 0.0642091139783029, + 0.07786302229492262, + 0.08688913383301486, + 0.09430287564487762, + 0.097218242271719, + 0.09441429274396865, + 0.08431122451724601, + 0.06246417729292724 + ], + "n_valid_labels": 177120, + "n_masked_labels": 480, + "mae_median": 253.78469060321837, + "n_mase_elements": 177120, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 0.7755335947189894, + "wql": 0.6354218835026332 + } + }, + { + "config_id": "electricity__H__long", + "leaderboard_key": "electricity/H/long", + "dataset": "electricity/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.356699671272273, + "wql": 0.14674885232557194 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.1938613612304692, + "wql": 0.0921254552426491, + "wsql_by_level": [ + 0.04329169324302598, + 0.06912442645431958, + 0.087577480048575, + 0.10065297395921705, + 0.10919552931323835, + 0.11314674740219362, + 0.11243386435048265, + 0.10605195859299704, + 0.08765442381979272 + ], + "n_valid_labels": 265680, + "n_masked_labels": 720, + "mae_median": 299.2827778657711, + "n_mase_elements": 265680, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 0.8799746815821818, + "wql": 0.6277763252162459 + } + }, + { + "config_id": "electricity__D__short", + "leaderboard_key": "electricity/D/short", + "dataset": "electricity/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.6456666278884469, + "wql": 0.09261378216375024 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.4749551142682222, + "wql": 0.06713765516464394, + "wsql_by_level": [ + 0.028620890225454738, + 0.04822629243410145, + 0.06416217718420397, + 0.07550580303707083, + 0.08329641300429567, + 0.08632169812225819, + 0.08408334060618844, + 0.07595558185480906, + 0.058066700013413235 + ], + "n_valid_labels": 11070, + "n_masked_labels": 30, + "mae_median": 5479.165390015596, + "n_mase_elements": 11070, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 0.8962660415376689, + "wql": 0.7249207795653781 + } + }, + { + "config_id": "electricity__W__short", + "leaderboard_key": "electricity/W/short", + "dataset": "electricity/W", + "term": "short", + "freq": "W-FRI", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 1, + "n_instances": 370, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.316880865245498, + "wql": 0.06523927951573125 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 370, + "instances": 370, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.4337487190979303, + "wql": 0.06593147967358859, + "wsql_by_level": [ + 0.027002621553155585, + 0.047144738483528105, + 0.06475539675997997, + 0.07612982599737529, + 0.08350401589276975, + 0.08577709737376074, + 0.0821358538352078, + 0.0726545251903385, + 0.05427924197618145 + ], + "n_valid_labels": 2952, + "n_masked_labels": 8, + "mae_median": 35960.00405279537, + "n_mase_elements": 2952, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 1 + }, + "relative": { + "mase": 1.0887459579197738, + "wql": 1.0106101747750054 + } + }, + { + "config_id": "solar__T__short", + "leaderboard_key": "solar/10T/short", + "dataset": "solar/10T", + "term": "short", + "freq": "10T", + "prediction_length": 48, + "seasonality": 144, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.016018364778558773, + "wql": 12.118563297136966 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.017867641314433875, + "wql": 0.42911476599220744, + "wsql_by_level": [ + 0.19412128912610782, + 0.3475395275056199, + 0.43794764948263964, + 0.490124952334262, + 0.515134932222128, + 0.5133773664591927, + 0.5119889991099781, + 0.47657134493060926, + 0.37522683275932955 + ], + "n_valid_labels": 6576, + "n_masked_labels": 0, + "mae_median": 0.0497822762493026, + "n_mase_elements": 6576, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.1154472732666465, + "wql": 0.03540970620614629 + } + }, + { + "config_id": "solar__T__medium", + "leaderboard_key": "solar/10T/medium", + "dataset": "solar/10T", + "term": "medium", + "freq": "10T", + "prediction_length": 480, + "seasonality": 144, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.8331425981399365, + "wql": 0.5650432034501303 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6750128478126656, + "wql": 0.2761358335441311, + "wsql_by_level": [ + 0.2049825876371191, + 0.30893504931913857, + 0.34664871266151814, + 0.3467372286418589, + 0.3265077786926864, + 0.3010610679082316, + 0.27037811959206914, + 0.22440375660918252, + 0.1555682008353756 + ], + "n_valid_labels": 65760, + "n_masked_labels": 0, + "mae_median": 1.5601190607069704, + "n_mase_elements": 65760, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8102008579559977, + "wql": 0.4886986196065314 + } + }, + { + "config_id": "solar__T__long", + "leaderboard_key": "solar/10T/long", + "dataset": "solar/10T", + "term": "long", + "freq": "10T", + "prediction_length": 720, + "seasonality": 144, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 2.1421153816960863, + "wql": 0.9032285592107642 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7006179421577138, + "wql": 0.22362238221667546, + "wsql_by_level": [ + 0.16567572425219568, + 0.25860797529536156, + 0.29726722633994057, + 0.30082269691457225, + 0.27981446859945597, + 0.2409167228071274, + 0.1943644226756878, + 0.15434698644786699, + 0.12078521661787081 + ], + "n_valid_labels": 98640, + "n_masked_labels": 0, + "mae_median": 1.6441124029223417, + "n_mase_elements": 98640, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.3270682560539656, + "wql": 0.24758116861592086 + } + }, + { + "config_id": "solar__H__short", + "leaderboard_key": "solar/H/short", + "dataset": "solar/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0569321595099215, + "wql": 0.602297355940449 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8684899796036568, + "wql": 0.3324843301142675, + "wsql_by_level": [ + 0.244347666363593, + 0.3835603161655153, + 0.43783172473505455, + 0.43943561861585434, + 0.4108568500130219, + 0.3662442782159461, + 0.3079976349870399, + 0.24160622142535756, + 0.1604786605070243 + ], + "n_valid_labels": 6576, + "n_masked_labels": 0, + "mae_median": 11.332148549274413, + "n_mase_elements": 6576, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.82170834881811, + "wql": 0.5520268798044354 + } + }, + { + "config_id": "solar__H__medium", + "leaderboard_key": "solar/H/medium", + "dataset": "solar/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.3782698364748944, + "wql": 0.9679824737641872 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.1953721377250308, + "wql": 0.4460289966222761, + "wsql_by_level": [ + 0.4711499461715604, + 0.5755660268583057, + 0.5925294616349343, + 0.5680847524161542, + 0.5208057681886746, + 0.4571530881297905, + 0.37776391299669115, + 0.28131376660381685, + 0.16989424660055666 + ], + "n_valid_labels": 65760, + "n_masked_labels": 0, + "mae_median": 15.607001743737127, + "n_mase_elements": 65760, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8672990629921581, + "wql": 0.4607820995847228 + } + }, + { + "config_id": "solar__H__long", + "leaderboard_key": "solar/H/long", + "dataset": "solar/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0723400769109404, + "wql": 0.9027882643891623 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0398390178894454, + "wql": 0.35695234062526515, + "wsql_by_level": [ + 0.4295676681830956, + 0.4671201231167708, + 0.46464369211104245, + 0.4415632204395562, + 0.4053652503737357, + 0.3574824427559057, + 0.2967613495142271, + 0.22094605403948156, + 0.12912126509357133 + ], + "n_valid_labels": 98640, + "n_masked_labels": 0, + "mae_median": 13.665251559159241, + "n_mase_elements": 98640, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9696914628844986, + "wql": 0.3953887691116405 + } + }, + { + "config_id": "solar__D__short", + "leaderboard_key": "solar/D/short", + "dataset": "solar/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.1670584568457976, + "wql": 0.4714212933677157 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.140715254864395, + "wql": 0.2882746049150719, + "wsql_by_level": [ + 0.24969341314317767, + 0.35119386591808394, + 0.3845073101085784, + 0.38268238325425663, + 0.35660153039451886, + 0.31437527005412, + 0.2571172167448492, + 0.1885318416845044, + 0.10976861293355761 + ], + "n_valid_labels": 4110, + "n_masked_labels": 0, + "mae_median": 288.513114550978, + "n_mase_elements": 4110, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9774276928230312, + "wql": 0.6115010267264558 + } + }, + { + "config_id": "solar__W__short", + "leaderboard_key": "solar/W/short", + "dataset": "solar/W", + "term": "short", + "freq": "W-FRI", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 1, + "n_instances": 137, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0078578333938706, + "wql": 0.13890951079671932 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 137, + "instances": 137, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0231462805183342, + "wql": 0.12058172987153763, + "wsql_by_level": [ + 0.05836324213640742, + 0.11719894250358959, + 0.14672967412044965, + 0.15518608184754626, + 0.1529947652963013, + 0.14355421693436907, + 0.12845127929668348, + 0.10708765276021028, + 0.07566971394828169 + ], + "n_valid_labels": 1096, + "n_masked_labels": 0, + "mae_median": 939.5007002336265, + "n_mase_elements": 1096, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.0151692496877076, + "wql": 0.8680595675554381 + } + }, + { + "config_id": "hospital__M__short", + "leaderboard_key": "hospital/M/short", + "dataset": "hospital", + "term": "short", + "freq": "M", + "prediction_length": 12, + "seasonality": 12, + "n_variates": 1, + "n_instances": 767, + "domain": "Healthcare", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9326829101839614, + "wql": 0.0633931064425068 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 767, + "instances": 767, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7929181212598443, + "wql": 0.05522441462304542, + "wsql_by_level": [ + 0.03014868575807013, + 0.04654219360421944, + 0.05725415189069781, + 0.06511166592973544, + 0.06935335298370321, + 0.0691885498790853, + 0.06481316088896792, + 0.05538031347043105, + 0.039227657202498434 + ], + "n_valid_labels": 9204, + "n_masked_labels": 0, + "mae_median": 19.255351124303022, + "n_mase_elements": 9204, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8501475824226798, + "wql": 0.8711422695956724 + } + }, + { + "config_id": "covid_deaths__D__short", + "leaderboard_key": "covid_deaths/D/short", + "dataset": "covid_deaths", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 266, + "domain": "Healthcare", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 50.55549046119792, + "wql": 0.12549070850235644 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 266, + "instances": 266, + "fraction": 1.0 + }, + "metrics": { + "mase": 42.741015085480534, + "wql": 0.07083739512170638, + "wsql_by_level": [ + 0.061804656946839086, + 0.08797211599907875, + 0.10134622447342963, + 0.09656135510057699, + 0.0807290227361644, + 0.048451714704900416, + 0.04056580598657651, + 0.05705437108394602, + 0.06305128906384566 + ], + "n_valid_labels": 7980, + "n_masked_labels": 0, + "mae_median": 164.00564300836925, + "n_mase_elements": 6810, + "n_seasonal_error_zero": 39, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8454277605769622, + "wql": 0.5644831873777827 + } + }, + { + "config_id": "us_births__D__short", + "leaderboard_key": "us_births/D/short", + "dataset": "us_births/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 1, + "domain": "Healthcare", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 2.328105874599355, + "wql": 0.13056664093780335 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.4450604294172986, + "wql": 0.023960035823986026, + "wsql_by_level": [ + 0.009932112804917998, + 0.0156905095655891, + 0.020553131024044585, + 0.02340981345013053, + 0.028883134584219112, + 0.032924715104147906, + 0.03408905748934609, + 0.030071505972249054, + 0.020086342421229853 + ], + "n_valid_labels": 30, + "n_masked_labels": 0, + "mae_median": 293.92151692708336, + "n_mase_elements": 30, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.19116846629403797, + "wql": 0.18350809710575014 + } + }, + { + "config_id": "us_births__M__short", + "leaderboard_key": "us_births/M/short", + "dataset": "us_births/M", + "term": "short", + "freq": "M", + "prediction_length": 12, + "seasonality": 12, + "n_variates": 1, + "n_instances": 1, + "domain": "Healthcare", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.3023112362005141, + "wql": 0.011101802850788281 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.2719745017652419, + "wql": 0.007650498867007711, + "wsql_by_level": [ + 0.005198747635457807, + 0.0058233637208749195, + 0.005553336055133983, + 0.007593263039026693, + 0.008126462989970572, + 0.008312885540495987, + 0.009999679131027095, + 0.010215910641408777, + 0.008030841049673566 + ], + "n_valid_labels": 12, + "n_masked_labels": 0, + "mae_median": 2551.109375, + "n_mase_elements": 12, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8996506553426591, + "wql": 0.6891222056302764 + } + }, + { + "config_id": "us_births__W__short", + "leaderboard_key": "us_births/W/short", + "dataset": "us_births/W", + "term": "short", + "freq": "W-TUE", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 1, + "n_instances": 1, + "domain": "Healthcare", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 3.858436986096576, + "wql": 0.04221704717157443 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.4421379900769922, + "wql": 0.016470330328072234, + "wsql_by_level": [ + 0.007734987137112833, + 0.016132479126163838, + 0.02015996588100275, + 0.021276709814609752, + 0.0210965579804511, + 0.020107854804805054, + 0.01798174757571124, + 0.0149148894430227, + 0.008827781189770852 + ], + "n_valid_labels": 8, + "n_masked_labels": 0, + "mae_median": 1569.380859375, + "n_mase_elements": 8, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.37376222425649736, + "wql": 0.39013458854986033 + } + }, + { + "config_id": "saugeenday__D__short", + "leaderboard_key": "saugeen/D/short", + "dataset": "saugeenday/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 3.898466092444523, + "wql": 0.5418638069109889 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 3.1254680653632874, + "wql": 0.31349008055489636, + "wsql_by_level": [ + 0.1444720558738459, + 0.25571001180766467, + 0.34396003325331337, + 0.40945173878919194, + 0.4423209105476838, + 0.4212654329176542, + 0.3458906208279467, + 0.2229568485940496, + 0.23538307238271663 + ], + "n_valid_labels": 30, + "n_masked_labels": 0, + "mae_median": 13.741436386108399, + "n_mase_elements": 30, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8017173912120577, + "wql": 0.5785403574784113 + } + }, + { + "config_id": "saugeenday__M__short", + "leaderboard_key": "saugeen/M/short", + "dataset": "saugeenday/M", + "term": "short", + "freq": "M", + "prediction_length": 12, + "seasonality": 12, + "n_variates": 1, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.33228103391864, + "wql": 0.2615013833629034 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.4360933579789521, + "wql": 0.2319688099622008, + "wsql_by_level": [ + 0.12365462883049684, + 0.20643107058675686, + 0.25289762359547585, + 0.2673775488253035, + 0.25994252924432126, + 0.2452221175452368, + 0.2607463506256514, + 0.2704285164815506, + 0.20101890392501398 + ], + "n_valid_labels": 12, + "n_masked_labels": 0, + "mae_median": 7.559715986251831, + "n_mase_elements": 12, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.3124232606238093, + "wql": 0.8870653263056806 + } + }, + { + "config_id": "saugeenday__W__short", + "leaderboard_key": "saugeen/W/short", + "dataset": "saugeenday/W", + "term": "short", + "freq": "W-THU", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 1, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.5685710422753978, + "wql": 0.5994091721735982 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7123383480757575, + "wql": 0.23323336105577763, + "wsql_by_level": [ + 0.10078252321196057, + 0.1670712380326051, + 0.24326543768967077, + 0.30932112239088794, + 0.3491239516239304, + 0.3511947401642117, + 0.28287017635518474, + 0.1373879203285203, + 0.15808313970502702 + ], + "n_valid_labels": 8, + "n_masked_labels": 0, + "mae_median": 8.537327408790588, + "n_mase_elements": 8, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.2528572422981812, + "wql": 0.3891054256143909 + } + }, + { + "config_id": "temperature_rain_with_missing__D__short", + "leaderboard_key": "temperature_rain/D/short", + "dataset": "temperature_rain_with_missing", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 32072, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 3.2912255413171745, + "wql": 1.099183165150044 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 32072, + "instances": 32072, + "fraction": 1.0 + }, + "metrics": { + "mase": 2.1044333195712186, + "wql": 0.5239368140215878, + "wsql_by_level": [ + 0.1779565137153612, + 0.3345804038111841, + 0.46967389657444875, + 0.5787375608142252, + 0.6570946983151983, + 0.7024985778365737, + 0.7014264126621094, + 0.6328871866149693, + 0.46057607585022026 + ], + "n_valid_labels": 961756, + "n_masked_labels": 404, + "mae_median": 6.601805725668225, + "n_mase_elements": 960736, + "n_seasonal_error_zero": 34, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6394072035333707, + "wql": 0.47666015149537677 + } + }, + { + "config_id": "kdd_cup_2018_with_missing__H__short", + "leaderboard_key": "kdd_cup_2018/H/short", + "dataset": "kdd_cup_2018_with_missing/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 270, + "domain": "Nature", + "n_cohorts": 2, + "status": "ok", + "baseline": { + "mase": 0.6811227593500775, + "wql": 0.6266148384878599 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 270, + "instances": 270, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.5360946951775218, + "wql": 0.38131674534774906, + "wsql_by_level": [ + 0.14758299696862512, + 0.2497769541939192, + 0.34174661450336996, + 0.4211850190871072, + 0.47886623830907177, + 0.5036309817098481, + 0.4972538158412967, + 0.4552697724603184, + 0.3365383150561849 + ], + "n_valid_labels": 11685, + "n_masked_labels": 1275, + "mae_median": 12.308050782817217, + "n_mase_elements": 11685, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7870749990633988, + "wql": 0.6085344966741267 + } + }, + { + "config_id": "kdd_cup_2018_with_missing__H__medium", + "leaderboard_key": "kdd_cup_2018/H/medium", + "dataset": "kdd_cup_2018_with_missing/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 1, + "n_instances": 270, + "domain": "Nature", + "n_cohorts": 2, + "status": "ok", + "baseline": { + "mase": 1.2781450805103305, + "wql": 1.049898934007083 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 270, + "instances": 270, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9242485534598619, + "wql": 0.4595858606823105, + "wsql_by_level": [ + 0.18105167429699465, + 0.33068847830534764, + 0.45059136698427105, + 0.5402759995799932, + 0.5963899942139294, + 0.6109031900367335, + 0.5797875537576381, + 0.497212703507675, + 0.3493717854582126 + ], + "n_valid_labels": 116458, + "n_masked_labels": 13142, + "mae_median": 19.988807649218664, + "n_mase_elements": 116458, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7231170917552123, + "wql": 0.437742953912943 + } + }, + { + "config_id": "kdd_cup_2018_with_missing__H__long", + "leaderboard_key": "kdd_cup_2018/H/long", + "dataset": "kdd_cup_2018_with_missing/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 1, + "n_instances": 270, + "domain": "Nature", + "n_cohorts": 2, + "status": "ok", + "baseline": { + "mase": 0.981050679806651, + "wql": 1.2362237298155803 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 270, + "instances": 270, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8694406236631339, + "wql": 0.4722874999690492, + "wsql_by_level": [ + 0.1820913957684534, + 0.3298621747777634, + 0.45245597094888157, + 0.546147439467688, + 0.6071205016372825, + 0.6306469869450954, + 0.6111254740819184, + 0.5331988095778821, + 0.35793874651647717 + ], + "n_valid_labels": 175906, + "n_masked_labels": 18494, + "mae_median": 18.516057049483603, + "n_mase_elements": 175906, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8862341584988112, + "wql": 0.3820404742105258 + } + }, + { + "config_id": "kdd_cup_2018_with_missing__D__short", + "leaderboard_key": "kdd_cup_2018/D/short", + "dataset": "kdd_cup_2018_with_missing/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 270, + "domain": "Nature", + "n_cohorts": 2, + "status": "ok", + "baseline": { + "mase": 1.2132840958596942, + "wql": 0.8994855622016019 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 270, + "instances": 270, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0124099062608518, + "wql": 0.3911172969437853, + "wsql_by_level": [ + 0.16413243020708349, + 0.2886888157886592, + 0.38096385796167115, + 0.44767796586490777, + 0.4893880551647252, + 0.5062315001487473, + 0.49561708405561594, + 0.4415483764983069, + 0.3058075868043505 + ], + "n_valid_labels": 7581, + "n_masked_labels": 519, + "mae_median": 15.1888820829995, + "n_mase_elements": 7581, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8344376306552429, + "wql": 0.434823318327064 + } + }, + { + "config_id": "car_parts_with_missing__M__short", + "leaderboard_key": "car_parts/M/short", + "dataset": "car_parts_with_missing", + "term": "short", + "freq": "M", + "prediction_length": 12, + "seasonality": 12, + "n_variates": 1, + "n_instances": 2674, + "domain": "Sales", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.556811831303017, + "wql": 1.6139130745452677 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 2674, + "instances": 2674, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.415822404833143, + "wql": 1.1182555293311536, + "wsql_by_level": [ + 0.278451758356467, + 0.5477663705116169, + 0.8182308306318171, + 1.0812325214292384, + 1.3150302942025385, + 1.5028527483290572, + 1.6149955395651996, + 1.587316159606548, + 1.318423541347901 + ], + "n_valid_labels": 30108, + "n_masked_labels": 1980, + "mae_median": 0.6222677229142941, + "n_mase_elements": 28068, + "n_seasonal_error_zero": 215, + "n_seasonal_error_nan": 7 + }, + "relative": { + "mase": 0.9094370792699661, + "wql": 0.6928846088233287 + } + }, + { + "config_id": "restaurant__D__short", + "leaderboard_key": "restaurant/D/short", + "dataset": "restaurant", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 806, + "domain": "Sales", + "n_cohorts": 13, + "skipped_series": 1, + "status": "ok", + "baseline": { + "mase": 1.0028179898604987, + "wql": 0.6760963195065456 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 806, + "instances": 806, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6908883873619863, + "wql": 0.26063786901318353, + "wsql_by_level": [ + 0.1307655436139024, + 0.2137393852343807, + 0.2726571826812677, + 0.31154011912661506, + 0.33146273677915805, + 0.3315685268529457, + 0.30988919808502036, + 0.2632130745441039, + 0.18090505420125833 + ], + "n_valid_labels": 21222, + "n_masked_labels": 2958, + "mae_median": 7.089447840684524, + "n_mase_elements": 21222, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6889469418653881, + "wql": 0.3855040494872272 + } + }, + { + "config_id": "hierarchical_sales__D__short", + "leaderboard_key": "hierarchical_sales/D/short", + "dataset": "hierarchical_sales/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 118, + "domain": "Sales", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0956340453936162, + "wql": 1.4587792906606432 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 118, + "instances": 118, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9574763106756976, + "wql": 0.6301563672377362, + "wsql_by_level": [ + 0.19775357851930392, + 0.37117153862642915, + 0.5231916769883593, + 0.6562048888389568, + 0.7621339071659042, + 0.8342361866351382, + 0.868945647694416, + 0.8219005423856248, + 0.6358693382854934 + ], + "n_valid_labels": 3304, + "n_masked_labels": 236, + "mae_median": 2.98879208085612, + "n_mase_elements": 3304, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8739015684125768, + "wql": 0.4319751255533349 + } + }, + { + "config_id": "hierarchical_sales__W__short", + "leaderboard_key": "hierarchical_sales/W/short", + "dataset": "hierarchical_sales/W", + "term": "short", + "freq": "W-WED", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 1, + "n_instances": 118, + "domain": "Sales", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9952062817493519, + "wql": 0.7382990422957836 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 118, + "instances": 118, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8208862855266078, + "wql": 0.40553998100542116, + "wsql_by_level": [ + 0.14609909659779252, + 0.26454427903838895, + 0.3572297818940012, + 0.42913221762547515, + 0.4855450079575537, + 0.523917167934575, + 0.5382195534613025, + 0.50978726984053, + 0.39538545469917075 + ], + "n_valid_labels": 944, + "n_masked_labels": 0, + "mae_median": 11.85573350998052, + "n_mase_elements": 944, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8248403377073462, + "wql": 0.5492895937456063 + } + }, + { + "config_id": "LOOP_SEATTLE__T__short", + "leaderboard_key": "loop_seattle/5T/short", + "dataset": "LOOP_SEATTLE/5T", + "term": "short", + "freq": "5T", + "prediction_length": 48, + "seasonality": 288, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.6088421384511257, + "wql": 0.05736115508602545 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.39993084642756493, + "wql": 0.029262934876402927, + "wsql_by_level": [ + 0.019358970222190394, + 0.027425509358303984, + 0.03239040826880835, + 0.03527741455093835, + 0.03638992527646169, + 0.035659235061082234, + 0.032709593438462116, + 0.026914255225703503, + 0.017241102485675747 + ], + "n_valid_labels": 15504, + "n_masked_labels": 0, + "mae_median": 2.3601980074025284, + "n_mase_elements": 15504, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6568711676970582, + "wql": 0.5101524687310922 + } + }, + { + "config_id": "LOOP_SEATTLE__T__medium", + "leaderboard_key": "loop_seattle/5T/medium", + "dataset": "LOOP_SEATTLE/5T", + "term": "medium", + "freq": "5T", + "prediction_length": 480, + "seasonality": 288, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.5924843577520822, + "wql": 0.14109820582939464 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6078378506353068, + "wql": 0.05055894412171815, + "wsql_by_level": [ + 0.04058872519148814, + 0.05388800228107568, + 0.06059412470578535, + 0.0631318749459717, + 0.06233000584589522, + 0.05825957009613512, + 0.0510042687693808, + 0.04024260947352449, + 0.024991315786206815 + ], + "n_valid_labels": 155040, + "n_masked_labels": 0, + "mae_median": 3.786790057487778, + "n_mase_elements": 155040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.38169156744077415, + "wql": 0.35832450047486947 + } + }, + { + "config_id": "LOOP_SEATTLE__T__long", + "leaderboard_key": "loop_seattle/5T/long", + "dataset": "LOOP_SEATTLE/5T", + "term": "long", + "freq": "5T", + "prediction_length": 720, + "seasonality": 288, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.5910237866124803, + "wql": 0.14753926773607257 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6763055467875052, + "wql": 0.05735080256953889, + "wsql_by_level": [ + 0.04494552206303267, + 0.0613880167584584, + 0.0695125648840952, + 0.07230771592600974, + 0.07090542683445987, + 0.06592245157972529, + 0.057517253950405245, + 0.045316085474954276, + 0.028342185654709345 + ], + "n_valid_labels": 232560, + "n_masked_labels": 0, + "mae_median": 4.171157973203045, + "n_mase_elements": 232560, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.42507569809968554, + "wql": 0.38871551587291037 + } + }, + { + "config_id": "LOOP_SEATTLE__H__short", + "leaderboard_key": "loop_seattle/H/short", + "dataset": "LOOP_SEATTLE/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 2.0101473993616685, + "wql": 0.13665681786039896 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6640821567430758, + "wql": 0.04245623804460206, + "wsql_by_level": [ + 0.03434379685099982, + 0.04574663943930065, + 0.050837704141094224, + 0.05265611644077589, + 0.05179870709341923, + 0.04897365803999613, + 0.04332887645063514, + 0.0338903575844593, + 0.02053028636073811 + ], + "n_valid_labels": 15504, + "n_masked_labels": 0, + "mae_median": 3.1375520719893824, + "n_mase_elements": 15504, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.33036490605313723, + "wql": 0.3106777891460417 + } + }, + { + "config_id": "LOOP_SEATTLE__H__medium", + "leaderboard_key": "loop_seattle/H/medium", + "dataset": "LOOP_SEATTLE/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.1535310881157237, + "wql": 0.14911283164622935 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7136884995427406, + "wql": 0.05037771986382907, + "wsql_by_level": [ + 0.04193888147188516, + 0.05552802459951294, + 0.06122655911385554, + 0.062410971719677674, + 0.060536933078666304, + 0.0560846765930446, + 0.04931744924299941, + 0.03999876646076204, + 0.026357216494057967 + ], + "n_valid_labels": 155040, + "n_masked_labels": 0, + "mae_median": 3.3774043112862526, + "n_mase_elements": 155040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6186989730017076, + "wql": 0.3378496626189111 + } + }, + { + "config_id": "LOOP_SEATTLE__H__long", + "leaderboard_key": "loop_seattle/H/long", + "dataset": "LOOP_SEATTLE/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.2448539713840052, + "wql": 0.17526380961630228 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7180144046646927, + "wql": 0.050309622818327494, + "wsql_by_level": [ + 0.04188216129141009, + 0.054848654042818704, + 0.06032926428469035, + 0.061619247569002084, + 0.06007553890044291, + 0.05611005419850331, + 0.04982058711188952, + 0.040794495702393664, + 0.027306602263796834 + ], + "n_valid_labels": 232560, + "n_masked_labels": 0, + "mae_median": 3.3718493354225183, + "n_mase_elements": 232560, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.5767860497455921, + "wql": 0.2870508345588758 + } + }, + { + "config_id": "LOOP_SEATTLE__D__short", + "leaderboard_key": "loop_seattle/D/short", + "dataset": "LOOP_SEATTLE/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 323, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.1854124643746355, + "wql": 0.09281728785965133 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 323, + "instances": 323, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.5961687840193222, + "wql": 0.027558619275772148, + "wsql_by_level": [ + 0.020146057631070503, + 0.028542284120052712, + 0.03281918214582724, + 0.034548937834537996, + 0.03422690310907488, + 0.03205530689248923, + 0.02822920104687035, + 0.02268089523415943, + 0.014778805467866984 + ], + "n_valid_labels": 9690, + "n_masked_labels": 0, + "mae_median": 1.9210474445354828, + "n_mase_elements": 9690, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.5029209679635274, + "wql": 0.2969125678121885 + } + }, + { + "config_id": "SZ_TAXI__T__short", + "leaderboard_key": "sz_taxi/15T/short", + "dataset": "SZ_TAXI/15T", + "term": "short", + "freq": "15T", + "prediction_length": 48, + "seasonality": 96, + "n_variates": 1, + "n_instances": 156, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7251090475210906, + "wql": 0.3023498132057821 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 156, + "instances": 156, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.5179111052003924, + "wql": 0.19538693258711864, + "wsql_by_level": [ + 0.10136875483960171, + 0.16559470980266675, + 0.20887581361656457, + 0.23645023599173373, + 0.24867818818619478, + 0.2460554031674562, + 0.2284450675152645, + 0.19213955528088347, + 0.13087466488370214 + ], + "n_valid_labels": 7488, + "n_masked_labels": 0, + "mae_median": 2.7833159066748947, + "n_mase_elements": 7488, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7142527140861918, + "wql": 0.6462280578759164 + } + }, + { + "config_id": "SZ_TAXI__T__medium", + "leaderboard_key": "sz_taxi/15T/medium", + "dataset": "SZ_TAXI/15T", + "term": "medium", + "freq": "15T", + "prediction_length": 480, + "seasonality": 96, + "n_variates": 1, + "n_instances": 156, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.6350051480164337, + "wql": 0.3916041859838231 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 156, + "instances": 156, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.4658492052897504, + "wql": 0.19414015999917775, + "wsql_by_level": [ + 0.10051500343405752, + 0.1599315152999943, + 0.20062051205306405, + 0.2270252211580487, + 0.2407026764067246, + 0.24144978189648392, + 0.2289165458352852, + 0.20071713002905953, + 0.14738305387988168 + ], + "n_valid_labels": 74880, + "n_masked_labels": 0, + "mae_median": 2.663922059763316, + "n_mase_elements": 74880, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7336148482337884, + "wql": 0.49575608981666386 + } + }, + { + "config_id": "SZ_TAXI__T__long", + "leaderboard_key": "sz_taxi/15T/long", + "dataset": "SZ_TAXI/15T", + "term": "long", + "freq": "15T", + "prediction_length": 720, + "seasonality": 96, + "n_variates": 1, + "n_instances": 156, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.6084219160390921, + "wql": 0.45522272202116565 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 156, + "instances": 156, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.48882665830167354, + "wql": 0.21696208190260288, + "wsql_by_level": [ + 0.11395198515506903, + 0.17810677203519906, + 0.2201277473511588, + 0.24619308428117148, + 0.25935671519264636, + 0.26246850681638456, + 0.25580131136286854, + 0.2350753895934818, + 0.18157722533544615 + ], + "n_valid_labels": 112320, + "n_masked_labels": 0, + "mae_median": 2.880343150147824, + "n_mase_elements": 112320, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8034336788589082, + "wql": 0.47660644209344893 + } + }, + { + "config_id": "SZ_TAXI__H__short", + "leaderboard_key": "sz_taxi/H/short", + "dataset": "SZ_TAXI/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 156, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.6087142479652129, + "wql": 0.20653078520030457 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 156, + "instances": 156, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.47888502593866694, + "wql": 0.12995279515788938, + "wsql_by_level": [ + 0.06894579552246093, + 0.10808885285535937, + 0.13435765791362264, + 0.15098678576197802, + 0.15883872754466102, + 0.15841783355811107, + 0.1503538553045403, + 0.13505012098443667, + 0.10453552697583443 + ], + "n_valid_labels": 7488, + "n_masked_labels": 0, + "mae_median": 1.755985058188134, + "n_mase_elements": 7488, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7867156511277102, + "wql": 0.6292175523946913 + } + }, + { + "config_id": "M_DENSE__H__short", + "leaderboard_key": "m_dense/H/short", + "dataset": "M_DENSE/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 1, + "n_instances": 30, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.8744657675879529, + "wql": 0.18983266370122717 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 30, + "instances": 30, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7019813356401194, + "wql": 0.12583710294572342, + "wsql_by_level": [ + 0.09126764912493585, + 0.12445640057464644, + 0.142683066740757, + 0.15216848152213777, + 0.15430220704346317, + 0.14774184786249075, + 0.13408658501097306, + 0.11150625448451729, + 0.07432143414758954 + ], + "n_valid_labels": 1440, + "n_masked_labels": 0, + "mae_median": 97.18842435148028, + "n_mase_elements": 1440, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.802754506418703, + "wql": 0.6628843555805299 + } + }, + { + "config_id": "M_DENSE__H__medium", + "leaderboard_key": "m_dense/H/medium", + "dataset": "M_DENSE/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 1, + "n_instances": 30, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.171624112893389, + "wql": 0.3497462745339787 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 30, + "instances": 30, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.778367679257878, + "wql": 0.13784735681068172, + "wsql_by_level": [ + 0.08205189271051978, + 0.12009254457954086, + 0.14254435544894214, + 0.15689252541217918, + 0.1659952448132427, + 0.168011295227382, + 0.1605267464574044, + 0.1411175325522018, + 0.10339407409472248 + ], + "n_valid_labels": 14400, + "n_masked_labels": 0, + "mae_median": 97.43265520400472, + "n_mase_elements": 14400, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6643493170652292, + "wql": 0.39413531136066327 + } + }, + { + "config_id": "M_DENSE__H__long", + "leaderboard_key": "m_dense/H/long", + "dataset": "M_DENSE/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 1, + "n_instances": 30, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0805183298420056, + "wql": 0.3841191250034235 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 30, + "instances": 30, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0677048373267768, + "wql": 0.17615388279757468, + "wsql_by_level": [ + 0.08720402729662341, + 0.13894986301864637, + 0.17628034013557095, + 0.20338156711073663, + 0.22163033820388206, + 0.22750910688159456, + 0.21773259452843108, + 0.18624106545783353, + 0.12645604254485365 + ], + "n_valid_labels": 21600, + "n_masked_labels": 0, + "mae_median": 129.88990574284836, + "n_mase_elements": 21600, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9881413464618389, + "wql": 0.45859180481056416 + } + }, + { + "config_id": "M_DENSE__D__short", + "leaderboard_key": "m_dense/D/short", + "dataset": "M_DENSE/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 1, + "n_instances": 30, + "domain": "Transport", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.007688577826318, + "wql": 0.1992117768924222 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 30, + "instances": 30, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0191145040765455, + "wql": 0.09333023005068944, + "wsql_by_level": [ + 0.0621327327745601, + 0.09304722982734974, + 0.11249623183060851, + 0.12271659131503843, + 0.12414607518630008, + 0.11480117723298025, + 0.09762371125502671, + 0.07045498518059644, + 0.04255333585374462 + ], + "n_valid_labels": 900, + "n_masked_labels": 0, + "mae_median": 72.75773768954807, + "n_mase_elements": 900, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.0113387474083255, + "wql": 0.46849755323998427 + } + }, + { + "config_id": "ett1__T__short", + "leaderboard_key": "ett1/15T/short", + "dataset": "ett1/15T", + "term": "short", + "freq": "15T", + "prediction_length": 48, + "seasonality": 96, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.2054822899524387, + "wql": 0.48104386522982623 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.788347147431414, + "wql": 0.27756564532051753, + "wsql_by_level": [ + 0.16261583563135545, + 0.2593401661059953, + 0.31472615337599685, + 0.347647348034137, + 0.3587300011793886, + 0.3563844391540659, + 0.32302953258229805, + 0.24649123538400372, + 0.1291260964374169 + ], + "n_valid_labels": 336, + "n_masked_labels": 0, + "mae_median": 1.3110812812429642, + "n_mase_elements": 336, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6539682532063723, + "wql": 0.5770069330120366 + } + }, + { + "config_id": "ett1__T__medium", + "leaderboard_key": "ett1/15T/medium", + "dataset": "ett1/15T", + "term": "medium", + "freq": "15T", + "prediction_length": 480, + "seasonality": 96, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7745679584044315, + "wql": 0.4386794376669185 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9585156999882454, + "wql": 0.37233345581011495, + "wsql_by_level": [ + 0.18219472957389204, + 0.32340079712235587, + 0.43628631346319957, + 0.49308181295322573, + 0.5035316662782264, + 0.47759874115873846, + 0.4158486333275072, + 0.3218752832926215, + 0.19718312512126793 + ], + "n_valid_labels": 3360, + "n_masked_labels": 0, + "mae_median": 1.6419718053517587, + "n_mase_elements": 3360, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.2374843157245188, + "wql": 0.8487597635994535 + } + }, + { + "config_id": "ett1__T__long", + "leaderboard_key": "ett1/15T/long", + "dataset": "ett1/15T", + "term": "long", + "freq": "15T", + "prediction_length": 720, + "seasonality": 96, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.327073089604087, + "wql": 0.5796800252115644 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.3123263431761003, + "wql": 0.48335732053145847, + "wsql_by_level": [ + 0.307761382724777, + 0.4705484816508691, + 0.5893429410666685, + 0.6421402280140814, + 0.6387720680355108, + 0.5887864350035353, + 0.5019154450168467, + 0.3827227669236787, + 0.22822613634715896 + ], + "n_valid_labels": 5040, + "n_masked_labels": 0, + "mae_median": 2.1899329521397632, + "n_mase_elements": 5040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.988887766210084, + "wql": 0.8338347010577927 + } + }, + { + "config_id": "ett1__H__short", + "leaderboard_key": "ett1/H/short", + "dataset": "ett1/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0441605493380515, + "wql": 0.5044116168241106 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.764186760002598, + "wql": 0.3403765828700584, + "wsql_by_level": [ + 0.20054579996029875, + 0.3035196825642922, + 0.3698340052124777, + 0.4221233181512067, + 0.4424400319125334, + 0.4369823506354944, + 0.397659222237294, + 0.31562326011376196, + 0.17466157504316615 + ], + "n_valid_labels": 336, + "n_masked_labels": 0, + "mae_median": 5.346845639958268, + "n_mase_elements": 336, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7318671065355384, + "wql": 0.6747992542541866 + } + }, + { + "config_id": "ett1__H__medium", + "leaderboard_key": "ett1/H/medium", + "dataset": "ett1/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.2235872159229322, + "wql": 0.5499353323396741 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.4011011416712038, + "wql": 0.4317332127341386, + "wsql_by_level": [ + 0.29948254556682846, + 0.4658192091188319, + 0.5366459323021678, + 0.5567272877759347, + 0.5432906445191121, + 0.5011691374535995, + 0.43182976358700226, + 0.3394284759611779, + 0.21120591832259253 + ], + "n_valid_labels": 3360, + "n_masked_labels": 0, + "mae_median": 8.313465294692044, + "n_mase_elements": 3360, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.1450766430363328, + "wql": 0.7850617833506894 + } + }, + { + "config_id": "ett1__H__long", + "leaderboard_key": "ett1/H/long", + "dataset": "ett1/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.4320631719624162, + "wql": 0.5783242328839591 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.4323379142769612, + "wql": 0.4150778844660929, + "wsql_by_level": [ + 0.2962515643574201, + 0.4613565692784515, + 0.5370155983358509, + 0.5553667233772366, + 0.5326693879364102, + 0.4782020523304837, + 0.3976404730459638, + 0.29752467291053997, + 0.17967391862247972 + ], + "n_valid_labels": 5040, + "n_masked_labels": 0, + "mae_median": 8.968908114478523, + "n_mase_elements": 5040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.0001918506948047, + "wql": 0.7177252151378869 + } + }, + { + "config_id": "ett1__D__short", + "leaderboard_key": "ett1/D/short", + "dataset": "ett1/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.8181967261759215, + "wql": 0.48528320354978605 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.742998383325776, + "wql": 0.33894350537272816, + "wsql_by_level": [ + 0.16658927590245146, + 0.2989214029078543, + 0.3983746167231747, + 0.4513426682709984, + 0.4550566998820699, + 0.42772194467198016, + 0.3666769255604449, + 0.29072358712068713, + 0.1950844273148928 + ], + "n_valid_labels": 210, + "n_masked_labels": 0, + "mae_median": 144.44604312805902, + "n_mase_elements": 210, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9586412505492161, + "wql": 0.698444749155542 + } + }, + { + "config_id": "ett1__W__short", + "leaderboard_key": "ett1/W/short", + "dataset": "ett1/W", + "term": "short", + "freq": "W-THU", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.2444126904903803, + "wql": 0.25814356436755426 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.033593034603534, + "wql": 0.19527016631492167, + "wsql_by_level": [ + 0.1365289639726844, + 0.1865352557603657, + 0.22317678115645945, + 0.22990201174952818, + 0.2202599250042185, + 0.2183595568112577, + 0.21532257276835998, + 0.1873327942248028, + 0.14001363538661818 + ], + "n_valid_labels": 56, + "n_masked_labels": 0, + "mae_median": 549.7111603873117, + "n_mase_elements": 56, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8305870251099983, + "wql": 0.7564401878207928 + } + }, + { + "config_id": "ett2__T__short", + "leaderboard_key": "ett2/15T/short", + "dataset": "ett2/15T", + "term": "short", + "freq": "15T", + "prediction_length": 48, + "seasonality": 96, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7618250880337474, + "wql": 0.093929612604377 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0696131825548585, + "wql": 0.12938917577079873, + "wsql_by_level": [ + 0.06630448694388948, + 0.10661323358172212, + 0.13515004208305764, + 0.154591923661697, + 0.1654605127808766, + 0.16619135445599453, + 0.15568054982441185, + 0.1306838288981578, + 0.08382664970738161 + ], + "n_valid_labels": 336, + "n_masked_labels": 0, + "mae_median": 2.6402322224208286, + "n_mase_elements": 336, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.4040141226058922, + "wql": 1.3775120772165237 + } + }, + { + "config_id": "ett2__T__medium", + "leaderboard_key": "ett2/15T/medium", + "dataset": "ett2/15T", + "term": "medium", + "freq": "15T", + "prediction_length": 480, + "seasonality": 96, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9027189688220486, + "wql": 0.13649095157039726 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8034282180521727, + "wql": 0.09676315693219488, + "wsql_by_level": [ + 0.0642852337403001, + 0.09778956385192608, + 0.11612856329791325, + 0.12403118619737774, + 0.12315535774227791, + 0.11495778540647218, + 0.09998566208754796, + 0.07854131533070557, + 0.05199374473523305 + ], + "n_valid_labels": 3360, + "n_masked_labels": 0, + "mae_median": 1.8742148856765457, + "n_mase_elements": 3360, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8900092341036772, + "wql": 0.7089345910398158 + } + }, + { + "config_id": "ett2__T__long", + "leaderboard_key": "ett2/15T/long", + "dataset": "ett2/15T", + "term": "long", + "freq": "15T", + "prediction_length": 720, + "seasonality": 96, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0565955316162643, + "wql": 0.16755935574924186 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9940660196103676, + "wql": 0.12459646120835038, + "wsql_by_level": [ + 0.08525082283046481, + 0.12548008724390328, + 0.1498281597252962, + 0.16178246098897475, + 0.16070370390641026, + 0.1485970486484915, + 0.12689691649596915, + 0.0980187655569927, + 0.06481018547865101 + ], + "n_valid_labels": 5040, + "n_masked_labels": 0, + "mae_median": 2.42373161848361, + "n_mase_elements": 5040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9408198216490222, + "wql": 0.7435959672392936 + } + }, + { + "config_id": "ett2__H__short", + "leaderboard_key": "ett2/H/short", + "dataset": "ett2/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9915624508458626, + "wql": 0.11931409133707109 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6930203018528216, + "wql": 0.07497887458506275, + "wsql_by_level": [ + 0.051897663866832755, + 0.0781726779457277, + 0.09205322163217843, + 0.09694039982615654, + 0.09360206118314811, + 0.08460138295170896, + 0.07182314071305292, + 0.06083393097118523, + 0.04488539217557406 + ], + "n_valid_labels": 336, + "n_masked_labels": 0, + "mae_median": 5.738943788267317, + "n_mase_elements": 336, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6989174522105325, + "wql": 0.6284159209094751 + } + }, + { + "config_id": "ett2__H__medium", + "leaderboard_key": "ett2/H/medium", + "dataset": "ett2/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 2.649073318865916, + "wql": 0.345818716053239 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 2.6422015734785287, + "wql": 0.2548147170230195, + "wsql_by_level": [ + 0.1031547126033691, + 0.18295548937825531, + 0.2527666124503449, + 0.3097915825722811, + 0.3470616392525713, + 0.3548591125879356, + 0.32638011290536173, + 0.26137356543442075, + 0.15498962602263539 + ], + "n_valid_labels": 3360, + "n_masked_labels": 0, + "mae_median": 19.73954467236929, + "n_mase_elements": 3360, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9974059814281286, + "wql": 0.736844783680796 + } + }, + { + "config_id": "ett2__H__long", + "leaderboard_key": "ett2/H/long", + "dataset": "ett2/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 3.171779953228176, + "wql": 0.3702966971424018 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 3.212799211210998, + "wql": 0.3552933208625825, + "wsql_by_level": [ + 0.2799350226002499, + 0.3829846459581484, + 0.4332944459116179, + 0.45382029719845046, + 0.4477177509440063, + 0.41536027080112786, + 0.35740299169410294, + 0.273085010609682, + 0.15403945204585662 + ], + "n_valid_labels": 5040, + "n_masked_labels": 0, + "mae_median": 25.263269333179213, + "n_mase_elements": 5040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.0129325673873035, + "wql": 0.9594828244604903 + } + }, + { + "config_id": "ett2__D__short", + "leaderboard_key": "ett2/D/short", + "dataset": "ett2/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 4.704440132303346, + "wql": 0.31867490583739955 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 4.71929721710434, + "wql": 0.3283811762336678, + "wsql_by_level": [ + 0.29416617494405717, + 0.3938450460104784, + 0.42850437843576394, + 0.429942234407033, + 0.4062336550364003, + 0.3611516331590905, + 0.2977461979721755, + 0.22048489274059366, + 0.1233563733974183 + ], + "n_valid_labels": 210, + "n_masked_labels": 0, + "mae_median": 549.3284191063473, + "n_mase_elements": 210, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 1.003158098388579, + "wql": 1.0304582200181798 + } + }, + { + "config_id": "ett2__W__short", + "leaderboard_key": "ett2/W/short", + "dataset": "ett2/W", + "term": "short", + "freq": "W-THU", + "prediction_length": 8, + "seasonality": 1, + "n_variates": 7, + "n_instances": 1, + "domain": "Energy", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.7680609986327813, + "wql": 0.21133928538207686 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.6311045038069198, + "wql": 0.17324740054523854, + "wsql_by_level": [ + 0.10079159594343452, + 0.17388069983380497, + 0.20826686194481153, + 0.22331967713460954, + 0.2234521809566432, + 0.2093358634283538, + 0.17605495037457866, + 0.14315474632496497, + 0.10097002896594572 + ], + "n_valid_labels": 56, + "n_masked_labels": 0, + "mae_median": 2174.751711300441, + "n_mase_elements": 56, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9225385917500764, + "wql": 0.8197595644937825 + } + }, + { + "config_id": "jena_weather__T__short", + "leaderboard_key": "jena_weather/10T/short", + "dataset": "jena_weather/10T", + "term": "short", + "freq": "10T", + "prediction_length": 48, + "seasonality": 144, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7621672521709891, + "wql": 0.1366740261223883 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.4252574434567273, + "wql": 0.01855438183099174, + "wsql_by_level": [ + 0.007203821326484731, + 0.012402259300931556, + 0.016047148457988342, + 0.01903205506614273, + 0.02171927987199733, + 0.02334621540736752, + 0.024229649978673995, + 0.0233885920216093, + 0.019620415047730117 + ], + "n_valid_labels": 1008, + "n_masked_labels": 0, + "mae_median": 3.42261957548677, + "n_mase_elements": 1008, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.5579581676402472, + "wql": 0.13575645905372494 + } + }, + { + "config_id": "jena_weather__T__medium", + "leaderboard_key": "jena_weather/10T/medium", + "dataset": "jena_weather/10T", + "term": "medium", + "freq": "10T", + "prediction_length": 480, + "seasonality": 144, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9778443284819783, + "wql": 0.22790411536869984 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8072658849100436, + "wql": 0.08247203639237989, + "wsql_by_level": [ + 0.02420115660372474, + 0.050742924160527454, + 0.07344457109765382, + 0.08990018763696911, + 0.10093089899685037, + 0.1070742069376445, + 0.10720924720488173, + 0.10126833532996896, + 0.08747679956319827 + ], + "n_valid_labels": 10080, + "n_masked_labels": 0, + "mae_median": 17.06892567877011, + "n_mase_elements": 10080, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8255566467959746, + "wql": 0.36187164176021075 + } + }, + { + "config_id": "jena_weather__T__long", + "leaderboard_key": "jena_weather/10T/long", + "dataset": "jena_weather/10T", + "term": "long", + "freq": "10T", + "prediction_length": 720, + "seasonality": 144, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9055523182794231, + "wql": 0.2428907683297211 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6987782064283822, + "wql": 0.07727274209347496, + "wsql_by_level": [ + 0.028579956252950112, + 0.05390905507714933, + 0.07289102938055085, + 0.08628305377622068, + 0.09451791264447383, + 0.09715912000362661, + 0.0955566406596366, + 0.08961094287105725, + 0.07694696817560943 + ], + "n_valid_labels": 15120, + "n_masked_labels": 0, + "mae_median": 16.15822817024174, + "n_mase_elements": 15120, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7716596736852068, + "wql": 0.31813783053532196 + } + }, + { + "config_id": "jena_weather__H__short", + "leaderboard_key": "jena_weather/H/short", + "dataset": "jena_weather/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7591774901189448, + "wql": 0.1835169108215369 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.5008519882834924, + "wql": 0.05655664721375489, + "wsql_by_level": [ + 0.02306671223659807, + 0.04806196830462026, + 0.06159442114034524, + 0.06773993996943836, + 0.0684648955820893, + 0.06729117759622587, + 0.06452453493960461, + 0.06042631173343655, + 0.04783986342143573 + ], + "n_valid_labels": 1008, + "n_masked_labels": 0, + "mae_median": 11.440364085918565, + "n_mase_elements": 1008, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6597297664937629, + "wql": 0.30818221035092536 + } + }, + { + "config_id": "jena_weather__H__medium", + "leaderboard_key": "jena_weather/H/medium", + "dataset": "jena_weather/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0707310989927863, + "wql": 0.3640989806826866 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8101090819223903, + "wql": 0.09145297201536373, + "wsql_by_level": [ + 0.04476472907080207, + 0.0766050006224796, + 0.09393944195716683, + 0.10299387482697608, + 0.10658035041613502, + 0.10840382732098884, + 0.10705060366479938, + 0.10030165403605502, + 0.08243726622287074 + ], + "n_valid_labels": 10080, + "n_masked_labels": 0, + "mae_median": 18.35794843700301, + "n_mase_elements": 10080, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7565943332405703, + "wql": 0.2511761275570977 + } + }, + { + "config_id": "jena_weather__H__long", + "leaderboard_key": "jena_weather/H/long", + "dataset": "jena_weather/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.4925574952113163, + "wql": 0.44387827099252614 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.992524163229133, + "wql": 0.12233212194466812, + "wsql_by_level": [ + 0.06721096611493609, + 0.11727572077603794, + 0.14207383120432152, + 0.15011407557988168, + 0.14765054689183935, + 0.14073256299869893, + 0.12982911336146163, + 0.1145061280257136, + 0.09159615254912251 + ], + "n_valid_labels": 15120, + "n_masked_labels": 0, + "mae_median": 25.736238953506064, + "n_mase_elements": 15120, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.6649821976128373, + "wql": 0.27559835643932185 + } + }, + { + "config_id": "jena_weather__D__short", + "leaderboard_key": "jena_weather/D/short", + "dataset": "jena_weather/D", + "term": "short", + "freq": "D", + "prediction_length": 30, + "seasonality": 1, + "n_variates": 21, + "n_instances": 1, + "domain": "Nature", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.8578467510262653, + "wql": 0.23138296558762514 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.443662087455527, + "wql": 0.11089317438276146, + "wsql_by_level": [ + 0.04961862622845671, + 0.09477397782776545, + 0.12299067976137472, + 0.13734189194507684, + 0.14254928392660768, + 0.13992328636954648, + 0.12865968927145663, + 0.10775812598102594, + 0.07442300813354276 + ], + "n_valid_labels": 630, + "n_masked_labels": 0, + "mae_median": 24.847062839276532, + "n_mase_elements": 630, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7770619867640081, + "wql": 0.4792624820117366 + } + }, + { + "config_id": "bitbrains_fast_storage__T__short", + "leaderboard_key": "bitbrains_fast_storage/5T/short", + "dataset": "bitbrains_fast_storage/5T", + "term": "short", + "freq": "5T", + "prediction_length": 48, + "seasonality": 288, + "n_variates": 2, + "n_instances": 1250, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.9726733005020567, + "wql": 1.8982594024982165 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1250, + "instances": 1250, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.0593421111558305, + "wql": 0.4736197141546754, + "wsql_by_level": [ + 0.18522539995965692, + 0.3235863761205415, + 0.4346998001254317, + 0.5185323213827823, + 0.5794120459472906, + 0.6151772490456198, + 0.6151769156491563, + 0.5607161171674653, + 0.43005120199413405 + ], + "n_valid_labels": 107692, + "n_masked_labels": 12308, + "mae_median": 170.21454751110988, + "n_mase_elements": 104420, + "n_seasonal_error_zero": 56, + "n_seasonal_error_nan": 52 + }, + "relative": { + "mase": 0.5370083890151612, + "wql": 0.24950210362786307 + } + }, + { + "config_id": "bitbrains_fast_storage__T__medium", + "leaderboard_key": "bitbrains_fast_storage/5T/medium", + "dataset": "bitbrains_fast_storage/5T", + "term": "medium", + "freq": "5T", + "prediction_length": 480, + "seasonality": 288, + "n_variates": 2, + "n_instances": 1250, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.332305698225943, + "wql": 0.7965658755181099 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1250, + "instances": 1250, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.1129761607826445, + "wql": 0.6716054693015313, + "wsql_by_level": [ + 0.49355401241617264, + 0.859143280650735, + 0.9337638637780139, + 0.9059290682862835, + 0.8291196585670596, + 0.7207688153488407, + 0.5920142139677289, + 0.4421483618944695, + 0.26800794880447887 + ], + "n_valid_labels": 1151890, + "n_masked_labels": 48110, + "mae_median": 515.3438083916063, + "n_mase_elements": 1112970, + "n_seasonal_error_zero": 58, + "n_seasonal_error_nan": 66 + }, + "relative": { + "mase": 0.8353759668405301, + "wql": 0.8431260865458232 + } + }, + { + "config_id": "bitbrains_fast_storage__T__long", + "leaderboard_key": "bitbrains_fast_storage/5T/long", + "dataset": "bitbrains_fast_storage/5T", + "term": "long", + "freq": "5T", + "prediction_length": 720, + "seasonality": 288, + "n_variates": 2, + "n_instances": 1250, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.5068539886984111, + "wql": 0.6979053733746295 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1250, + "instances": 1250, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.2531100258064793, + "wql": 0.500429045668183, + "wsql_by_level": [ + 0.341007192983253, + 0.560008050347016, + 0.640839257238496, + 0.6613473385847053, + 0.6394589199077761, + 0.5776901886829315, + 0.4881903875827295, + 0.37116784944132514, + 0.2241522262454152 + ], + "n_valid_labels": 1732080, + "n_masked_labels": 67920, + "mae_median": 466.81533236537314, + "n_mase_elements": 1677544, + "n_seasonal_error_zero": 58, + "n_seasonal_error_nan": 66 + }, + "relative": { + "mase": 0.8316068014585073, + "wql": 0.717044265253933 + } + }, + { + "config_id": "bitbrains_fast_storage__H__short", + "leaderboard_key": "bitbrains_fast_storage/H/short", + "dataset": "bitbrains_fast_storage/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 2, + "n_instances": 1250, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.5571822067903167, + "wql": 0.6231221387021137 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1250, + "instances": 1250, + "fraction": 1.0 + }, + "metrics": { + "mase": 1.3556301863802467, + "wql": 0.48559776005769556, + "wsql_by_level": [ + 0.33829667734182245, + 0.5559228713695178, + 0.6387768585887845, + 0.6474695746295439, + 0.6082746782037193, + 0.5395182875494245, + 0.4586403560681789, + 0.3595284066890432, + 0.223952130079225 + ], + "n_valid_labels": 116442, + "n_masked_labels": 3558, + "mae_median": 429.4449793618243, + "n_mase_elements": 112610, + "n_seasonal_error_zero": 58, + "n_seasonal_error_nan": 66 + }, + "relative": { + "mase": 0.8705661935185404, + "wql": 0.7792978774099337 + } + }, + { + "config_id": "bitbrains_rnd__T__short", + "leaderboard_key": "bitbrains_rnd/5T/short", + "dataset": "bitbrains_rnd/5T", + "term": "short", + "freq": "5T", + "prediction_length": 48, + "seasonality": 288, + "n_variates": 2, + "n_instances": 500, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.8369702659182979, + "wql": 0.895586111036325 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 500, + "instances": 500, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.5518577774011539, + "wql": 0.22176716433571958, + "wsql_by_level": [ + 0.11288407542564684, + 0.17220782599031556, + 0.21291411648756467, + 0.24067459342688877, + 0.25521083809071476, + 0.26170496452804376, + 0.259636069636938, + 0.25796133430853374, + 0.22271066112682988 + ], + "n_valid_labels": 46368, + "n_masked_labels": 1632, + "mae_median": 136.7615177270061, + "n_mase_elements": 45888, + "n_seasonal_error_zero": 10, + "n_seasonal_error_nan": 34 + }, + "relative": { + "mase": 0.6593517116114903, + "wql": 0.24762238002898718 + } + }, + { + "config_id": "bitbrains_rnd__T__medium", + "leaderboard_key": "bitbrains_rnd/5T/medium", + "dataset": "bitbrains_rnd/5T", + "term": "medium", + "freq": "5T", + "prediction_length": 480, + "seasonality": 288, + "n_variates": 2, + "n_instances": 500, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9740075110165132, + "wql": 1.1044931903333195 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 500, + "instances": 500, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.8226966429030266, + "wql": 0.8695253493994237, + "wsql_by_level": [ + 0.343096905529961, + 0.6965474334054153, + 0.8802173650233293, + 0.9841804499209531, + 1.038843784261278, + 1.0520002623308595, + 1.0261048045869936, + 0.9603947295767309, + 0.8443424099592926 + ], + "n_valid_labels": 455110, + "n_masked_labels": 24890, + "mae_median": 311.9840166388593, + "n_mase_elements": 441864, + "n_seasonal_error_zero": 10, + "n_seasonal_error_nan": 54 + }, + "relative": { + "mase": 0.844651230712202, + "wql": 0.787261847342865 + } + }, + { + "config_id": "bitbrains_rnd__T__long", + "leaderboard_key": "bitbrains_rnd/5T/long", + "dataset": "bitbrains_rnd/5T", + "term": "long", + "freq": "5T", + "prediction_length": 720, + "seasonality": 288, + "n_variates": 2, + "n_instances": 500, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.1660081104198932, + "wql": 0.9977535818816068 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 500, + "instances": 500, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9668005345759616, + "wql": 0.7371965495669304, + "wsql_by_level": [ + 0.27094090823381217, + 0.434484663177823, + 0.5738092511997975, + 0.7025376029007325, + 0.8197202527779688, + 0.9252151320531801, + 1.00605480690398, + 1.0369914405339349, + 0.8650148883211443 + ], + "n_valid_labels": 684238, + "n_masked_labels": 35762, + "mae_median": 268.1499411709821, + "n_mase_elements": 657984, + "n_seasonal_error_zero": 12, + "n_seasonal_error_nan": 64 + }, + "relative": { + "mase": 0.8291542107951594, + "wql": 0.738856329813112 + } + }, + { + "config_id": "bitbrains_rnd__H__short", + "leaderboard_key": "bitbrains_rnd/H/short", + "dataset": "bitbrains_rnd/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 2, + "n_instances": 500, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.1175347302132743, + "wql": 0.9314629241561541 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 500, + "instances": 500, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.9123749502738243, + "wql": 0.61284087786555, + "wsql_by_level": [ + 0.17025695109437916, + 0.33451745186359444, + 0.5077861326106005, + 0.6585042313892268, + 0.7852847299717295, + 0.8446606146550141, + 0.8347322431916672, + 0.7683390837696029, + 0.6114864622441357 + ], + "n_valid_labels": 46216, + "n_masked_labels": 1784, + "mae_median": 254.38266735450813, + "n_mase_elements": 44928, + "n_seasonal_error_zero": 10, + "n_seasonal_error_nan": 54 + }, + "relative": { + "mase": 0.8164175354977141, + "wql": 0.6579337319526106 + } + }, + { + "config_id": "bizitobs_application__S__short", + "leaderboard_key": "bizitobs_application/10S/short", + "dataset": "bizitobs_application", + "term": "short", + "freq": "10S", + "prediction_length": 60, + "seasonality": 360, + "n_variates": 2, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.3935671590031806, + "wql": 0.01840457246049758 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.5357908563923016, + "wql": 0.009640745613154209, + "wsql_by_level": [ + 0.005706867088226679, + 0.009185701909113555, + 0.011442089749474768, + 0.0126396015169553, + 0.012934225250250517, + 0.012302813628655169, + 0.010539304833132184, + 0.007756889305860633, + 0.0042592172367190715 + ], + "n_valid_labels": 120, + "n_masked_labels": 0, + "mae_median": 334.6782527923584, + "n_mase_elements": 120, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.3844743706328105, + "wql": 0.5238233940965759 + } + }, + { + "config_id": "bizitobs_application__S__medium", + "leaderboard_key": "bizitobs_application/10S/medium", + "dataset": "bizitobs_application", + "term": "medium", + "freq": "10S", + "prediction_length": 600, + "seasonality": 360, + "n_variates": 2, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9183336447716528, + "wql": 0.013742470259025481 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6720055894160316, + "wql": 0.008993228966356057, + "wsql_by_level": [ + 0.005331774459229003, + 0.008037839731728258, + 0.009906151678847014, + 0.011048885808405741, + 0.011532837024810555, + 0.011270806993908176, + 0.010255230749607972, + 0.008336631884893492, + 0.005218902365774303 + ], + "n_valid_labels": 1200, + "n_masked_labels": 0, + "mae_median": 276.0973589865367, + "n_mase_elements": 1200, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7317662738830922, + "wql": 0.6544113828770834 + } + }, + { + "config_id": "bizitobs_application__S__long", + "leaderboard_key": "bizitobs_application/10S/long", + "dataset": "bizitobs_application", + "term": "long", + "freq": "10S", + "prediction_length": 900, + "seasonality": 360, + "n_variates": 2, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7487259254586917, + "wql": 0.012942679940654697 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7147419161296621, + "wql": 0.009417046576486975, + "wsql_by_level": [ + 0.005615684733042007, + 0.008806406230986016, + 0.010792684543634317, + 0.011812197309494132, + 0.011997029462683103, + 0.011547769128777446, + 0.010406613421155578, + 0.008438405294745181, + 0.005336629063864999 + ], + "n_valid_labels": 1800, + "n_masked_labels": 0, + "mae_median": 292.312062057919, + "n_mase_elements": 1800, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.9546108820684819, + "wql": 0.72759634169016 + } + }, + { + "config_id": "bizitobs_service__S__short", + "leaderboard_key": "bizitobs_service/10S/short", + "dataset": "bizitobs_service", + "term": "short", + "freq": "10S", + "prediction_length": 60, + "seasonality": 360, + "n_variates": 2, + "n_instances": 21, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.0559084960397855, + "wql": 0.025515037101462117 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 21, + "instances": 21, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.5076168099233301, + "wql": 0.009002125929086117, + "wsql_by_level": [ + 0.005521871876954798, + 0.008706895487164587, + 0.010758077179763773, + 0.01182535243657376, + 0.012015026539836313, + 0.011401388468273444, + 0.009872177142996702, + 0.007262161002139866, + 0.003656183228071802 + ], + "n_valid_labels": 2520, + "n_masked_labels": 0, + "mae_median": 16.110688292270616, + "n_mase_elements": 2520, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.48073939344854333, + "wql": 0.35281649379103813 + } + }, + { + "config_id": "bizitobs_service__S__medium", + "leaderboard_key": "bizitobs_service/10S/medium", + "dataset": "bizitobs_service", + "term": "medium", + "freq": "10S", + "prediction_length": 600, + "seasonality": 360, + "n_variates": 2, + "n_instances": 21, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.9546641394188339, + "wql": 0.023513421962609537 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 21, + "instances": 21, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.6729060450908224, + "wql": 0.009794907918858562, + "wsql_by_level": [ + 0.00607698196474443, + 0.009213216607658033, + 0.011161518923551864, + 0.012196153834766037, + 0.012443721774536676, + 0.011977344979010868, + 0.010802284082934745, + 0.00877126126880751, + 0.005511687833716899 + ], + "n_valid_labels": 25200, + "n_masked_labels": 0, + "mae_median": 15.695413104118336, + "n_mase_elements": 25200, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.7048615500530523, + "wql": 0.4165666713434643 + } + }, + { + "config_id": "bizitobs_service__S__long", + "leaderboard_key": "bizitobs_service/10S/long", + "dataset": "bizitobs_service", + "term": "long", + "freq": "10S", + "prediction_length": 900, + "seasonality": 360, + "n_variates": 2, + "n_instances": 21, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.8316933390369606, + "wql": 0.023678985220657325 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 21, + "instances": 21, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7434164225187173, + "wql": 0.010573591393059275, + "wsql_by_level": [ + 0.0063136198778993725, + 0.009860483714965477, + 0.012037003173613484, + 0.013232118946578398, + 0.013581299050146723, + 0.013137048608381175, + 0.011765229881868717, + 0.009361097288569282, + 0.00587442199551084 + ], + "n_valid_labels": 37800, + "n_masked_labels": 0, + "mae_median": 17.35466092003584, + "n_mase_elements": 37800, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.8938588150525992, + "wql": 0.44653904272193945 + } + }, + { + "config_id": "bizitobs_l2c__T__short", + "leaderboard_key": "bizitobs_l2c/5T/short", + "dataset": "bizitobs_l2c/5T", + "term": "short", + "freq": "5T", + "prediction_length": 48, + "seasonality": 288, + "n_variates": 7, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 0.7721410982041648, + "wql": 0.22094461659341424 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.17620784557534244, + "wql": 0.05198605890523452, + "wsql_by_level": [ + 0.039115064823848064, + 0.05721952087046935, + 0.06634063144469578, + 0.06827666022661018, + 0.064819915954785, + 0.058874862457406966, + 0.04853064937129885, + 0.03791464652521037, + 0.026782578472786086 + ], + "n_valid_labels": 336, + "n_masked_labels": 0, + "mae_median": 1.6651754180590312, + "n_mase_elements": 336, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.22820679534500138, + "wql": 0.235290000303108 + } + }, + { + "config_id": "bizitobs_l2c__T__medium", + "leaderboard_key": "bizitobs_l2c/5T/medium", + "dataset": "bizitobs_l2c/5T", + "term": "medium", + "freq": "5T", + "prediction_length": 480, + "seasonality": 288, + "n_variates": 7, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.4416925389331963, + "wql": 0.47091183801289255 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.4687418350220447, + "wql": 0.15091588321053273, + "wsql_by_level": [ + 0.11985851733238993, + 0.16679772562375386, + 0.18846160225251862, + 0.18761118241614, + 0.17979751552158196, + 0.16807779633616968, + 0.14831121253533072, + 0.11596759983999938, + 0.08335979703691049 + ], + "n_valid_labels": 3360, + "n_masked_labels": 0, + "mae_median": 4.001506079981724, + "n_mase_elements": 3360, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.32513301023871416, + "wql": 0.32047587473560385 + } + }, + { + "config_id": "bizitobs_l2c__T__long", + "leaderboard_key": "bizitobs_l2c/5T/long", + "dataset": "bizitobs_l2c/5T", + "term": "long", + "freq": "5T", + "prediction_length": 720, + "seasonality": 288, + "n_variates": 7, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.6820288964143004, + "wql": 0.6755692567838184 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.7423525109082231, + "wql": 0.27920598018588255, + "wsql_by_level": [ + 0.14485213078998457, + 0.2354901203999575, + 0.30001254677827677, + 0.34205633604288704, + 0.37412344316363244, + 0.3784870685128515, + 0.34959269898614426, + 0.2575462345080017, + 0.13069324249120656 + ], + "n_valid_labels": 5040, + "n_masked_labels": 0, + "mae_median": 6.844067294555642, + "n_mase_elements": 5040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.44134349444932147, + "wql": 0.4132899438247058 + } + }, + { + "config_id": "bizitobs_l2c__H__short", + "leaderboard_key": "bizitobs_l2c/H/short", + "dataset": "bizitobs_l2c/H", + "term": "short", + "freq": "H", + "prediction_length": 48, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.5845833438972332, + "wql": 0.5573763030242874 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.691100880879655, + "wql": 0.2074221193214032, + "wsql_by_level": [ + 0.122494192764358, + 0.21131032642492306, + 0.27639593803647405, + 0.2989209228111275, + 0.29756310971041383, + 0.26092835233579925, + 0.19471032063797966, + 0.12760851019806052, + 0.07686740097349272 + ], + "n_valid_labels": 336, + "n_masked_labels": 0, + "mae_median": 6.225689606009317, + "n_mase_elements": 336, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.436140442559439, + "wql": 0.37214018284585176 + } + }, + { + "config_id": "bizitobs_l2c__H__medium", + "leaderboard_key": "bizitobs_l2c/H/medium", + "dataset": "bizitobs_l2c/H", + "term": "medium", + "freq": "H", + "prediction_length": 480, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.6159633796006725, + "wql": 1.1167911109559348 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.3496421376412217, + "wql": 0.2094430562519484, + "wsql_by_level": [ + 0.11329214214416998, + 0.1774260088971426, + 0.21465949889240707, + 0.23873915505399734, + 0.25169355946693417, + 0.2510291711343047, + 0.24126666882535183, + 0.2228160312251548, + 0.1740652706280729 + ], + "n_valid_labels": 3360, + "n_masked_labels": 0, + "mae_median": 3.444867950025946, + "n_mase_elements": 3360, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.21636761207275826, + "wql": 0.18754004593810955 + } + }, + { + "config_id": "bizitobs_l2c__H__long", + "leaderboard_key": "bizitobs_l2c/H/long", + "dataset": "bizitobs_l2c/H", + "term": "long", + "freq": "H", + "prediction_length": 720, + "seasonality": 24, + "n_variates": 7, + "n_instances": 1, + "domain": "Web/CloudOps", + "n_cohorts": 1, + "status": "ok", + "baseline": { + "mase": 1.280223980485366, + "wql": 1.0134048622912797 + }, + "quantile_crossing_fraction": 0.0, + "coverage": { + "instances_scored": 1, + "instances": 1, + "fraction": 1.0 + }, + "metrics": { + "mase": 0.427479164109974, + "wql": 0.21419413351494765, + "wsql_by_level": [ + 0.1170480726921636, + 0.18689250690465406, + 0.23152060009130032, + 0.25454984294517113, + 0.2609357477303992, + 0.25361942326514153, + 0.24215246291043507, + 0.21674787824176037, + 0.16428066685350382 + ], + "n_valid_labels": 5040, + "n_masked_labels": 0, + "mae_median": 3.9424317456427076, + "n_mase_elements": 5040, + "n_seasonal_error_zero": 0, + "n_seasonal_error_nan": 0 + }, + "relative": { + "mase": 0.3339096678597644, + "wql": 0.2113608701567316 + } + } + ], + "checkpoint_sha256": "74d648f1505df6d90123e5d8ca2895b54805f37da97976a1e98cbc2564568960", + "inference_seconds": 718.7604067868087, + "minimum_free_before_replay_mib": 16096.0, + "observed_free_before_replay_mib": 17572.0, + "memory_guard_and_lock_wait_seconds": 123.36737965187058 +} diff --git a/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/zero_mass.py b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/zero_mass.py new file mode 100644 index 0000000000000000000000000000000000000000..7e9c7067950c67da130e2c2538ffb42f34537402 --- /dev/null +++ b/tasks/timeseries-forecasting/timeseries-forecasting-astra-xhigh-1h100-48h-20261022a/submissions/S129/zero_mass.py @@ -0,0 +1,12 @@ +"""Fixed zero-mass projection from the supplied history only.""" +import numpy as np + +def project(ctx,q,threshold=.4): + finite=np.isfinite(ctx);n=finite.sum(-1).clip(min=1) + x=np.where(finite,ctx,0.) + mean=x.sum(-1)/n + scale=np.sqrt((np.where(finite,ctx-mean[...,None],0.)**2).sum(-1)/n) + zero=((ctx==0)&finite).sum(-1) + active=((ctx>=0)|~finite).all(-1)&(zero>=4)&(zero/n>=.1) + cutoff=np.where(active,threshold*scale,0.) + return np.where((q>=0)&(q