diff --git a/A1_R1_R2_FIX1_gate_report.txt b/A1_R1_R2_FIX1_gate_report.txt new file mode 100644 index 0000000000000000000000000000000000000000..c98b306aa09126d0518fc104bc40d1063c5cd81c --- /dev/null +++ b/A1_R1_R2_FIX1_gate_report.txt @@ -0,0 +1,22 @@ +CIDM Foundation A1-R1-R2 FIX1 — Stable Semantic Dynamics Qualification +============================================================================================ +VERDICT: CORE_SEMANTICS_REVIEW_REQUIRED +Selected candidate: C1_Euler_Sync + +[PASS] NeuralOperator checkpoint repair 3/3 +[PASS] confirmation_complete +[FAIL] positive_sync_2of3 +[PASS] anchor_decode_2of3 +[PASS] step_scale_2of3 +[FAIL] prediction_cost_le_1p05 +[FAIL] structured_vs_blackbox_le_1p15 +[PASS] dynamics_alignment_2of3 +positive_sync_tasks: 1 +anchor_good_tasks: 2 +step_scale_good_tasks: 2 +selected_vs_predonly_rmse_ratio: 1.0957973990673535 +selected_vs_blackbox_rmse_ratio: 1.1942276568119583 +alignment_positive_tasks: 3 + +Interpretation: +CORE_SEMANTICS_REVIEW_REQUIRED -> numerical engineering is stable; revise/interpret state semantics before scaling. \ No newline at end of file diff --git a/CIDM_Foundation_A1_R1_R2_FIX1_REPORT.json b/CIDM_Foundation_A1_R1_R2_FIX1_REPORT.json new file mode 100644 index 0000000000000000000000000000000000000000..ba154120e1eefd51383b75263396244cb63fd349 --- /dev/null +++ b/CIDM_Foundation_A1_R1_R2_FIX1_REPORT.json @@ -0,0 +1,1201 @@ +{ + "experiment": "CIDM Foundation A1-R1-R2 Semantic State Anchoring + Discrete Dynamics Qualification", + "started_at": "2026-09-27 13:52:08", + "protocol": { + "history": 4, + "horizon": 6, + "screen_updates": 80, + "confirm_updates": 240, + "seeds": [ + 17, + 41 + ] + }, + "engineering_repair": [ + { + "task": "burgers", + "pass": true, + "removed_pseudo_metadata_keys": [ + "_metadata" + ], + "error": "" + }, + { + "task": "diff_react_2d", + "pass": true, + "removed_pseudo_metadata_keys": [ + "_metadata" + ], + "error": "" + }, + { + "task": "swe_2d", + "pass": true, + "removed_pseudo_metadata_keys": [ + "_metadata" + ], + "error": "" + } + ], + "screen": [ + { + "candidate": "C0_Euler_PredOnly", + "task": "burgers", + "completed": true, + "completed_steps": 80, + "numerical_fail": false, + "fail_reason": "", + "best_val_rmse": 0.1927094808535734, + "sync_gain_mean": -0.3006888248943694, + "sync_gain_last": -0.44500984220287754, + "sync_by_lead": [ + -0.20261117563843672, + -0.22347428346155065, + -0.25803652081418854, + -0.3061182517524385, + -0.36888287549672427, + -0.44500984220287754 + ], + "observed_state_anchor_decode_rmse": 0.10879550874233246, + "dynamic_final_decode_rmse": 0.2503768801689148, + "anchor_to_dynamic_decode_ratio": 0.43452697656802186, + "observed_final_relative_speed": 0.13004452735185623, + "dynamic_final_relative_speed": 0.13318440318107605, + "final_step_norm_ratio_dyn_over_obs": 188.55020904541016, + "total_delta_cos": -0.0009603229118511081 + }, + { + "candidate": "C0_Euler_PredOnly", + "task": "diff_react_2d", + "completed": true, + "completed_steps": 80, + "numerical_fail": false, + "fail_reason": "", + "best_val_rmse": 0.024831059020262915, + "sync_gain_mean": -0.02114614252259943, + "sync_gain_last": -0.06249073316170445, + "sync_by_lead": [ + 0.0036176433148209664, + 0.0008869479306628327, + -0.007616966272027343, + -0.021396254974827448, + -0.03987749197252113, + -0.06249073316170445 + ], + "observed_state_anchor_decode_rmse": 0.04411158384755254, + "dynamic_final_decode_rmse": 0.0232164915651083, + "anchor_to_dynamic_decode_ratio": 1.900010762773784, + "observed_final_relative_speed": 0.15421431325376034, + "dynamic_final_relative_speed": 0.06592305190861225, + "final_step_norm_ratio_dyn_over_obs": 1.9657797366380692, + "total_delta_cos": 0.03426280105486512 + }, + { + "candidate": "C0_Euler_PredOnly", + "task": "swe_2d", + "completed": true, + "completed_steps": 80, + "numerical_fail": false, + "fail_reason": "", + "best_val_rmse": 0.04483280360039643, + "sync_gain_mean": -1.3746120733322762, + "sync_gain_last": -1.3346015740334378, + "sync_by_lead": [ + -1.4804809235816514, + -1.4110297544615733, + -1.3612958515219948, + -1.333688718284344, + -1.3265756181106565, + -1.3346015740334378 + ], + "observed_state_anchor_decode_rmse": 0.03895185701549053, + "dynamic_final_decode_rmse": 0.05247679725289345, + "anchor_to_dynamic_decode_ratio": 0.7422681843134552, + "observed_final_relative_speed": 0.060159413143992424, + "dynamic_final_relative_speed": 0.07279826980084181, + "final_step_norm_ratio_dyn_over_obs": 1.276487648487091, + "total_delta_cos": 0.0028314988303463906 + }, + { + "candidate": "C1_Euler_Sync", + "task": "burgers", + "completed": true, + "completed_steps": 80, + "numerical_fail": false, + "fail_reason": "", + "best_val_rmse": 0.18325291609720723, + "sync_gain_mean": -0.10253197211373803, + "sync_gain_last": -0.1513257326976225, + "sync_by_lead": [ + -0.06981393199906824, + -0.0764174628003239, + -0.08790234855824777, + -0.10418655859872758, + -0.12554579802843818, + -0.1513257326976225 + ], + "observed_state_anchor_decode_rmse": 0.09322044998407364, + "dynamic_final_decode_rmse": 0.24303140491247177, + "anchor_to_dynamic_decode_ratio": 0.38357367854433116, + "observed_final_relative_speed": 0.12311743199825287, + "dynamic_final_relative_speed": 0.07198306173086166, + "final_step_norm_ratio_dyn_over_obs": 105.13082504272461, + "total_delta_cos": 0.0021982438629493117 + }, + { + "candidate": "C1_Euler_Sync", + "task": "diff_react_2d", + "completed": true, + "completed_steps": 80, + "numerical_fail": false, + "fail_reason": "", + "best_val_rmse": 0.024582025354822408, + "sync_gain_mean": 0.11930255013020437, + "sync_gain_last": 0.15029867369609384, + "sync_by_lead": [ + 0.05272485714011917, + 0.0953130227762066, + 0.12501012466872197, + 0.14243373134490073, + 0.15003489115518392, + 0.15029867369609384 + ], + "observed_state_anchor_decode_rmse": 0.04474326269701123, + "dynamic_final_decode_rmse": 0.023331256350502372, + "anchor_to_dynamic_decode_ratio": 1.9177391060660913, + "observed_final_relative_speed": 0.16310996748507023, + "dynamic_final_relative_speed": 0.04300540452823043, + "final_step_norm_ratio_dyn_over_obs": 1.268760159611702, + "total_delta_cos": 0.22015358321368694 + }, + { + "candidate": "C1_Euler_Sync", + "task": "swe_2d", + "completed": true, + "completed_steps": 80, + "numerical_fail": false, + "fail_reason": "", + "best_val_rmse": 0.04883607114269896, + "sync_gain_mean": -0.14820378194018016, + "sync_gain_last": -0.14538981194781428, + "sync_by_lead": [ + -0.1584948208480223, + -0.15127420994186955, + -0.14634155636197324, + -0.14391234689455742, + -0.14380994564684413, + -0.14538981194781428 + ], + "observed_state_anchor_decode_rmse": 0.04511865368112922, + "dynamic_final_decode_rmse": 0.054074378218501806, + "anchor_to_dynamic_decode_ratio": 0.8343813681743206, + "observed_final_relative_speed": 0.05112661141902208, + "dynamic_final_relative_speed": 0.020537434611469507, + "final_step_norm_ratio_dyn_over_obs": 0.42128879204392433, + "total_delta_cos": 0.004927229834720492 + }, + { + "candidate": "C2_Euler_AnchorSync", + "task": "burgers", + "completed": true, + "completed_steps": 80, + "numerical_fail": false, + "fail_reason": "", + "best_val_rmse": 0.18064571493649606, + "sync_gain_mean": -0.10826834960314285, + "sync_gain_last": -0.1598083649277041, + "sync_by_lead": [ + -0.07359937128683236, + -0.08065561357863757, + -0.09284401460179811, + -0.11007830806047514, + -0.1326244251634099, + -0.1598083649277041 + ], + "observed_state_anchor_decode_rmse": 0.08606893569231033, + "dynamic_final_decode_rmse": 0.24112822860479355, + "anchor_to_dynamic_decode_ratio": 0.35694259519227156, + "observed_final_relative_speed": 0.12323768436908722, + "dynamic_final_relative_speed": 0.0740467868745327, + "final_step_norm_ratio_dyn_over_obs": 107.70825576782227, + "total_delta_cos": 0.0026565948501229286 + }, + { + "candidate": "C2_Euler_AnchorSync", + "task": "diff_react_2d", + "completed": true, + "completed_steps": 80, + "numerical_fail": false, + "fail_reason": "", + "best_val_rmse": 0.02546062857490604, + "sync_gain_mean": 0.12025233390789229, + "sync_gain_last": 0.14730201344758773, + "sync_by_lead": [ + 0.054885831287266484, + 0.0984540187253503, + 0.12776774572281732, + 0.14376562928191766, + 0.1493387649824143, + 0.14730201344758773 + ], + "observed_state_anchor_decode_rmse": 0.04074244713410735, + "dynamic_final_decode_rmse": 0.023450369480997324, + "anchor_to_dynamic_decode_ratio": 1.7373904137042453, + "observed_final_relative_speed": 0.1483233105391264, + "dynamic_final_relative_speed": 0.04373121401295066, + "final_step_norm_ratio_dyn_over_obs": 1.2804347276687622, + "total_delta_cos": 0.23297834023833275 + }, + { + "candidate": "C2_Euler_AnchorSync", + "task": "swe_2d", + "completed": true, + "completed_steps": 80, + "numerical_fail": false, + "fail_reason": "", + "best_val_rmse": 0.04998966287485394, + "sync_gain_mean": -0.17515967673026003, + "sync_gain_last": -0.17215532843838954, + "sync_by_lead": [ + -0.18697687211370834, + -0.17859511724316163, + -0.1729023192396738, + -0.17016396260500957, + -0.17016446074161745, + -0.17215532843838957 + ], + "observed_state_anchor_decode_rmse": 0.045912849716842175, + "dynamic_final_decode_rmse": 0.055659638717770576, + "anchor_to_dynamic_decode_ratio": 0.8248858737594262, + "observed_final_relative_speed": 0.05513222049921751, + "dynamic_final_relative_speed": 0.024001186480745673, + "final_step_norm_ratio_dyn_over_obs": 0.45728158950805664, + "total_delta_cos": 0.004049755341839045 + }, + { + "candidate": "C3_Euler_AnchorSyncSpeed", + "task": "burgers", + "completed": true, + "completed_steps": 80, + "numerical_fail": false, + "fail_reason": "", + "best_val_rmse": 0.18064751420397368, + "sync_gain_mean": -0.10821009706597834, + "sync_gain_last": -0.1597204009182012, + "sync_by_lead": [ + -0.07356191515670607, + -0.08061325837582677, + -0.09279443822724534, + -0.11001866948748129, + -0.13255190023040933, + -0.1597204009182012 + ], + "observed_state_anchor_decode_rmse": 0.08607283234596252, + "dynamic_final_decode_rmse": 0.24112923443317413, + "anchor_to_dynamic_decode_ratio": 0.35695726629039876, + "observed_final_relative_speed": 0.12323671206831932, + "dynamic_final_relative_speed": 0.07403664290904999, + "final_step_norm_ratio_dyn_over_obs": 107.68050003051758, + "total_delta_cos": 0.002816198975779116 + }, + { + "candidate": "C3_Euler_AnchorSyncSpeed", + "task": "diff_react_2d", + "completed": true, + "completed_steps": 80, + "numerical_fail": false, + "fail_reason": "", + "best_val_rmse": 0.02551979169873434, + "sync_gain_mean": 0.1220662932787878, + "sync_gain_last": 0.1480823581029484, + "sync_by_lead": [ + 0.056311738534595146, + 0.10071620852756775, + 0.13027492183874695, + 0.14602528019267824, + 0.15098725247619033, + 0.1480823581029484 + ], + "observed_state_anchor_decode_rmse": 0.040704610757529736, + "dynamic_final_decode_rmse": 0.023457656847313046, + "anchor_to_dynamic_decode_ratio": 1.7352377103338963, + "observed_final_relative_speed": 0.14809156954288483, + "dynamic_final_relative_speed": 0.04514878848567605, + "final_step_norm_ratio_dyn_over_obs": 1.3182497322559357, + "total_delta_cos": 0.2308701928704977 + }, + { + "candidate": "C3_Euler_AnchorSyncSpeed", + "task": "swe_2d", + "completed": true, + "completed_steps": 80, + "numerical_fail": false, + "fail_reason": "", + "best_val_rmse": 0.05001558298723604, + "sync_gain_mean": -0.18005569652876638, + "sync_gain_last": -0.17700700379293824, + "sync_by_lead": [ + -0.19216317796839552, + -0.18356241922961328, + -0.1777274584499916, + -0.17492911551837337, + -0.1749450042132863, + -0.1770070037929382 + ], + "observed_state_anchor_decode_rmse": 0.04593736073002219, + "dynamic_final_decode_rmse": 0.05568184703588486, + "anchor_to_dynamic_decode_ratio": 0.8249970713151323, + "observed_final_relative_speed": 0.05510684801265597, + "dynamic_final_relative_speed": 0.02431022608652711, + "final_step_norm_ratio_dyn_over_obs": 0.4634660631418228, + "total_delta_cos": 0.004047444206662476 + }, + { + "candidate": "C4_Cayley_AnchorSyncSpeed", + "task": "burgers", + "completed": true, + "completed_steps": 80, + "numerical_fail": false, + "fail_reason": "", + "best_val_rmse": 0.18261261286590064, + "sync_gain_mean": -0.10540268142570507, + "sync_gain_last": -0.15545500488780317, + "sync_by_lead": [ + -0.07176205618429825, + -0.0785879231085855, + -0.09041216886072787, + -0.1071507542323504, + -0.12904818128046522, + -0.15545500488780317 + ], + "observed_state_anchor_decode_rmse": 0.08942092582583427, + "dynamic_final_decode_rmse": 0.2429230958223343, + "anchor_to_dynamic_decode_ratio": 0.368103845882294, + "observed_final_relative_speed": 0.12412595748901367, + "dynamic_final_relative_speed": 0.07375380024313927, + "final_step_norm_ratio_dyn_over_obs": 107.19236755371094, + "total_delta_cos": 0.002824177499860525 + }, + { + "candidate": "C4_Cayley_AnchorSyncSpeed", + "task": "diff_react_2d", + "completed": true, + "completed_steps": 80, + "numerical_fail": false, + "fail_reason": "", + "best_val_rmse": 0.025477729483350888, + "sync_gain_mean": 0.12223053653096867, + "sync_gain_last": 0.14843460858092944, + "sync_by_lead": [ + 0.05632478851641616, + 0.10076914924860095, + 0.13038826978895218, + 0.14621188062019522, + 0.15125452243071827, + 0.14843460858092944 + ], + "observed_state_anchor_decode_rmse": 0.040719661861658096, + "dynamic_final_decode_rmse": 0.023436493007466197, + "anchor_to_dynamic_decode_ratio": 1.7374468888619972, + "observed_final_relative_speed": 0.14819438941776752, + "dynamic_final_relative_speed": 0.04506289679557085, + "final_step_norm_ratio_dyn_over_obs": 1.3153119385242462, + "total_delta_cos": 0.2292734533548355 + }, + { + "candidate": "C4_Cayley_AnchorSyncSpeed", + "task": "swe_2d", + "completed": true, + "completed_steps": 80, + "numerical_fail": false, + "fail_reason": "", + "best_val_rmse": 0.049824426458319096, + "sync_gain_mean": -0.18659384667363343, + "sync_gain_last": -0.1836969632301449, + "sync_by_lead": [ + -0.19901918821057574, + -0.19007246903721187, + -0.18407872926432078, + -0.18127651685200724, + -0.18141921344754017, + -0.1836969632301449 + ], + "observed_state_anchor_decode_rmse": 0.046432615257799625, + "dynamic_final_decode_rmse": 0.0543952533043921, + "anchor_to_dynamic_decode_ratio": 0.8536152042158146, + "observed_final_relative_speed": 0.05170767800882459, + "dynamic_final_relative_speed": 0.02326575736515224, + "final_step_norm_ratio_dyn_over_obs": 0.47307102009654045, + "total_delta_cos": 0.0048957543913275 + } + ], + "screen_summary": [ + { + "candidate": "C0_Euler_PredOnly", + "eligible": true, + "mean_val_rmse_ratio_vs_C0": 1.0, + "positive_sync_tasks": 0, + "mean_sync_last": -0.61403404979934, + "mean_abs_log_step_ratio": 2.0531218643764655, + "mean_anchor_to_dynamic_decode_ratio": 1.0256019745517537, + "reason": "" + }, + { + "candidate": "C1_Euler_Sync", + "eligible": true, + "mean_val_rmse_ratio_vs_C0": 1.0100641789029845, + "positive_sync_tasks": 1, + "mean_sync_last": -0.04880562364978098, + "mean_abs_log_step_ratio": 1.9192274707864214, + "mean_anchor_to_dynamic_decode_ratio": 1.045231384261581, + "reason": "" + }, + { + "candidate": "C2_Euler_AnchorSync", + "eligible": true, + "mean_val_rmse_ratio_vs_C0": 1.025925855923959, + "positive_sync_tasks": 1, + "mean_sync_last": -0.06155389330616864, + "mean_abs_log_step_ratio": 1.9030272653173714, + "mean_anchor_to_dynamic_decode_ratio": 0.9730729608853145, + "reason": "" + }, + { + "candidate": "C3_Euler_AnchorSyncSpeed", + "eligible": true, + "mean_val_rmse_ratio_vs_C0": 1.0269158936455245, + "positive_sync_tasks": 1, + "mean_sync_last": -0.06288168220273034, + "mean_abs_log_step_ratio": 1.9081651737388137, + "mean_anchor_to_dynamic_decode_ratio": 0.9723973493131424, + "reason": "" + }, + { + "candidate": "C4_Cayley_AnchorSyncSpeed", + "eligible": true, + "mean_val_rmse_ratio_vs_C0": 1.028329062849252, + "positive_sync_tasks": 1, + "mean_sync_last": -0.06357245317900621, + "mean_abs_log_step_ratio": 1.8990695515270037, + "mean_anchor_to_dynamic_decode_ratio": 0.9863886463200352, + "reason": "" + } + ], + "selected_candidate": "C1_Euler_Sync", + "confirmation": [ + { + "seed": 17, + "task": "burgers", + "variant": "Euler-PredOnly", + "status": "COMPLETED", + "params": 487623, + "best_val_rmse": 0.16929015758444876, + "train_gpu_seconds": 43.14570364600013, + "peak_vram_bytes": 1563788288, + "rmse": 0.1499707457332522, + "mae": 0.08726799115538597, + "relative_l2": 0.2865189462900162, + "lead_rmse": [ + 0.09599953889846802, + 0.09610644727945328, + 0.10337240993976593, + 0.11455164849758148, + 0.1270807981491089, + 0.13948604464530945 + ], + "rollout_growth": 1.4529865980148315, + "sync_gain_mean": -0.4409240857572423, + "sync_gain_last": -0.5740999125248853, + "sync_by_lead": [ + -0.3580029613374607, + -0.37090407033762685, + -0.39907393220142917, + -0.44242588611728373, + -0.5010377520247675, + -0.5740999125248853 + ], + "observed_state_anchor_decode_rmse": 0.1221889965236187, + "dynamic_final_decode_rmse": 0.18335384875535965, + "anchor_to_dynamic_decode_ratio": 0.6664108626737892, + "observed_final_relative_speed": 0.12039395794272423, + "dynamic_final_relative_speed": 0.1440921425819397, + "final_step_norm_ratio_dyn_over_obs": 65.94201564788818, + "total_delta_cos": 0.0031906842486932874 + }, + { + "seed": 17, + "task": "burgers", + "variant": "Selected-Semantic", + "status": "COMPLETED", + "params": 487623, + "best_val_rmse": 0.18250181256008158, + "train_gpu_seconds": 44.29690304900032, + "peak_vram_bytes": 2006566400, + "rmse": 0.15647177752172767, + "mae": 0.10491807758808136, + "relative_l2": 0.3548569530248642, + "lead_rmse": [ + 0.11015808582305908, + 0.11108524352312088, + 0.1191612184047699, + 0.1306139975786209, + 0.14290720224380493, + 0.15473243594169617 + ], + "rollout_growth": 1.4046398401260376, + "sync_gain_mean": -0.12573116279327512, + "sync_gain_last": -0.15924760532957932, + "sync_by_lead": [ + -0.1056888055220038, + -0.10834126304209081, + -0.11499442816839558, + -0.12565270908051412, + -0.14046216561706695, + -0.15924760532957932 + ], + "observed_state_anchor_decode_rmse": 0.13084949180483818, + "dynamic_final_decode_rmse": 0.19122642278671265, + "anchor_to_dynamic_decode_ratio": 0.684264705148949, + "observed_final_relative_speed": 0.11984247714281082, + "dynamic_final_relative_speed": 0.07866193354129791, + "final_step_norm_ratio_dyn_over_obs": 31.73400115966797, + "total_delta_cos": 0.007208673050627112 + }, + { + "seed": 17, + "task": "burgers", + "variant": "BlackboxCore", + "status": "COMPLETED", + "params": 453112, + "best_val_rmse": 0.16309536832392837, + "train_gpu_seconds": 27.15576391200011, + "peak_vram_bytes": 1118245888, + "rmse": 0.1397462715558321, + "mae": 0.0734796542674303, + "relative_l2": 0.16401401162147522, + "lead_rmse": [ + 0.07430826872587204, + 0.07780992984771729, + 0.08881807327270508, + 0.10271594673395157, + 0.11718272417783737, + 0.13129420578479767 + ], + "rollout_growth": 1.76688551902771 + }, + { + "seed": 17, + "task": "diff_react_2d", + "variant": "Euler-PredOnly", + "status": "COMPLETED", + "params": 503232, + "best_val_rmse": 0.015477659191146874, + "train_gpu_seconds": 118.67044920399985, + "peak_vram_bytes": 4624111616, + "rmse": 0.015690370910899868, + "mae": 0.010047867777757347, + "relative_l2": 0.20934375934302807, + "lead_rmse": [ + 0.018176347017288208, + 0.015775147825479507, + 0.014445261098444462, + 0.013992909342050552, + 0.014225475490093231, + 0.014895261265337467 + ], + "rollout_growth": 0.8194859623908997, + "sync_gain_mean": -0.1565456117262294, + "sync_gain_last": -0.32637512231158605, + "sync_by_lead": [ + -0.015206586367869963, + -0.054859013748787176, + -0.11206848249020489, + -0.17923345988685693, + -0.25153100555207153, + -0.32637512231158605 + ], + "observed_state_anchor_decode_rmse": 0.0218083958607167, + "dynamic_final_decode_rmse": 0.015488087083213031, + "anchor_to_dynamic_decode_ratio": 1.408075493348305, + "observed_final_relative_speed": 0.08648122288286686, + "dynamic_final_relative_speed": 0.06427163444459438, + "final_step_norm_ratio_dyn_over_obs": 1.5621269196271896, + "total_delta_cos": 0.04081425163894892 + }, + { + "seed": 17, + "task": "diff_react_2d", + "variant": "Selected-Semantic", + "status": "COMPLETED", + "params": 503232, + "best_val_rmse": 0.023564698687693557, + "train_gpu_seconds": 129.34806594699967, + "peak_vram_bytes": 5755017728, + "rmse": 0.024234290908566356, + "mae": 0.017567915376275778, + "relative_l2": 0.32646066695451736, + "lead_rmse": [ + 0.027032077312469482, + 0.024779746308922768, + 0.023439742624759674, + 0.022729763761162758, + 0.022464416921138763, + 0.022511128336191177 + ], + "rollout_growth": 0.8327561616897583, + "sync_gain_mean": 0.02616371663746418, + "sync_gain_last": 0.021482850981150256, + "sync_by_lead": [ + 0.02087612975044929, + 0.030321727276382365, + 0.030959697304636356, + 0.02837478747769486, + 0.02496710703447193, + 0.021482850981150256 + ], + "observed_state_anchor_decode_rmse": 0.037699146661907434, + "dynamic_final_decode_rmse": 0.02298241131938994, + "anchor_to_dynamic_decode_ratio": 1.6403477484584565, + "observed_final_relative_speed": 0.20106762647628784, + "dynamic_final_relative_speed": 0.030714584281668067, + "final_step_norm_ratio_dyn_over_obs": 0.7605674490332603, + "total_delta_cos": 0.10334006231278181 + }, + { + "seed": 17, + "task": "diff_react_2d", + "variant": "BlackboxCore", + "status": "COMPLETED", + "params": 489547, + "best_val_rmse": 0.014972193764509258, + "train_gpu_seconds": 67.97902066500046, + "peak_vram_bytes": 2657754112, + "rmse": 0.015147828835960078, + "mae": 0.00816565949935466, + "relative_l2": 0.2021583430469036, + "lead_rmse": [ + 0.016720399260520935, + 0.014713664539158344, + 0.013908294029533863, + 0.013959156349301338, + 0.014526134356856346, + 0.0153517946600914 + ], + "rollout_growth": 0.918147623538971 + }, + { + "seed": 17, + "task": "swe_2d", + "variant": "Euler-PredOnly", + "status": "COMPLETED", + "params": 499051, + "best_val_rmse": 0.030553254433612582, + "train_gpu_seconds": 117.41366703899985, + "peak_vram_bytes": 4613837312, + "rmse": 0.0300979775016558, + "mae": 0.02053888887166977, + "relative_l2": 0.02774921990931034, + "lead_rmse": [ + 0.024405453354120255, + 0.02442908100783825, + 0.026105394586920738, + 0.028947733342647552, + 0.032423362135887146, + 0.036188267171382904 + ], + "rollout_growth": 1.4827942848205566, + "sync_gain_mean": -1.237389608810169, + "sync_gain_last": -1.193995659428481, + "sync_by_lead": [ + -1.349951113809959, + -1.2717753895652786, + -1.2228632037144291, + -1.1968520863295724, + -1.1889002000132958, + -1.193995659428481 + ], + "observed_state_anchor_decode_rmse": 0.025448665488511324, + "dynamic_final_decode_rmse": 0.03645177627913654, + "anchor_to_dynamic_decode_ratio": 0.6981461011291532, + "observed_final_relative_speed": 0.06586706917732954, + "dynamic_final_relative_speed": 0.07336996961385012, + "final_step_norm_ratio_dyn_over_obs": 1.1661478579044342, + "total_delta_cos": 0.0020579295087372884 + }, + { + "seed": 17, + "task": "swe_2d", + "variant": "Selected-Semantic", + "status": "COMPLETED", + "params": 499051, + "best_val_rmse": 0.03384947173505952, + "train_gpu_seconds": 127.26132532700012, + "peak_vram_bytes": 5743170560, + "rmse": 0.03352869033183614, + "mae": 0.020951375481672585, + "relative_l2": 0.03049514815211296, + "lead_rmse": [ + 0.03098200261592865, + 0.029929963871836662, + 0.03005235828459263, + 0.03127375617623329, + 0.0333562046289444, + 0.0360197015106678 + ], + "rollout_growth": 1.1626008749008179, + "sync_gain_mean": -0.16154888686381794, + "sync_gain_last": -0.15740340526959307, + "sync_by_lead": [ + -0.17472746957471993, + -0.16481043275599533, + -0.15936987825335444, + -0.1567169150481083, + -0.15626522028113657, + -0.15740340526959304 + ], + "observed_state_anchor_decode_rmse": 0.03117333445698023, + "dynamic_final_decode_rmse": 0.03645847551524639, + "anchor_to_dynamic_decode_ratio": 0.8550366963079409, + "observed_final_relative_speed": 0.035740064922720194, + "dynamic_final_relative_speed": 0.018199395155534148, + "final_step_norm_ratio_dyn_over_obs": 0.5232475399971008, + "total_delta_cos": 0.01292537001427263 + }, + { + "seed": 17, + "task": "swe_2d", + "variant": "BlackboxCore", + "status": "COMPLETED", + "params": 485366, + "best_val_rmse": 0.0313635059041942, + "train_gpu_seconds": 66.38894155799971, + "peak_vram_bytes": 2649445376, + "rmse": 0.030877023194201453, + "mae": 0.02096370968502015, + "relative_l2": 0.0286776686552912, + "lead_rmse": [ + 0.023713601753115654, + 0.02416008710861206, + 0.02662566676735878, + 0.03015890158712864, + 0.034175775945186615, + 0.03843476623296738 + ], + "rollout_growth": 1.620789885520935 + }, + { + "seed": 41, + "task": "burgers", + "variant": "Euler-PredOnly", + "status": "COMPLETED", + "params": 487623, + "best_val_rmse": 0.1721252007465951, + "train_gpu_seconds": 40.4097172970005, + "peak_vram_bytes": 1563788288, + "rmse": 0.14676666715855638, + "mae": 0.08096333965659142, + "relative_l2": 0.23263141512870789, + "lead_rmse": [ + 0.08295473456382751, + 0.08835357427597046, + 0.09954032301902771, + 0.11304094642400742, + 0.1267579346895218, + 0.13963700830936432 + ], + "rollout_growth": 1.6832915544509888, + "sync_gain_mean": -0.2095730399621513, + "sync_gain_last": -0.2686786333317809, + "sync_by_lead": [ + -0.1692592770469858, + -0.1778274553229196, + -0.19232597559541653, + -0.21202648508863312, + -0.23732041338717172, + -0.2686786333317809 + ], + "observed_state_anchor_decode_rmse": 0.10160784050822258, + "dynamic_final_decode_rmse": 0.19034875184297562, + "anchor_to_dynamic_decode_ratio": 0.5337983019297228, + "observed_final_relative_speed": 0.13284413516521454, + "dynamic_final_relative_speed": 0.10681566596031189, + "final_step_norm_ratio_dyn_over_obs": 49.09364128112793, + "total_delta_cos": 0.0003297128132544458 + }, + { + "seed": 41, + "task": "burgers", + "variant": "Selected-Semantic", + "status": "COMPLETED", + "params": 487623, + "best_val_rmse": 0.16805789489295775, + "train_gpu_seconds": 44.185808762000306, + "peak_vram_bytes": 2006566400, + "rmse": 0.14398556874898574, + "mae": 0.07778021320700645, + "relative_l2": 0.1751851886510849, + "lead_rmse": [ + 0.08438622951507568, + 0.0860808789730072, + 0.09425514936447144, + 0.10573302209377289, + 0.11818395555019379, + 0.1302042156457901 + ], + "rollout_growth": 1.542955756187439, + "sync_gain_mean": -0.11576000162579253, + "sync_gain_last": -0.14865607875214965, + "sync_by_lead": [ + -0.094077872638196, + -0.09836014546716651, + -0.10598118542717046, + -0.11667929629613469, + -0.130805431173938, + -0.14865607875214965 + ], + "observed_state_anchor_decode_rmse": 0.11146904155611992, + "dynamic_final_decode_rmse": 0.18261826038360596, + "anchor_to_dynamic_decode_ratio": 0.610393732379058, + "observed_final_relative_speed": 0.12241233512759209, + "dynamic_final_relative_speed": 0.07542578503489494, + "final_step_norm_ratio_dyn_over_obs": 32.996474266052246, + "total_delta_cos": 0.004520793678238988 + }, + { + "seed": 41, + "task": "burgers", + "variant": "BlackboxCore", + "status": "COMPLETED", + "params": 453112, + "best_val_rmse": 0.1624037729362137, + "train_gpu_seconds": 27.496437993000654, + "peak_vram_bytes": 1118245888, + "rmse": 0.12911317934642702, + "mae": 0.07789885997772217, + "relative_l2": 0.2890360802412033, + "lead_rmse": [ + 0.06444382667541504, + 0.07250232994556427, + 0.08732233196496964, + 0.10307340323925018, + 0.11757981777191162, + 0.13012836873531342 + ], + "rollout_growth": 2.0192527770996094 + }, + { + "seed": 41, + "task": "diff_react_2d", + "variant": "Euler-PredOnly", + "status": "COMPLETED", + "params": 503232, + "best_val_rmse": 0.01952723763647711, + "train_gpu_seconds": 118.42930230799993, + "peak_vram_bytes": 4624111616, + "rmse": 0.019729806024337822, + "mae": 0.013998490176163614, + "relative_l2": 0.2738202214241028, + "lead_rmse": [ + 0.022609751671552658, + 0.02031121402978897, + 0.0189774502068758, + 0.01833718828856945, + 0.018195293843746185, + 0.01839195005595684 + ], + "rollout_growth": 0.8134521245956421, + "sync_gain_mean": -0.26180370041134876, + "sync_gain_last": -0.557498633396384, + "sync_by_lead": [ + -0.026905110474056682, + -0.08931417999458606, + -0.18130343523292683, + -0.2943707055893759, + -0.4214301377807628, + -0.557498633396384 + ], + "observed_state_anchor_decode_rmse": 0.023791946936398745, + "dynamic_final_decode_rmse": 0.018723343033343554, + "anchor_to_dynamic_decode_ratio": 1.2707104118120756, + "observed_final_relative_speed": 0.09296963829547167, + "dynamic_final_relative_speed": 0.07836077362298965, + "final_step_norm_ratio_dyn_over_obs": 1.65946826338768, + "total_delta_cos": -0.04880017600953579 + }, + { + "seed": 41, + "task": "diff_react_2d", + "variant": "Selected-Semantic", + "status": "COMPLETED", + "params": 503232, + "best_val_rmse": 0.017461935070742927, + "train_gpu_seconds": 129.26759447099994, + "peak_vram_bytes": 5755017728, + "rmse": 0.0176343011928536, + "mae": 0.012073409394361079, + "relative_l2": 0.23316538706421852, + "lead_rmse": [ + 0.020160431042313576, + 0.017715029418468475, + 0.016392845660448074, + 0.015970760956406593, + 0.016208410263061523, + 0.01684470660984516 + ], + "rollout_growth": 0.835533082485199, + "sync_gain_mean": 0.03330218388726496, + "sync_gain_last": 0.029623088325610523, + "sync_by_lead": [ + 0.028757120109587215, + 0.03770311643636633, + 0.037102021049736436, + 0.03461231536840559, + 0.03201544203388368, + 0.029623088325610523 + ], + "observed_state_anchor_decode_rmse": 0.02103782002814114, + "dynamic_final_decode_rmse": 0.01733495807275176, + "anchor_to_dynamic_decode_ratio": 1.2136066288622749, + "observed_final_relative_speed": 0.1451829243451357, + "dynamic_final_relative_speed": 0.016898056026548147, + "final_step_norm_ratio_dyn_over_obs": 0.38582880422472954, + "total_delta_cos": 0.1101990481838584 + }, + { + "seed": 41, + "task": "diff_react_2d", + "variant": "BlackboxCore", + "status": "COMPLETED", + "params": 489547, + "best_val_rmse": 0.014911862215968706, + "train_gpu_seconds": 67.97330821500054, + "peak_vram_bytes": 2657754112, + "rmse": 0.01507748176105691, + "mae": 0.010421790997497737, + "relative_l2": 0.2096279338002205, + "lead_rmse": [ + 0.017527390271425247, + 0.01527839619666338, + 0.014171184971928596, + 0.013868428766727448, + 0.014058208093047142, + 0.014506678096950054 + ], + "rollout_growth": 0.8276576399803162 + }, + { + "seed": 41, + "task": "swe_2d", + "variant": "Euler-PredOnly", + "status": "COMPLETED", + "params": 499051, + "best_val_rmse": 0.034153520197926016, + "train_gpu_seconds": 117.16719404899959, + "peak_vram_bytes": 4613837312, + "rmse": 0.033510004193101586, + "mae": 0.022667597280815244, + "relative_l2": 0.0314622528385371, + "lead_rmse": [ + 0.02431523986160755, + 0.026161689311265945, + 0.02945145219564438, + 0.033506982028484344, + 0.03788837417960167, + 0.042351339012384415 + ], + "rollout_growth": 1.7417610883712769, + "sync_gain_mean": -1.0008490668432712, + "sync_gain_last": -0.9911075571970146, + "sync_by_lead": [ + -1.0554453144152456, + -1.0150189938150875, + -0.9882350095721797, + -0.9766363311397538, + -0.9786511949203475, + -0.9911075571970146 + ], + "observed_state_anchor_decode_rmse": 0.025645729154348373, + "dynamic_final_decode_rmse": 0.04267868306487799, + "anchor_to_dynamic_decode_ratio": 0.6009025422683035, + "observed_final_relative_speed": 0.06766525888815522, + "dynamic_final_relative_speed": 0.06914292741566896, + "final_step_norm_ratio_dyn_over_obs": 1.0716578513383865, + "total_delta_cos": 0.010027030715718865 + }, + { + "seed": 41, + "task": "swe_2d", + "variant": "Selected-Semantic", + "status": "COMPLETED", + "params": 499051, + "best_val_rmse": 0.0364328846879714, + "train_gpu_seconds": 127.30498157800048, + "peak_vram_bytes": 5743170560, + "rmse": 0.03598219034618389, + "mae": 0.024474860168993473, + "relative_l2": 0.03333190130069852, + "lead_rmse": [ + 0.026533309370279312, + 0.028369517996907234, + 0.031566549092531204, + 0.035528503358364105, + 0.039844028651714325, + 0.04427105933427811 + ], + "rollout_growth": 1.668508768081665, + "sync_gain_mean": -0.07996828240250468, + "sync_gain_last": -0.07890745206604394, + "sync_by_lead": [ + -0.08466605045077881, + -0.08122814440510673, + -0.07899007977604265, + -0.0779774147394427, + -0.07804055297761331, + -0.07890745206604392 + ], + "observed_state_anchor_decode_rmse": 0.027610744815319777, + "dynamic_final_decode_rmse": 0.044842406176030636, + "anchor_to_dynamic_decode_ratio": 0.61572844032795, + "observed_final_relative_speed": 0.056353189051151276, + "dynamic_final_relative_speed": 0.017564741661772132, + "final_step_norm_ratio_dyn_over_obs": 0.32143574580550194, + "total_delta_cos": 0.004415164119563997 + }, + { + "seed": 41, + "task": "swe_2d", + "variant": "BlackboxCore", + "status": "COMPLETED", + "params": 485366, + "best_val_rmse": 0.03425161784189264, + "train_gpu_seconds": 66.77596297899981, + "peak_vram_bytes": 2649445376, + "rmse": 0.03348841982862127, + "mae": 0.022770278272219002, + "relative_l2": 0.03168133506551385, + "lead_rmse": [ + 0.028089020401239395, + 0.028269369155168533, + 0.03020133636891842, + 0.033125609159469604, + 0.03662499785423279, + 0.0404689684510231 + ], + "rollout_growth": 1.4407397508621216 + } + ], + "branch_audit": [ + { + "seed": 17, + "task": "burgers", + "skew_delta_cos": 0.0013656560331583023, + "skew_norm_ratio": 152.73060607910156, + "flux_delta_cos": 0.0006985156069276854, + "flux_norm_ratio": 25.720701813697815, + "local_delta_cos": 0.10754729062318802, + "local_norm_ratio": 7.685434237122536, + "total_delta_cos": 0.007208673050627112, + "total_norm_ratio": 153.4901294708252, + "skew_budget_fraction": 0.8215492069721222, + "flux_budget_fraction": 0.13534660637378693, + "local_budget_fraction": 0.04310414753854275 + }, + { + "seed": 17, + "task": "diff_react_2d", + "skew_delta_cos": 0.10441821720451117, + "skew_norm_ratio": 0.7340127602219582, + "flux_delta_cos": -0.1979677937924862, + "flux_norm_ratio": 0.00845514377579093, + "local_delta_cos": 0.23483028449118137, + "local_norm_ratio": 0.010007365723140538, + "total_delta_cos": 0.10334006231278181, + "total_norm_ratio": 0.7314123287796974, + "skew_budget_fraction": 0.9649790599942207, + "flux_budget_fraction": 0.018831515684723854, + "local_budget_fraction": 0.016189421294257045 + }, + { + "seed": 17, + "task": "swe_2d", + "skew_delta_cos": 0.012429351103492081, + "skew_norm_ratio": 0.5371080599725246, + "flux_delta_cos": 0.05013041663914919, + "flux_norm_ratio": 6.924370097749488e-06, + "local_delta_cos": 0.005590689135715365, + "local_norm_ratio": 0.05421942984685302, + "total_delta_cos": 0.01292537001427263, + "total_norm_ratio": 0.5389549434185028, + "skew_budget_fraction": 0.9087906628847122, + "flux_budget_fraction": 1.1631023426161846e-05, + "local_budget_fraction": 0.09119770769029856 + }, + { + "seed": 41, + "task": "burgers", + "skew_delta_cos": 0.0024867922766134143, + "skew_norm_ratio": 188.13918209075928, + "flux_delta_cos": 0.00041138702363241464, + "flux_norm_ratio": 6.573885455727577, + "local_delta_cos": 0.035519775934517384, + "local_norm_ratio": 10.169237285852432, + "total_delta_cos": 0.004520793678238988, + "total_norm_ratio": 190.27593803405762, + "skew_budget_fraction": 0.9073803424835205, + "flux_budget_fraction": 0.035998234525322914, + "local_budget_fraction": 0.05662139877676964 + }, + { + "seed": 41, + "task": "diff_react_2d", + "skew_delta_cos": 0.11288194451481104, + "skew_norm_ratio": 0.3589554876089096, + "flux_delta_cos": -0.20456264540553093, + "flux_norm_ratio": 0.014611530466936529, + "local_delta_cos": 0.3022610992193222, + "local_norm_ratio": 0.009813539567403495, + "total_delta_cos": 0.1101990481838584, + "total_norm_ratio": 0.3558346517384052, + "skew_budget_fraction": 0.9163949191570282, + "flux_budget_fraction": 0.0546077573671937, + "local_budget_fraction": 0.028997298562899232 + }, + { + "seed": 41, + "task": "swe_2d", + "skew_delta_cos": 0.0016319219721481204, + "skew_norm_ratio": 0.33294806629419327, + "flux_delta_cos": 0.1472770031541586, + "flux_norm_ratio": 0.0056970797595568, + "local_delta_cos": 0.0007507414193241857, + "local_norm_ratio": 0.11598197650164366, + "total_delta_cos": 0.004415164119563997, + "total_norm_ratio": 0.32173579186201096, + "skew_budget_fraction": 0.7355489879846573, + "flux_budget_fraction": 0.012419753475114703, + "local_budget_fraction": 0.2520312611013651 + } + ], + "gate": { + "engineering_neuraloperator_3of3": true, + "selected_candidate": "C1_Euler_Sync", + "positive_sync_tasks": 1, + "anchor_good_tasks": 2, + "step_scale_good_tasks": 2, + "selected_vs_predonly_rmse_ratio": 1.0957973990673535, + "selected_vs_blackbox_rmse_ratio": 1.1942276568119583, + "alignment_positive_tasks": 3, + "science_gates": { + "confirmation_complete": true, + "positive_sync_2of3": false, + "anchor_decode_2of3": true, + "step_scale_2of3": true, + "prediction_cost_le_1p05": false, + "structured_vs_blackbox_le_1p15": false, + "dynamics_alignment_2of3": true + }, + "verdict": "CORE_SEMANTICS_REVIEW_REQUIRED" + }, + "verdict": "CORE_SEMANTICS_REVIEW_REQUIRED", + "finished_at": "2026-09-27 15:06:22" +} \ No newline at end of file diff --git a/CIDM_Foundation_A1_R1_R2_FIX1_RESULTS.zip b/CIDM_Foundation_A1_R1_R2_FIX1_RESULTS.zip new file mode 100644 index 0000000000000000000000000000000000000000..b6bc4125aa1d63b7c7f2fe4ac186fb941a2ac641 --- /dev/null +++ b/CIDM_Foundation_A1_R1_R2_FIX1_RESULTS.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:02ad1c433ff552c0b963f4e8694cb1c07969d0f6cca9be62c23b6eb5257a9081 +size 39081 diff --git a/CIDM_Foundation_A1_R1_R2_FIX1_RESULTS.zip.sha256 b/CIDM_Foundation_A1_R1_R2_FIX1_RESULTS.zip.sha256 new file mode 100644 index 0000000000000000000000000000000000000000..7907e1d77cc64d1313244db0163066be5366dfaf --- /dev/null +++ b/CIDM_Foundation_A1_R1_R2_FIX1_RESULTS.zip.sha256 @@ -0,0 +1 @@ +02ad1c433ff552c0b963f4e8694cb1c07969d0f6cca9be62c23b6eb5257a9081 diff --git a/FIX1_numerical_preflight.csv b/FIX1_numerical_preflight.csv new file mode 100644 index 0000000000000000000000000000000000000000..79270f50c614194d416bd8816fb98a8f8503a666 --- /dev/null +++ b/FIX1_numerical_preflight.csv @@ -0,0 +1,16 @@ +candidate,task,pass,cayley_orthogonality_maxerr,error +C0_Euler_PredOnly,burgers,True,, +C0_Euler_PredOnly,diff_react_2d,True,, +C0_Euler_PredOnly,swe_2d,True,, +C1_Euler_Sync,burgers,True,, +C1_Euler_Sync,diff_react_2d,True,, +C1_Euler_Sync,swe_2d,True,, +C2_Euler_AnchorSync,burgers,True,, +C2_Euler_AnchorSync,diff_react_2d,True,, +C2_Euler_AnchorSync,swe_2d,True,, +C3_Euler_AnchorSyncSpeed,burgers,True,, +C3_Euler_AnchorSyncSpeed,diff_react_2d,True,, +C3_Euler_AnchorSyncSpeed,swe_2d,True,, +C4_Cayley_AnchorSyncSpeed,burgers,True,1.7881393432617188e-07, +C4_Cayley_AnchorSyncSpeed,diff_react_2d,True,1.7881393432617188e-07, +C4_Cayley_AnchorSyncSpeed,swe_2d,True,1.7881393432617188e-07, diff --git a/checkpoints/BlackboxCore__burgers__s17.pt b/checkpoints/BlackboxCore__burgers__s17.pt new file mode 100644 index 0000000000000000000000000000000000000000..06a9c729fe0ec7e0e34f999f1626991216cbb408 --- /dev/null +++ b/checkpoints/BlackboxCore__burgers__s17.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:77f92d093aed23311989985476869b55f45c0c994405c65920ac529443c4fa8e +size 1833669 diff --git a/checkpoints/BlackboxCore__burgers__s41.pt b/checkpoints/BlackboxCore__burgers__s41.pt new file mode 100644 index 0000000000000000000000000000000000000000..0b91f7c879b63918295f6d6af8f832d6e5e31ab1 --- /dev/null +++ b/checkpoints/BlackboxCore__burgers__s41.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e17bc0a93ac31f5eeea78064bd635c5b6d93eca6e5ffec686b3048c0dd0bf56a +size 1833669 diff --git a/checkpoints/BlackboxCore__diff_react_2d__s17.pt b/checkpoints/BlackboxCore__diff_react_2d__s17.pt new file mode 100644 index 0000000000000000000000000000000000000000..aab4159a1671fae3c5f3665fdaac1c11ee260897 --- /dev/null +++ b/checkpoints/BlackboxCore__diff_react_2d__s17.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3e89a2318b665aad9e3ad2a20149fc8a08ea186e3218621167e23224a16d4f81 +size 1979019 diff --git a/checkpoints/BlackboxCore__diff_react_2d__s41.pt b/checkpoints/BlackboxCore__diff_react_2d__s41.pt new file mode 100644 index 0000000000000000000000000000000000000000..f2d69c184046950688422679a7d262c0af1b047e --- /dev/null +++ b/checkpoints/BlackboxCore__diff_react_2d__s41.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b936685c169e5e852404045cee14cca0280f2518bbb290924e60c99bbdec1a4f +size 1979019 diff --git a/checkpoints/BlackboxCore__swe_2d__s17.pt b/checkpoints/BlackboxCore__swe_2d__s17.pt new file mode 100644 index 0000000000000000000000000000000000000000..a246ec1c9480c3e741e6bbbaa086451f3121945f --- /dev/null +++ b/checkpoints/BlackboxCore__swe_2d__s17.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fb0e9c1bfa41cd414c3b1e87471d503ad78f35ce00ad8c3eeff7e537f8704691 +size 1961796 diff --git a/checkpoints/BlackboxCore__swe_2d__s41.pt b/checkpoints/BlackboxCore__swe_2d__s41.pt new file mode 100644 index 0000000000000000000000000000000000000000..f0ffa3368b06f9b14f8fdecc625696c49e84b9a3 --- /dev/null +++ b/checkpoints/BlackboxCore__swe_2d__s41.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0a1ec0a3c0f6ecb85a421df6778bc93496a0b8f690a600d46aaec4a25b832234 +size 1961796 diff --git a/checkpoints/Euler-PredOnly__burgers__s17.pt b/checkpoints/Euler-PredOnly__burgers__s17.pt new file mode 100644 index 0000000000000000000000000000000000000000..bc42f05993b7bbf31b15ecbaf2ff9d1fc682b6f5 --- /dev/null +++ b/checkpoints/Euler-PredOnly__burgers__s17.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4df2c8170ec86307b9fc5f08a01a92e409bb6e96444734bc95045f2df08feb93 +size 1974003 diff --git a/checkpoints/Euler-PredOnly__burgers__s41.pt b/checkpoints/Euler-PredOnly__burgers__s41.pt new file mode 100644 index 0000000000000000000000000000000000000000..8d0d27ed9d61c25a11c01f50237c78c23fd1fca3 --- /dev/null +++ b/checkpoints/Euler-PredOnly__burgers__s41.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4f2aa5bb9d42c65bdd3dd1a85462f7291fe2266b9342b725d588512b6ef343c3 +size 1974003 diff --git a/checkpoints/Euler-PredOnly__diff_react_2d__s17.pt b/checkpoints/Euler-PredOnly__diff_react_2d__s17.pt new file mode 100644 index 0000000000000000000000000000000000000000..f9236abb0b0c147343a7aefdab55122ce6114ffd --- /dev/null +++ b/checkpoints/Euler-PredOnly__diff_react_2d__s17.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:84e862f858cb814627240c3bcb10ce3d0467037a0a1ad1edefda8f29ab428460 +size 2036189 diff --git a/checkpoints/Euler-PredOnly__diff_react_2d__s41.pt b/checkpoints/Euler-PredOnly__diff_react_2d__s41.pt new file mode 100644 index 0000000000000000000000000000000000000000..055c619dd845d496284d25b35db6c94a16b4b047 --- /dev/null +++ b/checkpoints/Euler-PredOnly__diff_react_2d__s41.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bd212800950f68798235174b3f1b6cdf7a59250a9abe1a37f36c4089b32f5e3e +size 2036189 diff --git a/checkpoints/Euler-PredOnly__swe_2d__s17.pt b/checkpoints/Euler-PredOnly__swe_2d__s17.pt new file mode 100644 index 0000000000000000000000000000000000000000..6703e44620d8f8b065a8d1dbfa5adcfb4bd6f8b5 --- /dev/null +++ b/checkpoints/Euler-PredOnly__swe_2d__s17.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3aea520da044d2955ebd1bf9535386a56a4d13bafcf53166a0c5b6a1ee7d6792 +size 2018860 diff --git a/checkpoints/Euler-PredOnly__swe_2d__s41.pt b/checkpoints/Euler-PredOnly__swe_2d__s41.pt new file mode 100644 index 0000000000000000000000000000000000000000..00b6f3db82f0cc04bd0fa49d5352c136f6d8c9b5 --- /dev/null +++ b/checkpoints/Euler-PredOnly__swe_2d__s41.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:19716bf9d68ada0a87bad3f8a9bb6143006ee581cb9c359ba7211ae8289ed80c +size 2018860 diff --git a/checkpoints/Selected-Semantic__burgers__s17.pt b/checkpoints/Selected-Semantic__burgers__s17.pt new file mode 100644 index 0000000000000000000000000000000000000000..e8efac7665557e9b4d4a92142ad1a62af59dd2b8 --- /dev/null +++ b/checkpoints/Selected-Semantic__burgers__s17.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e4876f49b01b39c1371d89dbecb5a1d309daf17365266b90056f776f0219289a +size 1974216 diff --git a/checkpoints/Selected-Semantic__burgers__s41.pt b/checkpoints/Selected-Semantic__burgers__s41.pt new file mode 100644 index 0000000000000000000000000000000000000000..11f06e3196e110cf284cdad7f0bef061576e187a --- /dev/null +++ b/checkpoints/Selected-Semantic__burgers__s41.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:065acbdd84a8d0fea0e68833784160cefb785e2ba3317e81c096e4941bca957b +size 1974216 diff --git a/checkpoints/Selected-Semantic__diff_react_2d__s17.pt b/checkpoints/Selected-Semantic__diff_react_2d__s17.pt new file mode 100644 index 0000000000000000000000000000000000000000..c05b82c720f857102aa16dbb26dbc8af591206da --- /dev/null +++ b/checkpoints/Selected-Semantic__diff_react_2d__s17.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b51dcdddc16127fe665d815eaf9319bb55b04d879d92034da6a64ec55b16e40a +size 2036402 diff --git a/checkpoints/Selected-Semantic__diff_react_2d__s41.pt b/checkpoints/Selected-Semantic__diff_react_2d__s41.pt new file mode 100644 index 0000000000000000000000000000000000000000..47fc1d3f131479fb2d65f41a9574f7bf9af05a02 --- /dev/null +++ b/checkpoints/Selected-Semantic__diff_react_2d__s41.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f0d2749e5065d8ff6d6ce83c7daa84427fae8df7fde338781c36870b0ee1a276 +size 2036402 diff --git a/checkpoints/Selected-Semantic__swe_2d__s17.pt b/checkpoints/Selected-Semantic__swe_2d__s17.pt new file mode 100644 index 0000000000000000000000000000000000000000..dd1c8271c1d5d96ebf191ff4962a8f8328636636 --- /dev/null +++ b/checkpoints/Selected-Semantic__swe_2d__s17.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9982855f28e210f88853de2babb2674c6a64fcac3c79378acb34e1b2a251d945 +size 2019073 diff --git a/checkpoints/Selected-Semantic__swe_2d__s41.pt b/checkpoints/Selected-Semantic__swe_2d__s41.pt new file mode 100644 index 0000000000000000000000000000000000000000..de7f9334508475e48528761ddcfc80bb5e4e7b71 --- /dev/null +++ b/checkpoints/Selected-Semantic__swe_2d__s41.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e45a7bb00f03d1b989b84d75d1d66198bb84289ad30fc300537a130777fc20a7 +size 2019073 diff --git a/checkpoints/neuralop_repair_burgers.pt b/checkpoints/neuralop_repair_burgers.pt new file mode 100644 index 0000000000000000000000000000000000000000..b4ffd47be6399faa6e02a2e3e004b48a1d3314a3 --- /dev/null +++ b/checkpoints/neuralop_repair_burgers.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b4ee7a9a0533d7dcf837651ee9ee4e2bb02aba94a8433d1e58bf17e868b086d7 +size 3562635 diff --git a/checkpoints/neuralop_repair_diff_react_2d.pt b/checkpoints/neuralop_repair_diff_react_2d.pt new file mode 100644 index 0000000000000000000000000000000000000000..bb798eff1230459eaba4547071c878833e6ff02a --- /dev/null +++ b/checkpoints/neuralop_repair_diff_react_2d.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5d4c46a72977115c898a3c94d499be248f236fe7c9f1b111e6c0c2aeae520ed6 +size 3801375 diff --git a/checkpoints/neuralop_repair_swe_2d.pt b/checkpoints/neuralop_repair_swe_2d.pt new file mode 100644 index 0000000000000000000000000000000000000000..45bd341c85f30ce5a2b2755cfcac5327c3963f55 --- /dev/null +++ b/checkpoints/neuralop_repair_swe_2d.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0f61959a04f01e79d411e734f7a9d65a15ac44f79cc4bd57ea674b7366d05235 +size 3798301 diff --git a/confirm__Euler-PredOnly__burgers__s17_history.csv b/confirm__Euler-PredOnly__burgers__s17_history.csv new file mode 100644 index 0000000000000000000000000000000000000000..50f4d1a58e519963e4027cbb4e197c11c309b74a --- /dev/null +++ b/confirm__Euler-PredOnly__burgers__s17_history.csv @@ -0,0 +1,6 @@ +step,pred,anchor,sync,speed,anchor_weight,sync_weight,speed_weight,val_rmse,val_sync_last,val_obs_speed,val_dyn_speed,val_step_ratio +1,0.2631424367427826,0.0,0.0,0.0,0.0,0.0,0.0,0.640483049622541,-0.07874431738503178,0.16199880093336105,0.06646031141281128,82.29803848266602 +60,0.05081118270754814,0.0,0.0,0.0,0.0,0.0,0.0,0.19576837504569325,-0.6654241076288994,0.12337533012032509,0.1565009206533432,225.83103942871094 +120,0.023057814687490463,0.0,0.0,0.0,0.0,0.0,0.0,0.1967288400018195,-0.36051847885111943,0.14658500999212265,0.137370765209198,183.91159057617188 +180,0.018342282623052597,0.0,0.0,0.0,0.0,0.0,0.0,0.16929015758444876,-0.3841970489797933,0.15026944130659103,0.14838587492704391,211.31659698486328 +240,0.015707185491919518,0.0,0.0,0.0,0.0,0.0,0.0,0.21023324562826917,-0.41840266093854916,0.15781307965517044,0.16505858302116394,239.3940887451172 diff --git a/confirm__Euler-PredOnly__burgers__s41_history.csv b/confirm__Euler-PredOnly__burgers__s41_history.csv new file mode 100644 index 0000000000000000000000000000000000000000..e0c220961e0f11cf5cecdd6edba05688b7da90e9 --- /dev/null +++ b/confirm__Euler-PredOnly__burgers__s41_history.csv @@ -0,0 +1,6 @@ +step,pred,anchor,sync,speed,anchor_weight,sync_weight,speed_weight,val_rmse,val_sync_last,val_obs_speed,val_dyn_speed,val_step_ratio +1,0.767362117767334,0.0,0.0,0.0,0.0,0.0,0.0,0.7412754679095305,-0.0869655363734623,0.1689341515302658,0.07258455455303192,90.49239921569824 +60,0.04219018667936325,0.0,0.0,0.0,0.0,0.0,0.0,0.23521098216009487,-0.2841665803588652,0.12320900708436966,0.0960596576333046,144.3836326599121 +120,0.023421064019203186,0.0,0.0,0.0,0.0,0.0,0.0,0.1721252007465951,-0.22287449262069053,0.1558252051472664,0.10822226852178574,148.1230354309082 +180,0.027514707297086716,0.0,0.0,0.0,0.0,0.0,0.0,0.1859069166957028,-0.4653704145984795,0.13109856098890305,0.13271519541740417,203.8318328857422 +240,0.02914794534444809,0.0,0.0,0.0,0.0,0.0,0.0,0.17776795216821134,-0.4538896504817821,0.15603242069482803,0.16101248562335968,246.48082733154297 diff --git a/confirm__Euler-PredOnly__diff_react_2d__s17_history.csv b/confirm__Euler-PredOnly__diff_react_2d__s17_history.csv new file mode 100644 index 0000000000000000000000000000000000000000..6989eab28a49b3b1c479ae88936981811d3ef6cd --- /dev/null +++ b/confirm__Euler-PredOnly__diff_react_2d__s17_history.csv @@ -0,0 +1,6 @@ +step,pred,anchor,sync,speed,anchor_weight,sync_weight,speed_weight,val_rmse,val_sync_last,val_obs_speed,val_dyn_speed,val_step_ratio +1,0.10725043714046478,0.0,0.0,0.0,0.0,0.0,0.0,1.2162065681414564,-0.20606385355810386,0.1471483459075292,0.08913871645927429,2.8306159178415933 +60,0.0010252244537696242,0.0,0.0,0.0,0.0,0.0,0.0,0.027202113645526545,-0.062156652308227256,0.17181934912999472,0.06664069245258968,2.0932088692982993 +120,0.000582308042794466,0.0,0.0,0.0,0.0,0.0,0.0,0.02284360749003261,-0.08282422481472304,0.12882659832636514,0.06584833314021428,1.839210033416748 +180,0.0003976179286837578,0.0,0.0,0.0,0.0,0.0,0.0,0.018820644989109892,-0.2032402794726598,0.09947230666875839,0.0658985252181689,1.6903797785441081 +240,0.0004365575441624969,0.0,0.0,0.0,0.0,0.0,0.0,0.015477659191146874,-0.32801803111269007,0.08534024904171626,0.06436435629924138,1.614181121190389 diff --git a/confirm__Euler-PredOnly__diff_react_2d__s41_history.csv b/confirm__Euler-PredOnly__diff_react_2d__s41_history.csv new file mode 100644 index 0000000000000000000000000000000000000000..fcdae19bf8507d9881470e01178cbead5d6425a7 --- /dev/null +++ b/confirm__Euler-PredOnly__diff_react_2d__s41_history.csv @@ -0,0 +1,6 @@ +step,pred,anchor,sync,speed,anchor_weight,sync_weight,speed_weight,val_rmse,val_sync_last,val_obs_speed,val_dyn_speed,val_step_ratio +1,0.07799327373504639,0.0,0.0,0.0,0.0,0.0,0.0,1.0741065157433338,-0.2904601924422189,0.1286280949910482,0.09180084615945816,3.0100310643514 +60,0.0010377959115430713,0.0,0.0,0.0,0.0,0.0,0.0,0.029607760601339756,-0.29744000284678557,0.11836400876442592,0.07700031499067943,2.382461150487264 +120,0.0005313322180882096,0.0,0.0,0.0,0.0,0.0,0.0,0.0232176377566251,-0.3924416110793203,0.10121734937032063,0.07728699346383412,2.219682216644287 +180,0.0006083005573600531,0.0,0.0,0.0,0.0,0.0,0.0,0.021199202075250848,-0.45286979155136375,0.09654403477907181,0.07778661698102951,1.9963933229446411 +240,0.0003045783960260451,0.0,0.0,0.0,0.0,0.0,0.0,0.01952723763647711,-0.5620600988663133,0.09308323264122009,0.07858656843503316,1.6923590103785198 diff --git a/confirm__Euler-PredOnly__swe_2d__s17_history.csv b/confirm__Euler-PredOnly__swe_2d__s17_history.csv new file mode 100644 index 0000000000000000000000000000000000000000..11bddf84d7291267a600df0b077bd8635dd682b5 --- /dev/null +++ b/confirm__Euler-PredOnly__swe_2d__s17_history.csv @@ -0,0 +1,6 @@ +step,pred,anchor,sync,speed,anchor_weight,sync_weight,speed_weight,val_rmse,val_sync_last,val_obs_speed,val_dyn_speed,val_step_ratio +1,0.9216632843017578,0.0,0.0,0.0,0.0,0.0,0.0,0.862681409168029,-5.532513112037356,0.026904047777255375,0.06447849919398625,2.4854792753855386 +60,0.0017366254469379783,0.0,0.0,0.0,0.0,0.0,0.0,0.04730104860205146,-1.5069915798728342,0.0560407799979051,0.07196909934282303,1.342216968536377 +120,0.0017878466751426458,0.0,0.0,0.0,0.0,0.0,0.0,0.03318493183361494,-1.1837609141499792,0.06101600453257561,0.06887485335270564,1.1639744838078816 +180,0.0005506989546120167,0.0,0.0,0.0,0.0,0.0,0.0,0.044261683494830145,-0.7915610421854068,0.07560188074906667,0.06966519355773926,0.9466519753138224 +240,0.0014963013818487525,0.0,0.0,0.0,0.0,0.0,0.0,0.030553254433612582,-1.1348224388768349,0.0671454668045044,0.07337438563505809,1.1343863010406494 diff --git a/confirm__Euler-PredOnly__swe_2d__s41_history.csv b/confirm__Euler-PredOnly__swe_2d__s41_history.csv new file mode 100644 index 0000000000000000000000000000000000000000..092964be38989a27bb56a3aa17db0bb67d64a574 --- /dev/null +++ b/confirm__Euler-PredOnly__swe_2d__s41_history.csv @@ -0,0 +1,6 @@ +step,pred,anchor,sync,speed,anchor_weight,sync_weight,speed_weight,val_rmse,val_sync_last,val_obs_speed,val_dyn_speed,val_step_ratio +1,1.3209093809127808,0.0,0.0,0.0,0.0,0.0,0.0,0.6430175113844505,-3.5465455224663827,0.03417169054349264,0.06618446360031764,1.997111717859904 +60,0.00289023551158607,0.0,0.0,0.0,0.0,0.0,0.0,0.051339177669184145,-1.3244083608842254,0.05928716311852137,0.07139478623867035,1.2869151830673218 +120,0.0008220031741075218,0.0,0.0,0.0,0.0,0.0,0.0,0.034153520197926016,-0.9439157947277476,0.06893517822027206,0.06917013227939606,1.0442159175872803 +180,0.0012577485758811235,0.0,0.0,0.0,0.0,0.0,0.0,0.037772071055291484,-0.8690362986084148,0.07722119241952896,0.0748272289832433,1.004386266072591 +240,0.001619490678422153,0.0,0.0,0.0,0.0,0.0,0.0,0.03644739821031318,-1.0228446061410843,0.07607303063074748,0.08070370058218639,1.1088032325108845 diff --git a/confirm__Selected-Semantic__burgers__s17_history.csv b/confirm__Selected-Semantic__burgers__s17_history.csv new file mode 100644 index 0000000000000000000000000000000000000000..fcbd4b26b459dfb39e959db93af59425c63a26f9 --- /dev/null +++ b/confirm__Selected-Semantic__burgers__s17_history.csv @@ -0,0 +1,6 @@ +step,pred,anchor,sync,speed,anchor_weight,sync_weight,speed_weight,val_rmse,val_sync_last,val_obs_speed,val_dyn_speed,val_step_ratio +1,0.2631424367427826,0.0,0.0,0.0,0.0,0.0,0.0,0.6404830379897887,-0.07874436368874808,0.16199880093336105,0.06646031141281128,82.29824829101562 +60,0.050744496285915375,0.0,0.012330116704106331,0.0,0.0,0.03,0.0,0.19536305011809352,-0.4198048656830943,0.12284005433320999,0.12205184251070023,177.46109008789062 +120,0.01966874673962593,0.0,0.008640364743769169,0.0,0.0,0.05,0.0,0.23655302995046673,-0.13132585461077845,0.1358564756810665,0.07883210107684135,115.62363815307617 +180,0.02138449251651764,0.0,0.007958194240927696,0.0,0.0,0.05,0.0,0.18250181256008158,-0.11202428866427913,0.1446688137948513,0.07958041504025459,109.81110382080078 +240,0.01783638447523117,0.0,0.008553000167012215,0.0,0.0,0.05,0.0,0.22140420273377434,-0.12016561973738304,0.1388154923915863,0.08289329707622528,120.95183563232422 diff --git a/confirm__Selected-Semantic__burgers__s41_history.csv b/confirm__Selected-Semantic__burgers__s41_history.csv new file mode 100644 index 0000000000000000000000000000000000000000..0923ac71a45a565f7cba39c7da439044c4e55110 --- /dev/null +++ b/confirm__Selected-Semantic__burgers__s41_history.csv @@ -0,0 +1,6 @@ +step,pred,anchor,sync,speed,anchor_weight,sync_weight,speed_weight,val_rmse,val_sync_last,val_obs_speed,val_dyn_speed,val_step_ratio +1,0.767362117767334,0.0,0.0,0.0,0.0,0.0,0.0,0.7412754679095305,-0.08696553267496528,0.1689341515302658,0.07258455082774162,90.49237060546875 +60,0.041975341737270355,0.0,0.009842636995017529,0.0,0.0,0.03,0.0,0.2346131823177132,-0.2588335549174252,0.12244154885411263,0.0912700742483139,137.4370574951172 +120,0.01932619884610176,0.0,0.006635869853198528,0.0,0.0,0.05,0.0,0.16805789489295775,-0.11473281122909341,0.1460525095462799,0.07526963576674461,107.9207763671875 +180,0.02582181617617607,0.0,0.010574951767921448,0.0,0.0,0.05,0.0,0.18133969143091405,-0.12244848764623398,0.14074327796697617,0.07719647139310837,116.11490249633789 +240,0.049120258539915085,0.0,0.012521268799901009,0.0,0.0,0.05,0.0,0.16966077047390585,-0.12149564922220286,0.14849524945020676,0.08518410474061966,129.34009552001953 diff --git a/confirm__Selected-Semantic__diff_react_2d__s17_history.csv b/confirm__Selected-Semantic__diff_react_2d__s17_history.csv new file mode 100644 index 0000000000000000000000000000000000000000..919bb68569a139953f0e24801969422bcd4489d1 --- /dev/null +++ b/confirm__Selected-Semantic__diff_react_2d__s17_history.csv @@ -0,0 +1,6 @@ +step,pred,anchor,sync,speed,anchor_weight,sync_weight,speed_weight,val_rmse,val_sync_last,val_obs_speed,val_dyn_speed,val_step_ratio +1,0.10725043714046478,0.0,0.0,0.0,0.0,0.0,0.0,1.2162065620153748,-0.20606381257612819,0.1471483459075292,0.08913871894280116,2.8306162357330322 +60,0.0010512094013392925,0.0,0.007305804640054703,0.0,0.0,0.03,0.0,0.027378801009773846,0.015343852120017048,0.159020334482193,0.06181977937618891,1.9183450937271118 +120,0.0011461663525551558,0.0,0.005818591918796301,0.0,0.0,0.05,0.0,0.02582161436044284,0.07007820288908427,0.16192241509755453,0.03551946332057317,1.0252039035161336 +180,0.0023287213407456875,0.0,0.005828792229294777,0.0,0.0,0.05,0.0,0.05136095875426159,0.019410709317290362,0.22199651102224985,0.028027215972542763,0.6984001199404398 +240,0.0006726199644617736,0.0,0.005322547629475594,0.0,0.0,0.05,0.0,0.023564698687693557,0.024809478816095003,0.20313255985577902,0.03067883290350437,0.7917935649553934 diff --git a/confirm__Selected-Semantic__diff_react_2d__s41_history.csv b/confirm__Selected-Semantic__diff_react_2d__s41_history.csv new file mode 100644 index 0000000000000000000000000000000000000000..af29fb27500b4ffe3349c23de66f46a032560f90 --- /dev/null +++ b/confirm__Selected-Semantic__diff_react_2d__s41_history.csv @@ -0,0 +1,6 @@ +step,pred,anchor,sync,speed,anchor_weight,sync_weight,speed_weight,val_rmse,val_sync_last,val_obs_speed,val_dyn_speed,val_step_ratio +1,0.07799327373504639,0.0,0.0,0.0,0.0,0.0,0.0,1.0741065157433338,-0.2904602342361586,0.1286280949910482,0.09180084615945816,3.010031223297119 +60,0.0009699984220787883,0.0,0.012524371966719627,0.0,0.0,0.03,0.0,0.02936300399073579,-0.19853527481399,0.12112603336572647,0.06615002204974492,2.0186357498168945 +120,0.0009036918636411428,0.0,0.011659987270832062,0.0,0.0,0.05,0.0,0.028603086469966173,0.056839442164416255,0.1678642282883326,0.031843677163124084,0.8352176745732626 +180,0.0005637854337692261,0.0,0.008883209899067879,0.0,0.0,0.05,0.0,0.02640585387699201,0.06990583687931477,0.1789672722419103,0.036499399691820145,0.8910857240358988 +240,0.00020909807062707841,0.0,0.00833023339509964,0.0,0.0,0.05,0.0,0.017461935070742927,0.03098954018612497,0.143446813027064,0.016865722835063934,0.3944693406422933 diff --git a/confirm__Selected-Semantic__swe_2d__s17_history.csv b/confirm__Selected-Semantic__swe_2d__s17_history.csv new file mode 100644 index 0000000000000000000000000000000000000000..0f0849493a4e0c478b886dfac0f63384d282f1fa --- /dev/null +++ b/confirm__Selected-Semantic__swe_2d__s17_history.csv @@ -0,0 +1,6 @@ +step,pred,anchor,sync,speed,anchor_weight,sync_weight,speed_weight,val_rmse,val_sync_last,val_obs_speed,val_dyn_speed,val_step_ratio +1,0.9216632843017578,0.0,0.0,0.0,0.0,0.0,0.0,0.8626814048497602,-5.532511941812764,0.026904047777255375,0.06447849919398625,2.485479195912679 +60,0.0017722796183079481,0.0,0.0015457863919436932,0.0,0.0,0.03,0.0,0.047105809071284054,-0.9408551053446877,0.05644879241784414,0.05676385387778282,1.0521302620569866 +120,0.0018312850734218955,0.0,0.0005931168561801314,0.0,0.0,0.05,0.0,0.034128296696896133,-0.10117022036010614,0.0433828371266524,0.01595711459716161,0.37275125583012897 +180,0.0003022469172719866,0.0,0.00030160299502313137,0.0,0.0,0.05,0.0,0.052994431931765944,-0.06336527658632372,0.04159506782889366,0.014061840251088142,0.3405705789724986 +240,0.0012924100738018751,0.0,0.000387190084438771,0.0,0.0,0.05,0.0,0.03384947173505952,-0.15185502045543317,0.03648931781450907,0.018286801253755886,0.5112934311230978 diff --git a/confirm__Selected-Semantic__swe_2d__s41_history.csv b/confirm__Selected-Semantic__swe_2d__s41_history.csv new file mode 100644 index 0000000000000000000000000000000000000000..6175d3be79501794407080bddf40b2e6fd54cffa --- /dev/null +++ b/confirm__Selected-Semantic__swe_2d__s41_history.csv @@ -0,0 +1,6 @@ +step,pred,anchor,sync,speed,anchor_weight,sync_weight,speed_weight,val_rmse,val_sync_last,val_obs_speed,val_dyn_speed,val_step_ratio +1,1.3209093809127808,0.0,0.0,0.0,0.0,0.0,0.0,0.643017494004098,-3.546545034345513,0.03417169054349264,0.0661844660838445,1.997111717859904 +60,0.002793785184621811,0.0,0.0015901621663942933,0.0,0.0,0.03,0.0,0.051412251201985865,-0.743157804043095,0.058964566638072334,0.053243834525346756,0.9673173427581787 +120,0.0008841467788442969,0.0,0.0010433027055114508,0.0,0.0,0.05,0.0,0.0364328846879714,-0.07708041705318269,0.057451002299785614,0.017699964965383213,0.3157781958580017 +180,0.0012469870271161199,0.0,0.0006876095430925488,0.0,0.0,0.05,0.0,0.0431864172116732,-0.09150831307923797,0.045982720951239266,0.014778077602386475,0.3257700204849243 +240,0.0024867323227226734,0.0,0.0006699045188724995,0.0,0.0,0.05,0.0,0.03696442250742829,-0.07581984108273022,0.04860068609317144,0.016499093423287075,0.34428228934605914 diff --git a/data_finite_audit.csv b/data_finite_audit.csv new file mode 100644 index 0000000000000000000000000000000000000000..b5de2c3a8d415bda29cfa97d70d197b2f2321e8a --- /dev/null +++ b/data_finite_audit.csv @@ -0,0 +1,19 @@ +task,split,tensor,finite,min,max,mean,std +burgers,train,history,True,-2.6379597187042236,2.3229775428771973,-0.08858475089073181,0.7023561596870422 +burgers,train,target,True,-2.579087495803833,2.2675113677978516,-0.08858495205640793,0.6830140948295593 +burgers,val,history,True,-1.9403314590454102,2.317517042160034,0.03168937563896179,0.7393393516540527 +burgers,val,target,True,-1.9171379804611206,2.2377374172210693,0.03168877586722374,0.7118183374404907 +burgers,test,history,True,-1.400324821472168,2.144442558288574,0.2857777178287506,0.6710096597671509 +burgers,test,target,True,-1.360896110534668,2.0784852504730225,0.2857781946659088,0.6574416160583496 +diff_react_2d,train,history,True,-4.751698017120361,4.8847551345825195,-0.029713183641433716,0.3676527142524719 +diff_react_2d,train,target,True,-0.5667744874954224,0.5370261669158936,-0.032400939613580704,0.10112137347459793 +diff_react_2d,val,history,True,-4.765668869018555,4.633437633514404,-0.029742024838924408,0.3675672113895416 +diff_react_2d,val,target,True,-0.5251368284225464,0.520041823387146,-0.03235478326678276,0.10054886341094971 +diff_react_2d,test,history,True,-4.838363170623779,4.347934246063232,-0.027614139020442963,0.3675236105918884 +diff_react_2d,test,target,True,-0.5166547894477844,0.48739176988601685,-0.029960518702864647,0.10217346996068954 +swe_2d,train,history,True,0.26135239005088806,2.0,1.0310554504394531,0.14037320017814636 +swe_2d,train,target,True,0.25597837567329407,2.0,1.0310554504394531,0.13310083746910095 +swe_2d,val,history,True,0.2683012783527374,2.0,1.035354733467102,0.14938805997371674 +swe_2d,val,target,True,0.25656038522720337,2.0,1.0353546142578125,0.14214810729026794 +swe_2d,test,history,True,0.2650366723537445,2.0,1.0360107421875,0.15087556838989258 +swe_2d,test,target,True,0.25636500120162964,2.0,1.0360107421875,0.1435721516609192 diff --git a/neuraloperator_checkpoint_repair.csv b/neuraloperator_checkpoint_repair.csv new file mode 100644 index 0000000000000000000000000000000000000000..a9447bb728792e163b2e3a21c3287a1a6a9ce68e --- /dev/null +++ b/neuraloperator_checkpoint_repair.csv @@ -0,0 +1,4 @@ +task,pass,removed_pseudo_metadata_keys,error +burgers,True,['_metadata'], +diff_react_2d,True,['_metadata'], +swe_2d,True,['_metadata'], diff --git a/official_data_manifest.json b/official_data_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..48ac7325045d11cba34733176e4bdcec60928610 --- /dev/null +++ b/official_data_manifest.json @@ -0,0 +1,20 @@ +{ + "burgers": { + "filename": "1D_Burgers_Sols_Nu0.01.hdf5", + "url": "https://darus.uni-stuttgart.de/api/access/datafile/281363", + "md5": "e6d9a4f62baf9a29121a816b919e2770", + "path": "/content/CIDM_PDEBench_Data/1D_Burgers_Sols_Nu0.01.hdf5" + }, + "diff_react_2d": { + "filename": "2D_diff-react_NA_NA.h5", + "url": "https://darus.uni-stuttgart.de/api/access/datafile/133017", + "md5": "b8d0b86064193195ddc30c33be5dc949", + "path": "/content/CIDM_PDEBench_Data/2D_diff-react_NA_NA.h5" + }, + "swe_2d": { + "filename": "2D_rdb_NA_NA.h5", + "url": "https://darus.uni-stuttgart.de/api/access/datafile/133021", + "md5": "75d838c47aa410694bdc912ea7f22282", + "path": "/content/CIDM_PDEBench_Data/2D_rdb_NA_NA.h5" + } +} \ No newline at end of file diff --git a/screen__C0_Euler_PredOnly__burgers_history.csv b/screen__C0_Euler_PredOnly__burgers_history.csv new file mode 100644 index 0000000000000000000000000000000000000000..352753c2c4d74531c5d4da5859557ac58cc144bd --- /dev/null +++ b/screen__C0_Euler_PredOnly__burgers_history.csv @@ -0,0 +1,6 @@ +step,pred,anchor,sync,speed,anchor_weight,sync_weight,speed_weight,val_rmse,val_sync_last,val_obs_speed,val_dyn_speed,val_step_ratio +1,0.2631424367427826,0.0,0.0,0.0,0.0,0.0,0.0,0.640483049622541,-0.07874431738503178,0.16199879348278046,0.06646031141281128,82.29841232299805 +20,0.08264627307653427,0.0,0.0,0.0,0.0,0.0,0.0,0.2735922239425511,-0.38247010233881507,0.13356643915176392,0.12437286600470543,168.99044799804688 +40,0.04015783593058586,0.0,0.0,0.0,0.0,0.0,0.0,0.2523142422409703,-0.6776422591810256,0.13775088638067245,0.179518923163414,244.42076110839844 +60,0.05081116408109665,0.0,0.0,0.0,0.0,0.0,0.0,0.19576833460891332,-0.6654239723665389,0.12337533757090569,0.1565008908510208,225.83042907714844 +80,0.037521399557590485,0.0,0.0,0.0,0.0,0.0,0.0,0.1927094808535734,-0.44500984220287754,0.13004452735185623,0.13318440318107605,188.55020904541016 diff --git a/screen__C0_Euler_PredOnly__diff_react_2d_history.csv b/screen__C0_Euler_PredOnly__diff_react_2d_history.csv new file mode 100644 index 0000000000000000000000000000000000000000..0d8a31e83700087d415a4c41c59aabeaf0874488 --- /dev/null +++ b/screen__C0_Euler_PredOnly__diff_react_2d_history.csv @@ -0,0 +1,6 @@ +step,pred,anchor,sync,speed,anchor_weight,sync_weight,speed_weight,val_rmse,val_sync_last,val_obs_speed,val_dyn_speed,val_step_ratio +1,0.10725043714046478,0.0,0.0,0.0,0.0,0.0,0.0,1.2162065681414564,-0.20606387795136114,0.1471483459075292,0.08913871894280116,2.8306159178415933 +20,0.0055647059343755245,0.0,0.0,0.0,0.0,0.0,0.0,0.06593392982453194,-0.31681303652669507,0.1019518996278445,0.07070485750834148,2.2161954243977866 +40,0.0012165068183094263,0.0,0.0,0.0,0.0,0.0,0.0,0.0376336775495907,-0.09905947600754546,0.17467132210731506,0.06907096256812413,2.0333827336629233 +60,0.001025224570184946,0.0,0.0,0.0,0.0,0.0,0.0,0.02720211431422068,-0.062156623035825455,0.17181935409704843,0.06664068748553593,2.0932087898254395 +80,0.0006349861505441368,0.0,0.0,0.0,0.0,0.0,0.0,0.024831059020262915,-0.061241943206522785,0.15516349176565805,0.06596797953049342,1.9857969681421916 diff --git a/screen__C0_Euler_PredOnly__swe_2d_history.csv b/screen__C0_Euler_PredOnly__swe_2d_history.csv new file mode 100644 index 0000000000000000000000000000000000000000..94ade209db5e53f6269814dabbd09d3891c0ba48 --- /dev/null +++ b/screen__C0_Euler_PredOnly__swe_2d_history.csv @@ -0,0 +1,6 @@ +step,pred,anchor,sync,speed,anchor_weight,sync_weight,speed_weight,val_rmse,val_sync_last,val_obs_speed,val_dyn_speed,val_step_ratio +1,0.9216632843017578,0.0,0.0,0.0,0.0,0.0,0.0,0.862681409168029,-5.532511906287087,0.02690404715637366,0.06447850167751312,2.4854793548583984 +20,0.01569940149784088,0.0,0.0,0.0,0.0,0.0,0.0,0.11523888415469222,-2.698797324696845,0.04425686101118723,0.07508655140797298,1.754618724187215 +40,0.004725953564047813,0.0,0.0,0.0,0.0,0.0,0.0,0.060502452041477514,-1.7456152760464596,0.05417645846803983,0.07669885208209355,1.5077368021011353 +60,0.0017366025131195784,0.0,0.0,0.0,0.0,0.0,0.0,0.04730061682079408,-1.5069802981147815,0.05604097992181778,0.07196906457344691,1.3422114451726277 +80,0.002099295612424612,0.0,0.0,0.0,0.0,0.0,0.0,0.04483280360039643,-1.2687197001154742,0.061637447526057564,0.07274911055962245,1.2328402996063232 diff --git a/screen__C1_Euler_Sync__burgers_history.csv b/screen__C1_Euler_Sync__burgers_history.csv new file mode 100644 index 0000000000000000000000000000000000000000..1a4be16c2146221682a076de74b52bb82970dc8d --- /dev/null +++ b/screen__C1_Euler_Sync__burgers_history.csv @@ -0,0 +1,6 @@ +step,pred,anchor,sync,speed,anchor_weight,sync_weight,speed_weight,val_rmse,val_sync_last,val_obs_speed,val_dyn_speed,val_step_ratio +1,0.2631424367427826,0.0,0.0,0.0,0.0,0.0,0.0,0.6404830379897887,-0.07874431738503178,0.16199880093336105,0.06646031141281128,82.2983570098877 +20,0.08258147537708282,0.0,0.009093535132706165,0.0,0.0,0.03,0.0,0.2735376447123843,-0.36673773340736393,0.13342270627617836,0.12161131575703621,165.45623779296875 +40,0.039538417011499405,0.0,0.007768645416945219,0.0,0.0,0.05,0.0,0.2525049937457871,-0.32046729740744195,0.1365385428071022,0.11988584324717522,167.07816314697266 +60,0.05047978460788727,0.0,0.010771671310067177,0.0,0.0,0.05,0.0,0.19385838659072496,-0.20480532366243412,0.12046900764107704,0.08211984857916832,121.67328262329102 +80,0.03869065269827843,0.0,0.011036974377930164,0.0,0.0,0.05,0.0,0.18325291609720723,-0.1513257326976225,0.12311743199825287,0.07198306173086166,105.13082504272461 diff --git a/screen__C1_Euler_Sync__diff_react_2d_history.csv b/screen__C1_Euler_Sync__diff_react_2d_history.csv new file mode 100644 index 0000000000000000000000000000000000000000..ff23e2faf1b022b23401410d658147023a5763df --- /dev/null +++ b/screen__C1_Euler_Sync__diff_react_2d_history.csv @@ -0,0 +1,6 @@ +step,pred,anchor,sync,speed,anchor_weight,sync_weight,speed_weight,val_rmse,val_sync_last,val_obs_speed,val_dyn_speed,val_step_ratio +1,0.10725043714046478,0.0,0.0,0.0,0.0,0.0,0.0,1.2162065558892932,-0.20606387795136114,0.14714835087458292,0.08913871894280116,2.8306155999501548 +20,0.005606633611023426,0.0,0.006234755739569664,0.0,0.0,0.03,0.0,0.06619142308773841,-0.30420791800935504,0.10094471275806427,0.06918643414974213,2.1689164638519287 +40,0.0016429725801572204,0.0,0.014614746905863285,0.0,0.0,0.05,0.0,0.04219845133908568,-0.013375635504027789,0.15212089816729227,0.05649210264285406,1.6446565389633179 +60,0.0012857511173933744,0.0,0.004339870531111956,0.0,0.0,0.05,0.0,0.027358829675355138,0.13241167581828328,0.15882916251818338,0.05159193525711695,1.564325213432312 +80,0.0007603329140692949,0.0,0.0069250138476490974,0.0,0.0,0.05,0.0,0.024582025354822408,0.154098243679872,0.16379189987977347,0.04299348716934522,1.2714354991912842 diff --git a/screen__C1_Euler_Sync__swe_2d_history.csv b/screen__C1_Euler_Sync__swe_2d_history.csv new file mode 100644 index 0000000000000000000000000000000000000000..584e6148c12012e5b79462ed0c6e2331f0c54153 --- /dev/null +++ b/screen__C1_Euler_Sync__swe_2d_history.csv @@ -0,0 +1,6 @@ +step,pred,anchor,sync,speed,anchor_weight,sync_weight,speed_weight,val_rmse,val_sync_last,val_obs_speed,val_dyn_speed,val_step_ratio +1,0.9216632843017578,0.0,0.0,0.0,0.0,0.0,0.0,0.8626814134862979,-5.532512917510135,0.026904048398137093,0.06447849919398625,2.4854792753855386 +20,0.015688816085457802,0.0,0.0019834490958601236,0.0,0.0,0.03,0.0,0.11532225329159757,-2.542651839162294,0.04425382986664772,0.07282786319653194,1.7017923593521118 +40,0.003909940831363201,0.0,0.0022846744395792484,0.0,0.0,0.05,0.0,0.062379483588062556,-0.7743658153293872,0.06138250604271889,0.05667152379949888,0.9969862898190817 +60,0.0032821507193148136,0.0,0.0006840589339844882,0.0,0.0,0.05,0.0,0.06514920402947758,-0.3789899274078761,0.04627354939778646,0.029595208043853443,0.6673722465833029 +80,0.00224099587649107,0.0,0.0008284448413178325,0.0,0.0,0.05,0.0,0.04883607114269896,-0.13904070211259922,0.05242707828680674,0.020608864724636078,0.4084564546744029 diff --git a/screen__C2_Euler_AnchorSync__burgers_history.csv b/screen__C2_Euler_AnchorSync__burgers_history.csv new file mode 100644 index 0000000000000000000000000000000000000000..5125c751b4fabf57eb197ea887ebed47947db446 --- /dev/null +++ b/screen__C2_Euler_AnchorSync__burgers_history.csv @@ -0,0 +1,6 @@ +step,pred,anchor,sync,speed,anchor_weight,sync_weight,speed_weight,val_rmse,val_sync_last,val_obs_speed,val_dyn_speed,val_step_ratio +1,0.2631424367427826,0.0,0.0,0.0,0.0,0.0,0.0,0.640483049622541,-0.07874431738503178,0.16199880093336105,0.06646031141281128,82.29833602905273 +20,0.08167807757854462,0.06467848271131516,0.009121880866587162,0.0,0.03,0.03,0.0,0.27200329537797147,-0.36509027889712764,0.1336023136973381,0.12155327200889587,165.4083251953125 +40,0.03954211249947548,0.020508229732513428,0.007868988439440727,0.0,0.05,0.05,0.0,0.2601462852013011,-0.3132631719028536,0.1382647641003132,0.12039093673229218,167.34922409057617 +60,0.050788283348083496,0.017798244953155518,0.011054209433495998,0.0,0.05,0.05,0.0,0.19212948875342822,-0.20123206606012273,0.12251953780651093,0.08286821097135544,122.02833557128906 +80,0.03902658447623253,0.012110082432627678,0.011189430020749569,0.0,0.05,0.05,0.0,0.18064571493649606,-0.1598083649277041,0.12323768436908722,0.0740467868745327,107.70825576782227 diff --git a/screen__C2_Euler_AnchorSync__diff_react_2d_history.csv b/screen__C2_Euler_AnchorSync__diff_react_2d_history.csv new file mode 100644 index 0000000000000000000000000000000000000000..ace61b1d469ea27ad799f311676061da7e95a6ec --- /dev/null +++ b/screen__C2_Euler_AnchorSync__diff_react_2d_history.csv @@ -0,0 +1,6 @@ +step,pred,anchor,sync,speed,anchor_weight,sync_weight,speed_weight,val_rmse,val_sync_last,val_obs_speed,val_dyn_speed,val_step_ratio +1,0.10725043714046478,0.0,0.0,0.0,0.0,0.0,0.0,1.2162065558892932,-0.20606378774091572,0.1471483459075292,0.08913871894280116,2.830615520477295 +20,0.005546096712350845,0.006042824126780033,0.006260608322918415,0.0,0.03,0.03,0.0,0.06599809359859019,-0.30311946284752594,0.10125453521807988,0.06922104954719543,2.1644956270853677 +40,0.001818877994082868,0.003157160710543394,0.013777881860733032,0.0,0.05,0.05,0.0,0.04307170172278408,-0.012001082230512489,0.14733856419722238,0.056797737876574196,1.6556047598520915 +60,0.0012551341205835342,0.0018889950588345528,0.004057706333696842,0.0,0.05,0.05,0.0,0.02718515107580623,0.13385294648305168,0.15020462373892465,0.0532126451532046,1.6107751528422039 +80,0.0007192345801740885,0.0014232090907171369,0.006242799572646618,0.0,0.05,0.05,0.0,0.02546062857490604,0.15160755471680015,0.14907882114251456,0.04371687273184458,1.2842543522516887 diff --git a/screen__C2_Euler_AnchorSync__swe_2d_history.csv b/screen__C2_Euler_AnchorSync__swe_2d_history.csv new file mode 100644 index 0000000000000000000000000000000000000000..ca0f3f9e7951cdaaddb6ac62da66964eea4ada52 --- /dev/null +++ b/screen__C2_Euler_AnchorSync__swe_2d_history.csv @@ -0,0 +1,6 @@ +step,pred,anchor,sync,speed,anchor_weight,sync_weight,speed_weight,val_rmse,val_sync_last,val_obs_speed,val_dyn_speed,val_step_ratio +1,0.9216632843017578,0.0,0.0,0.0,0.0,0.0,0.0,0.8626814134862979,-5.532512894161637,0.026904048398137093,0.06447850167751312,2.485479195912679 +20,0.015851564705371857,0.015630315989255905,0.0019859476014971733,0.0,0.03,0.03,0.0,0.11540784951973015,-2.5366378849568654,0.04432571058471998,0.072865625222524,1.7000387112299602 +40,0.004057317040860653,0.0032473625615239143,0.0022682729177176952,0.0,0.05,0.05,0.0,0.06087050210800117,-0.7894485719512914,0.06046536440650622,0.05641567955414454,1.0080965360005696 +60,0.003367631696164608,0.0031173587776720524,0.0006855971878394485,0.0,0.05,0.05,0.0,0.06856773120260322,-0.40256835383234374,0.046297804762919746,0.030525342871745426,0.6876290043195089 +80,0.002251487458124757,0.00195430894382298,0.0009720445377752185,0.0,0.05,0.05,0.0,0.04998966287485394,-0.16454189791378496,0.05651892970005671,0.024070875098307926,0.44318462411562604 diff --git a/screen__C3_Euler_AnchorSyncSpeed__burgers_history.csv b/screen__C3_Euler_AnchorSyncSpeed__burgers_history.csv new file mode 100644 index 0000000000000000000000000000000000000000..b726823794cffceb795505a3c9d44c4ad367487f --- /dev/null +++ b/screen__C3_Euler_AnchorSyncSpeed__burgers_history.csv @@ -0,0 +1,6 @@ +step,pred,anchor,sync,speed,anchor_weight,sync_weight,speed_weight,val_rmse,val_sync_last,val_obs_speed,val_dyn_speed,val_step_ratio +1,0.2631424367427826,0.0,0.0,0.0,0.0,0.0,0.0,0.6404830379897887,-0.07874427521041757,0.16199880093336105,0.06646031141281128,82.29811096191406 +20,0.08167809993028641,0.06467850506305695,0.009121879003942013,0.0,0.03,0.03,0.0,0.272003329617355,-0.36509027949434225,0.1336023136973381,0.12155327200889587,165.40791702270508 +40,0.03954189270734787,0.020508229732513428,0.007868151180446148,0.002991095883771777,0.05,0.05,0.0006666666666666666,0.2601467649202786,-0.31304749821187655,0.13826516270637512,0.12034817785024643,167.29647827148438 +60,0.05078838765621185,0.01779874600470066,0.01105230487883091,0.004538993816822767,0.05,0.05,0.002,0.1921297238506927,-0.20100392424105373,0.12251989543437958,0.08282488211989403,121.96210479736328 +80,0.03902679681777954,0.012110164389014244,0.011188317090272903,0.004676684737205505,0.05,0.05,0.002,0.18064751420397368,-0.1597204009182012,0.12323671206831932,0.07403664290904999,107.68050003051758 diff --git a/screen__C3_Euler_AnchorSyncSpeed__diff_react_2d_history.csv b/screen__C3_Euler_AnchorSyncSpeed__diff_react_2d_history.csv new file mode 100644 index 0000000000000000000000000000000000000000..7fb8ea6a9be8b3acffeb306c1cf326424bc5a838 --- /dev/null +++ b/screen__C3_Euler_AnchorSyncSpeed__diff_react_2d_history.csv @@ -0,0 +1,6 @@ +step,pred,anchor,sync,speed,anchor_weight,sync_weight,speed_weight,val_rmse,val_sync_last,val_obs_speed,val_dyn_speed,val_step_ratio +1,0.10725043714046478,0.0,0.0,0.0,0.0,0.0,0.0,1.2162065497632117,-0.20606386167850133,0.14714835087458292,0.08913872142632802,2.830615679423014 +20,0.005546096712350845,0.0060428231954574585,0.0062606073915958405,0.0,0.03,0.03,0.0,0.06599809227565057,-0.30311944765105636,0.10125453273455302,0.06922104954719543,2.164495865503947 +40,0.001818914315663278,0.00315715535543859,0.013777604326605797,0.01457437127828598,0.05,0.05,0.0006666666666666666,0.043072154443785295,-0.012085616056504898,0.14733285705248514,0.05682603518168131,1.6563710769017537 +60,0.0012552911648526788,0.0018926074262708426,0.004064403474330902,0.005300787277519703,0.05,0.05,0.002,0.027189057201255147,0.13320416304981603,0.15010092159112295,0.0539882630109787,1.6328133742014568 +80,0.0007178827072493732,0.0014251956017687917,0.006233555264770985,0.01075000874698162,0.05,0.05,0.002,0.02551979169873434,0.15248400834988526,0.1488466113805771,0.045133216927448906,1.3221594095230103 diff --git a/screen__C3_Euler_AnchorSyncSpeed__swe_2d_history.csv b/screen__C3_Euler_AnchorSyncSpeed__swe_2d_history.csv new file mode 100644 index 0000000000000000000000000000000000000000..03314fda8393d53aaeda5b347ae49057311b3e0f --- /dev/null +++ b/screen__C3_Euler_AnchorSyncSpeed__swe_2d_history.csv @@ -0,0 +1,6 @@ +step,pred,anchor,sync,speed,anchor_weight,sync_weight,speed_weight,val_rmse,val_sync_last,val_obs_speed,val_dyn_speed,val_step_ratio +1,0.9216632843017578,0.0,0.0,0.0,0.0,0.0,0.0,0.8626814048497602,-5.532512788910551,0.026904047777255375,0.06447850167751312,2.4854792753855386 +20,0.015851110219955444,0.015629863366484642,0.0019859434105455875,0.0,0.03,0.03,0.0,0.1154125052176083,-2.5366445593874274,0.04432563856244087,0.07286558796962102,1.700040300687154 +40,0.004057287238538265,0.003247368149459362,0.0022682109847664833,0.0001242076396010816,0.05,0.05,0.0006666666666666666,0.06087266918004553,-0.7893784299930201,0.06046568602323532,0.05641346673170725,1.0080521901448567 +60,0.00336842960678041,0.0031180796213448048,0.0006869162898510695,1.8380747860646807e-05,0.05,0.05,0.002,0.06857784200654435,-0.4048548711488266,0.04629520823558172,0.030607717111706734,0.6895303726196289 +80,0.0022529258858412504,0.001955633517354727,0.0009754721540957689,0.0002461503027006984,0.05,0.05,0.002,0.05001558298723604,-0.16914178581184372,0.05649300913016001,0.024378334482510883,0.449123740196228 diff --git a/screen__C4_Cayley_AnchorSyncSpeed__burgers_history.csv b/screen__C4_Cayley_AnchorSyncSpeed__burgers_history.csv new file mode 100644 index 0000000000000000000000000000000000000000..77e044c08f5aa826be29af9f1a5dfa2ca3e3937f --- /dev/null +++ b/screen__C4_Cayley_AnchorSyncSpeed__burgers_history.csv @@ -0,0 +1,6 @@ +step,pred,anchor,sync,speed,anchor_weight,sync_weight,speed_weight,val_rmse,val_sync_last,val_obs_speed,val_dyn_speed,val_step_ratio +1,0.26310995221138,0.0,0.0,0.0,0.0,0.0,0.0,0.6404585622110749,-0.078779641615692,0.16200271248817444,0.06642843037843704,82.26239967346191 +20,0.08169161528348923,0.06471476703882217,0.009088786318898201,0.0,0.03,0.03,0.0,0.2726416040110332,-0.36392016787281456,0.13361411914229393,0.12130802497267723,165.15452575683594 +40,0.038486942648887634,0.01953612081706524,0.007875466719269753,0.0029473495669662952,0.05,0.05,0.0006666666666666666,0.26343740351823375,-0.2982725184359116,0.13872236385941505,0.11776018515229225,163.99179077148438 +60,0.051118724048137665,0.018491730093955994,0.01101650670170784,0.004513866268098354,0.05,0.05,0.002,0.1955362325965982,-0.20268057224177882,0.1221764087677002,0.08283847942948341,121.92816543579102 +80,0.03911392018198967,0.011992697604000568,0.011233982630074024,0.0047201854176819324,0.05,0.05,0.002,0.18261261286590064,-0.15545500488780317,0.12412595748901367,0.07375380024313927,107.19236755371094 diff --git a/screen__C4_Cayley_AnchorSyncSpeed__diff_react_2d_history.csv b/screen__C4_Cayley_AnchorSyncSpeed__diff_react_2d_history.csv new file mode 100644 index 0000000000000000000000000000000000000000..443979e8c2284f3a8ed9a79d2b3cfbbbea3f7111 --- /dev/null +++ b/screen__C4_Cayley_AnchorSyncSpeed__diff_react_2d_history.csv @@ -0,0 +1,6 @@ +step,pred,anchor,sync,speed,anchor_weight,sync_weight,speed_weight,val_rmse,val_sync_last,val_obs_speed,val_dyn_speed,val_step_ratio +1,0.10725909471511841,0.0,0.0,0.0,0.0,0.0,0.0,1.2161694557732925,-0.20667429225825965,0.1471502979596456,0.08918767670790355,2.831989129384359 +20,0.005530442576855421,0.006027192808687687,0.006259592715650797,0.0,0.03,0.03,0.0,0.06599117426177942,-0.30223410124477407,0.10129123429457347,0.06904112795988719,2.1577163537343345 +40,0.0018203899962827563,0.0031579947099089622,0.01377627532929182,0.014584744349122047,0.05,0.05,0.0006666666666666666,0.04308070828712416,-0.011490892474773867,0.14733754098415375,0.05670132115483284,1.6523823738098145 +60,0.0012547355145215988,0.0018919432768598199,0.004067071247845888,0.005311363376677036,0.05,0.05,0.002,0.02719550119537364,0.1337300934844481,0.15022142231464386,0.05387552082538605,1.6286226908365886 +80,0.0007197068771347404,0.0014271069085225463,0.0062346747145056725,0.010770989581942558,0.05,0.05,0.002,0.025477729483350888,0.1528344301235854,0.14894897242387137,0.04504694044589996,1.319190541903178 diff --git a/screen__C4_Cayley_AnchorSyncSpeed__swe_2d_history.csv b/screen__C4_Cayley_AnchorSyncSpeed__swe_2d_history.csv new file mode 100644 index 0000000000000000000000000000000000000000..9f97f911a2b8c2e68c952d99bb149be551df6f77 --- /dev/null +++ b/screen__C4_Cayley_AnchorSyncSpeed__swe_2d_history.csv @@ -0,0 +1,6 @@ +step,pred,anchor,sync,speed,anchor_weight,sync_weight,speed_weight,val_rmse,val_sync_last,val_obs_speed,val_dyn_speed,val_step_ratio +1,0.9217020273208618,0.0,0.0,0.0,0.0,0.0,0.0,0.8627726882252212,-5.534723830898291,0.026903071751197178,0.06447457025448482,2.4854249954223633 +20,0.015580572187900543,0.015359893441200256,0.0019751018844544888,0.0,0.03,0.03,0.0,0.11776671368667138,-2.523776148837297,0.04429438958565394,0.07258467376232147,1.6945419708887737 +40,0.003983668051660061,0.003197826910763979,0.0022738089319318533,0.00012425697059370577,0.05,0.05,0.0006666666666666666,0.062102303977759385,-0.7899638874565991,0.06066480030616125,0.05656911681095759,1.0078758200009663 +60,0.003428494557738304,0.003179779276251793,0.0007027871906757355,2.0556006347760558e-05,0.05,0.05,0.002,0.06732474378481243,-0.4021373297954384,0.04667243113120397,0.0307683323820432,0.6880944768587748 +80,0.002380946185439825,0.0021469872444868088,0.0008835531771183014,0.00022259869729168713,0.05,0.05,0.002,0.049824426458319096,-0.1752672824529431,0.05302232379714648,0.023324893787503242,0.4581534465154012 diff --git a/selected_branch_audit.csv b/selected_branch_audit.csv new file mode 100644 index 0000000000000000000000000000000000000000..4324c2c749e40c8588cbd72bba53573369335525 --- /dev/null +++ b/selected_branch_audit.csv @@ -0,0 +1,7 @@ +seed,task,skew_delta_cos,skew_norm_ratio,flux_delta_cos,flux_norm_ratio,local_delta_cos,local_norm_ratio,total_delta_cos,total_norm_ratio,skew_budget_fraction,flux_budget_fraction,local_budget_fraction +17,burgers,0.0013656560331583023,152.73060607910156,0.0006985156069276854,25.720701813697815,0.10754729062318802,7.685434237122536,0.007208673050627112,153.4901294708252,0.8215492069721222,0.13534660637378693,0.04310414753854275 +17,diff_react_2d,0.10441821720451117,0.7340127602219582,-0.1979677937924862,0.00845514377579093,0.23483028449118137,0.010007365723140538,0.10334006231278181,0.7314123287796974,0.9649790599942207,0.018831515684723854,0.016189421294257045 +17,swe_2d,0.012429351103492081,0.5371080599725246,0.05013041663914919,6.924370097749488e-06,0.005590689135715365,0.05421942984685302,0.01292537001427263,0.5389549434185028,0.9087906628847122,1.1631023426161846e-05,0.09119770769029856 +41,burgers,0.0024867922766134143,188.13918209075928,0.00041138702363241464,6.573885455727577,0.035519775934517384,10.169237285852432,0.004520793678238988,190.27593803405762,0.9073803424835205,0.035998234525322914,0.05662139877676964 +41,diff_react_2d,0.11288194451481104,0.3589554876089096,-0.20456264540553093,0.014611530466936529,0.3022610992193222,0.009813539567403495,0.1101990481838584,0.3558346517384052,0.9163949191570282,0.0546077573671937,0.028997298562899232 +41,swe_2d,0.0016319219721481204,0.33294806629419327,0.1472770031541586,0.0056970797595568,0.0007507414193241857,0.11598197650164366,0.004415164119563997,0.32173579186201096,0.7355489879846573,0.012419753475114703,0.2520312611013651 diff --git a/semantic_candidate_screen.csv b/semantic_candidate_screen.csv new file mode 100644 index 0000000000000000000000000000000000000000..28c6ea778bca490c2d570451c03b6643970e812f --- /dev/null +++ b/semantic_candidate_screen.csv @@ -0,0 +1,16 @@ +candidate,task,completed,completed_steps,numerical_fail,fail_reason,best_val_rmse,sync_gain_mean,sync_gain_last,sync_by_lead,observed_state_anchor_decode_rmse,dynamic_final_decode_rmse,anchor_to_dynamic_decode_ratio,observed_final_relative_speed,dynamic_final_relative_speed,final_step_norm_ratio_dyn_over_obs,total_delta_cos +C0_Euler_PredOnly,burgers,True,80,False,,0.1927094808535734,-0.3006888248943694,-0.44500984220287754,"[-0.20261117563843672, -0.22347428346155065, -0.25803652081418854, -0.3061182517524385, -0.36888287549672427, -0.44500984220287754]",0.10879550874233246,0.2503768801689148,0.43452697656802186,0.13004452735185623,0.13318440318107605,188.55020904541016,-0.0009603229118511081 +C0_Euler_PredOnly,diff_react_2d,True,80,False,,0.024831059020262915,-0.02114614252259943,-0.06249073316170445,"[0.0036176433148209664, 0.0008869479306628327, -0.007616966272027343, -0.021396254974827448, -0.03987749197252113, -0.06249073316170445]",0.04411158384755254,0.0232164915651083,1.900010762773784,0.15421431325376034,0.06592305190861225,1.9657797366380692,0.03426280105486512 +C0_Euler_PredOnly,swe_2d,True,80,False,,0.04483280360039643,-1.3746120733322762,-1.3346015740334378,"[-1.4804809235816514, -1.4110297544615733, -1.3612958515219948, -1.333688718284344, -1.3265756181106565, -1.3346015740334378]",0.03895185701549053,0.05247679725289345,0.7422681843134552,0.060159413143992424,0.07279826980084181,1.276487648487091,0.0028314988303463906 +C1_Euler_Sync,burgers,True,80,False,,0.18325291609720723,-0.10253197211373803,-0.1513257326976225,"[-0.06981393199906824, -0.0764174628003239, -0.08790234855824777, -0.10418655859872758, -0.12554579802843818, -0.1513257326976225]",0.09322044998407364,0.24303140491247177,0.38357367854433116,0.12311743199825287,0.07198306173086166,105.13082504272461,0.0021982438629493117 +C1_Euler_Sync,diff_react_2d,True,80,False,,0.024582025354822408,0.11930255013020437,0.15029867369609384,"[0.05272485714011917, 0.0953130227762066, 0.12501012466872197, 0.14243373134490073, 0.15003489115518392, 0.15029867369609384]",0.04474326269701123,0.023331256350502372,1.9177391060660913,0.16310996748507023,0.04300540452823043,1.268760159611702,0.22015358321368694 +C1_Euler_Sync,swe_2d,True,80,False,,0.04883607114269896,-0.14820378194018016,-0.14538981194781428,"[-0.1584948208480223, -0.15127420994186955, -0.14634155636197324, -0.14391234689455742, -0.14380994564684413, -0.14538981194781428]",0.04511865368112922,0.054074378218501806,0.8343813681743206,0.05112661141902208,0.020537434611469507,0.42128879204392433,0.004927229834720492 +C2_Euler_AnchorSync,burgers,True,80,False,,0.18064571493649606,-0.10826834960314285,-0.1598083649277041,"[-0.07359937128683236, -0.08065561357863757, -0.09284401460179811, -0.11007830806047514, -0.1326244251634099, -0.1598083649277041]",0.08606893569231033,0.24112822860479355,0.35694259519227156,0.12323768436908722,0.0740467868745327,107.70825576782227,0.0026565948501229286 +C2_Euler_AnchorSync,diff_react_2d,True,80,False,,0.02546062857490604,0.12025233390789229,0.14730201344758773,"[0.054885831287266484, 0.0984540187253503, 0.12776774572281732, 0.14376562928191766, 0.1493387649824143, 0.14730201344758773]",0.04074244713410735,0.023450369480997324,1.7373904137042453,0.1483233105391264,0.04373121401295066,1.2804347276687622,0.23297834023833275 +C2_Euler_AnchorSync,swe_2d,True,80,False,,0.04998966287485394,-0.17515967673026003,-0.17215532843838954,"[-0.18697687211370834, -0.17859511724316163, -0.1729023192396738, -0.17016396260500957, -0.17016446074161745, -0.17215532843838957]",0.045912849716842175,0.055659638717770576,0.8248858737594262,0.05513222049921751,0.024001186480745673,0.45728158950805664,0.004049755341839045 +C3_Euler_AnchorSyncSpeed,burgers,True,80,False,,0.18064751420397368,-0.10821009706597834,-0.1597204009182012,"[-0.07356191515670607, -0.08061325837582677, -0.09279443822724534, -0.11001866948748129, -0.13255190023040933, -0.1597204009182012]",0.08607283234596252,0.24112923443317413,0.35695726629039876,0.12323671206831932,0.07403664290904999,107.68050003051758,0.002816198975779116 +C3_Euler_AnchorSyncSpeed,diff_react_2d,True,80,False,,0.02551979169873434,0.1220662932787878,0.1480823581029484,"[0.056311738534595146, 0.10071620852756775, 0.13027492183874695, 0.14602528019267824, 0.15098725247619033, 0.1480823581029484]",0.040704610757529736,0.023457656847313046,1.7352377103338963,0.14809156954288483,0.04514878848567605,1.3182497322559357,0.2308701928704977 +C3_Euler_AnchorSyncSpeed,swe_2d,True,80,False,,0.05001558298723604,-0.18005569652876638,-0.17700700379293824,"[-0.19216317796839552, -0.18356241922961328, -0.1777274584499916, -0.17492911551837337, -0.1749450042132863, -0.1770070037929382]",0.04593736073002219,0.05568184703588486,0.8249970713151323,0.05510684801265597,0.02431022608652711,0.4634660631418228,0.004047444206662476 +C4_Cayley_AnchorSyncSpeed,burgers,True,80,False,,0.18261261286590064,-0.10540268142570507,-0.15545500488780317,"[-0.07176205618429825, -0.0785879231085855, -0.09041216886072787, -0.1071507542323504, -0.12904818128046522, -0.15545500488780317]",0.08942092582583427,0.2429230958223343,0.368103845882294,0.12412595748901367,0.07375380024313927,107.19236755371094,0.002824177499860525 +C4_Cayley_AnchorSyncSpeed,diff_react_2d,True,80,False,,0.025477729483350888,0.12223053653096867,0.14843460858092944,"[0.05632478851641616, 0.10076914924860095, 0.13038826978895218, 0.14621188062019522, 0.15125452243071827, 0.14843460858092944]",0.040719661861658096,0.023436493007466197,1.7374468888619972,0.14819438941776752,0.04506289679557085,1.3153119385242462,0.2292734533548355 +C4_Cayley_AnchorSyncSpeed,swe_2d,True,80,False,,0.049824426458319096,-0.18659384667363343,-0.1836969632301449,"[-0.19901918821057574, -0.19007246903721187, -0.18407872926432078, -0.18127651685200724, -0.18141921344754017, -0.1836969632301449]",0.046432615257799625,0.0543952533043921,0.8536152042158146,0.05170767800882459,0.02326575736515224,0.47307102009654045,0.0048957543913275 diff --git a/semantic_candidate_summary.csv b/semantic_candidate_summary.csv new file mode 100644 index 0000000000000000000000000000000000000000..f77585a304f73b5501e382e69686dde3b331f329 --- /dev/null +++ b/semantic_candidate_summary.csv @@ -0,0 +1,6 @@ +candidate,eligible,mean_val_rmse_ratio_vs_C0,positive_sync_tasks,mean_sync_last,mean_abs_log_step_ratio,mean_anchor_to_dynamic_decode_ratio,reason +C0_Euler_PredOnly,True,1.0,0,-0.61403404979934,2.0531218643764655,1.0256019745517537, +C1_Euler_Sync,True,1.0100641789029845,1,-0.04880562364978098,1.9192274707864214,1.045231384261581, +C2_Euler_AnchorSync,True,1.025925855923959,1,-0.06155389330616864,1.9030272653173714,0.9730729608853145, +C3_Euler_AnchorSyncSpeed,True,1.0269158936455245,1,-0.06288168220273034,1.9081651737388137,0.9723973493131424, +C4_Cayley_AnchorSyncSpeed,True,1.028329062849252,1,-0.06357245317900621,1.8990695515270037,0.9863886463200352, diff --git a/semantic_confirmation.csv b/semantic_confirmation.csv new file mode 100644 index 0000000000000000000000000000000000000000..ddef30afbb7ea5ba4a9189951230b3a7416a980c --- /dev/null +++ b/semantic_confirmation.csv @@ -0,0 +1,19 @@ +seed,task,variant,status,params,best_val_rmse,train_gpu_seconds,peak_vram_bytes,rmse,mae,relative_l2,lead_rmse,rollout_growth,sync_gain_mean,sync_gain_last,sync_by_lead,observed_state_anchor_decode_rmse,dynamic_final_decode_rmse,anchor_to_dynamic_decode_ratio,observed_final_relative_speed,dynamic_final_relative_speed,final_step_norm_ratio_dyn_over_obs,total_delta_cos +17,burgers,Euler-PredOnly,COMPLETED,487623,0.16929015758444876,43.14570364600013,1563788288,0.1499707457332522,0.08726799115538597,0.2865189462900162,"[0.09599953889846802, 0.09610644727945328, 0.10337240993976593, 0.11455164849758148, 0.1270807981491089, 0.13948604464530945]",1.4529865980148315,-0.4409240857572423,-0.5740999125248853,"[-0.3580029613374607, -0.37090407033762685, -0.39907393220142917, -0.44242588611728373, -0.5010377520247675, -0.5740999125248853]",0.1221889965236187,0.18335384875535965,0.6664108626737892,0.12039395794272423,0.1440921425819397,65.94201564788818,0.0031906842486932874 +17,burgers,Selected-Semantic,COMPLETED,487623,0.18250181256008158,44.29690304900032,2006566400,0.15647177752172767,0.10491807758808136,0.3548569530248642,"[0.11015808582305908, 0.11108524352312088, 0.1191612184047699, 0.1306139975786209, 0.14290720224380493, 0.15473243594169617]",1.4046398401260376,-0.12573116279327512,-0.15924760532957932,"[-0.1056888055220038, -0.10834126304209081, -0.11499442816839558, -0.12565270908051412, -0.14046216561706695, -0.15924760532957932]",0.13084949180483818,0.19122642278671265,0.684264705148949,0.11984247714281082,0.07866193354129791,31.73400115966797,0.007208673050627112 +17,burgers,BlackboxCore,COMPLETED,453112,0.16309536832392837,27.15576391200011,1118245888,0.1397462715558321,0.0734796542674303,0.16401401162147522,"[0.07430826872587204, 0.07780992984771729, 0.08881807327270508, 0.10271594673395157, 0.11718272417783737, 0.13129420578479767]",1.76688551902771,,,,,,,,,, +17,diff_react_2d,Euler-PredOnly,COMPLETED,503232,0.015477659191146874,118.67044920399985,4624111616,0.015690370910899868,0.010047867777757347,0.20934375934302807,"[0.018176347017288208, 0.015775147825479507, 0.014445261098444462, 0.013992909342050552, 0.014225475490093231, 0.014895261265337467]",0.8194859623908997,-0.1565456117262294,-0.32637512231158605,"[-0.015206586367869963, -0.054859013748787176, -0.11206848249020489, -0.17923345988685693, -0.25153100555207153, -0.32637512231158605]",0.0218083958607167,0.015488087083213031,1.408075493348305,0.08648122288286686,0.06427163444459438,1.5621269196271896,0.04081425163894892 +17,diff_react_2d,Selected-Semantic,COMPLETED,503232,0.023564698687693557,129.34806594699967,5755017728,0.024234290908566356,0.017567915376275778,0.32646066695451736,"[0.027032077312469482, 0.024779746308922768, 0.023439742624759674, 0.022729763761162758, 0.022464416921138763, 0.022511128336191177]",0.8327561616897583,0.02616371663746418,0.021482850981150256,"[0.02087612975044929, 0.030321727276382365, 0.030959697304636356, 0.02837478747769486, 0.02496710703447193, 0.021482850981150256]",0.037699146661907434,0.02298241131938994,1.6403477484584565,0.20106762647628784,0.030714584281668067,0.7605674490332603,0.10334006231278181 +17,diff_react_2d,BlackboxCore,COMPLETED,489547,0.014972193764509258,67.97902066500046,2657754112,0.015147828835960078,0.00816565949935466,0.2021583430469036,"[0.016720399260520935, 0.014713664539158344, 0.013908294029533863, 0.013959156349301338, 0.014526134356856346, 0.0153517946600914]",0.918147623538971,,,,,,,,,, +17,swe_2d,Euler-PredOnly,COMPLETED,499051,0.030553254433612582,117.41366703899985,4613837312,0.0300979775016558,0.02053888887166977,0.02774921990931034,"[0.024405453354120255, 0.02442908100783825, 0.026105394586920738, 0.028947733342647552, 0.032423362135887146, 0.036188267171382904]",1.4827942848205566,-1.237389608810169,-1.193995659428481,"[-1.349951113809959, -1.2717753895652786, -1.2228632037144291, -1.1968520863295724, -1.1889002000132958, -1.193995659428481]",0.025448665488511324,0.03645177627913654,0.6981461011291532,0.06586706917732954,0.07336996961385012,1.1661478579044342,0.0020579295087372884 +17,swe_2d,Selected-Semantic,COMPLETED,499051,0.03384947173505952,127.26132532700012,5743170560,0.03352869033183614,0.020951375481672585,0.03049514815211296,"[0.03098200261592865, 0.029929963871836662, 0.03005235828459263, 0.03127375617623329, 0.0333562046289444, 0.0360197015106678]",1.1626008749008179,-0.16154888686381794,-0.15740340526959307,"[-0.17472746957471993, -0.16481043275599533, -0.15936987825335444, -0.1567169150481083, -0.15626522028113657, -0.15740340526959304]",0.03117333445698023,0.03645847551524639,0.8550366963079409,0.035740064922720194,0.018199395155534148,0.5232475399971008,0.01292537001427263 +17,swe_2d,BlackboxCore,COMPLETED,485366,0.0313635059041942,66.38894155799971,2649445376,0.030877023194201453,0.02096370968502015,0.0286776686552912,"[0.023713601753115654, 0.02416008710861206, 0.02662566676735878, 0.03015890158712864, 0.034175775945186615, 0.03843476623296738]",1.620789885520935,,,,,,,,,, +41,burgers,Euler-PredOnly,COMPLETED,487623,0.1721252007465951,40.4097172970005,1563788288,0.14676666715855638,0.08096333965659142,0.23263141512870789,"[0.08295473456382751, 0.08835357427597046, 0.09954032301902771, 0.11304094642400742, 0.1267579346895218, 0.13963700830936432]",1.6832915544509888,-0.2095730399621513,-0.2686786333317809,"[-0.1692592770469858, -0.1778274553229196, -0.19232597559541653, -0.21202648508863312, -0.23732041338717172, -0.2686786333317809]",0.10160784050822258,0.19034875184297562,0.5337983019297228,0.13284413516521454,0.10681566596031189,49.09364128112793,0.0003297128132544458 +41,burgers,Selected-Semantic,COMPLETED,487623,0.16805789489295775,44.185808762000306,2006566400,0.14398556874898574,0.07778021320700645,0.1751851886510849,"[0.08438622951507568, 0.0860808789730072, 0.09425514936447144, 0.10573302209377289, 0.11818395555019379, 0.1302042156457901]",1.542955756187439,-0.11576000162579253,-0.14865607875214965,"[-0.094077872638196, -0.09836014546716651, -0.10598118542717046, -0.11667929629613469, -0.130805431173938, -0.14865607875214965]",0.11146904155611992,0.18261826038360596,0.610393732379058,0.12241233512759209,0.07542578503489494,32.996474266052246,0.004520793678238988 +41,burgers,BlackboxCore,COMPLETED,453112,0.1624037729362137,27.496437993000654,1118245888,0.12911317934642702,0.07789885997772217,0.2890360802412033,"[0.06444382667541504, 0.07250232994556427, 0.08732233196496964, 0.10307340323925018, 0.11757981777191162, 0.13012836873531342]",2.0192527770996094,,,,,,,,,, +41,diff_react_2d,Euler-PredOnly,COMPLETED,503232,0.01952723763647711,118.42930230799993,4624111616,0.019729806024337822,0.013998490176163614,0.2738202214241028,"[0.022609751671552658, 0.02031121402978897, 0.0189774502068758, 0.01833718828856945, 0.018195293843746185, 0.01839195005595684]",0.8134521245956421,-0.26180370041134876,-0.557498633396384,"[-0.026905110474056682, -0.08931417999458606, -0.18130343523292683, -0.2943707055893759, -0.4214301377807628, -0.557498633396384]",0.023791946936398745,0.018723343033343554,1.2707104118120756,0.09296963829547167,0.07836077362298965,1.65946826338768,-0.04880017600953579 +41,diff_react_2d,Selected-Semantic,COMPLETED,503232,0.017461935070742927,129.26759447099994,5755017728,0.0176343011928536,0.012073409394361079,0.23316538706421852,"[0.020160431042313576, 0.017715029418468475, 0.016392845660448074, 0.015970760956406593, 0.016208410263061523, 0.01684470660984516]",0.835533082485199,0.03330218388726496,0.029623088325610523,"[0.028757120109587215, 0.03770311643636633, 0.037102021049736436, 0.03461231536840559, 0.03201544203388368, 0.029623088325610523]",0.02103782002814114,0.01733495807275176,1.2136066288622749,0.1451829243451357,0.016898056026548147,0.38582880422472954,0.1101990481838584 +41,diff_react_2d,BlackboxCore,COMPLETED,489547,0.014911862215968706,67.97330821500054,2657754112,0.01507748176105691,0.010421790997497737,0.2096279338002205,"[0.017527390271425247, 0.01527839619666338, 0.014171184971928596, 0.013868428766727448, 0.014058208093047142, 0.014506678096950054]",0.8276576399803162,,,,,,,,,, +41,swe_2d,Euler-PredOnly,COMPLETED,499051,0.034153520197926016,117.16719404899959,4613837312,0.033510004193101586,0.022667597280815244,0.0314622528385371,"[0.02431523986160755, 0.026161689311265945, 0.02945145219564438, 0.033506982028484344, 0.03788837417960167, 0.042351339012384415]",1.7417610883712769,-1.0008490668432712,-0.9911075571970146,"[-1.0554453144152456, -1.0150189938150875, -0.9882350095721797, -0.9766363311397538, -0.9786511949203475, -0.9911075571970146]",0.025645729154348373,0.04267868306487799,0.6009025422683035,0.06766525888815522,0.06914292741566896,1.0716578513383865,0.010027030715718865 +41,swe_2d,Selected-Semantic,COMPLETED,499051,0.0364328846879714,127.30498157800048,5743170560,0.03598219034618389,0.024474860168993473,0.03333190130069852,"[0.026533309370279312, 0.028369517996907234, 0.031566549092531204, 0.035528503358364105, 0.039844028651714325, 0.04427105933427811]",1.668508768081665,-0.07996828240250468,-0.07890745206604394,"[-0.08466605045077881, -0.08122814440510673, -0.07899007977604265, -0.0779774147394427, -0.07804055297761331, -0.07890745206604392]",0.027610744815319777,0.044842406176030636,0.61572844032795,0.056353189051151276,0.017564741661772132,0.32143574580550194,0.004415164119563997 +41,swe_2d,BlackboxCore,COMPLETED,485366,0.03425161784189264,66.77596297899981,2649445376,0.03348841982862127,0.022770278272219002,0.03168133506551385,"[0.028089020401239395, 0.028269369155168533, 0.03020133636891842, 0.033125609159469604, 0.03662499785423279, 0.0404689684510231]",1.4407397508621216,,,,,,,,,, diff --git a/sources/neuraloperator/.github/workflows/build_doc_dev.yml b/sources/neuraloperator/.github/workflows/build_doc_dev.yml new file mode 100644 index 0000000000000000000000000000000000000000..57b6e56f0bd2c4d916e24b3fa67111d301710d0f --- /dev/null +++ b/sources/neuraloperator/.github/workflows/build_doc_dev.yml @@ -0,0 +1,68 @@ +name: Build documentation +# Action adapted from https://github.com/tensorly/tensorly + +on: [push, pull_request] + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v3 + - name: Install Python + uses: actions/setup-python@v4 + with: + python-version: 3.13 + # - name: Install TensorLy and TensorLy-Torch dev + # run: | + # CWD=`pwd` + # echo 'Cloning repos in ${CWD}' + # mkdir git_repos + # cd git_repos + # git clone https://github.com/tensorly/tensorly + # cd tensorly + # python -m pip install -e . + # cd .. + # git clone https://github.com/tensorly/torch + # cd torch + # python -m pip install -e . + # cd ../.. + - name: Install dependencies + run: | + python -m pip install --upgrade pip + python -m pip install setuptools + python -m pip install torch torchvision --extra-index-url https://download.pytorch.org/whl/cpu + - name: Install package + run: | + python -m pip install -e .[all] + - name: Make doc + run: | + cd doc + make html + cd .. + - name: Push docs on main update + if: success() && github.ref == 'refs/heads/main' + run: | + # Add deploy key and clone through ssh + eval "$(ssh-agent -s)" + mkdir ~/.ssh + echo "${{ secrets.DOC_DEPLOY_PRIVATE_KEY }}" > ~/.ssh/id_rsa + chmod 600 ~/.ssh/id_rsa + ssh-keyscan -t rsa github.com + echo 'Documentation was successfully built, updating the website.' + # See https://github.community/t/github-actions-bot-email-address/17204/5 + git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com" + git config --global user.name "github-actions" + git clone "git@github.com:neuraloperator/neuraloperator.github.io.git" doc_folder + echo "-- Updating the content" + cd doc_folder + git rm -r dev/* + mkdir -p dev + echo "Copying to folder" + cp -r ../doc/build/html/* dev/ + echo "Pushing to git" + git add dev + git commit -m "Github action: auto-update." + git push --force origin main diff --git a/sources/neuraloperator/.github/workflows/deploy_pypi.yml b/sources/neuraloperator/.github/workflows/deploy_pypi.yml new file mode 100644 index 0000000000000000000000000000000000000000..ae98c4a837e3ea90e1e0ff2179854fabe7cd5dfa --- /dev/null +++ b/sources/neuraloperator/.github/workflows/deploy_pypi.yml @@ -0,0 +1,113 @@ +name: Deploy neuraloperator to Test-Pypi and Pypi 🐍 + +on: + push: + tags: + - '*' + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: 3.13 + - name: Install dependencies + run: | + python -m pip install --upgrade pip + python -m pip install setuptools + python -m pip install torch torchvision --extra-index-url https://download.pytorch.org/whl/cpu + - name: Install package + run: | + python -m pip install -e .[all] + pip install build + - name: Build a binary wheel and a source tarball + run: | + python -m build + - name: Store the distribution packages + uses: actions/upload-artifact@v4 + with: + name: python-package-distributions + path: dist/ + - name: Make doc + run: | + cd doc + make html + cd .. + if [ -d stable ]; then + git rm -r stable/* + fi + mkdir -p stable + echo "Copying to folder" + cp -r ./doc/build/html/* stable/ + - name: Store the built docs + uses: actions/upload-artifact@v4 + with: + name: built-docs + path: stable/ + + publish-to-pypi: + name: >- + Publish Python 🐍 distribution 📦 to PyPI + if: startsWith(github.ref, 'refs/tags/') # only publish to PyPI on tag pushes + needs: + - build + runs-on: ubuntu-latest + environment: + name: pypi + url: https://pypi.org/p/neuraloperator + permissions: + id-token: write # IMPORTANT: mandatory for trusted publishing + + steps: + - name: Download all the dists + uses: actions/download-artifact@v4 + with: + name: python-package-distributions + path: dist/ + - name: Publish distribution 📦 to PyPI + uses: pypa/gh-action-pypi-publish@release/v1 + + update-stable-docs: + name: >- + Publish Python 🐍 distribution 📦 to PyPI + if: startsWith(github.ref, 'refs/tags/') # only publish to PyPI on tag pushes + needs: + - build + - publish-to-pypi + runs-on: ubuntu-latest + steps: + - name: Download the prebuilt docs + uses: actions/download-artifact@v4 + with: + name: built-docs + path: stable/ + - name: Push docs + run: | + # Add deploy key and clone through ssh + eval "$(ssh-agent -s)" + mkdir ~/.ssh + echo "${{ secrets.DOC_DEPLOY_PRIVATE_KEY }}" > ~/.ssh/id_rsa + chmod 600 ~/.ssh/id_rsa + ssh-keyscan -t rsa github.com + echo 'Documentation was successfully built, updating the website.' + # See https://github.community/t/github-actions-bot-email-address/17204/5 + git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com" + git config --global user.name "github-actions" + git clone "git@github.com:neuraloperator/neuraloperator.github.io.git" doc_folder + echo "-- Updating the content" + cd doc_folder + if [ -d stable ]; then + git rm -r stable/* + fi + mkdir -p stable + echo "Copying to folder" + cp -r ../stable/* stable/ + echo "Pushing to git" + git add stable + git commit -m "Github action: auto-update." + git push --force origin main diff --git a/sources/neuraloperator/.github/workflows/test.yml b/sources/neuraloperator/.github/workflows/test.yml new file mode 100644 index 0000000000000000000000000000000000000000..1e245a216035d03685df02d2602f83e3a9ddf040 --- /dev/null +++ b/sources/neuraloperator/.github/workflows/test.yml @@ -0,0 +1,40 @@ +name: Test neuralop + +on: [push, pull_request] + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: Set up Python 3.9 + uses: actions/setup-python@v4 + with: + python-version: 3.9 + - name: Install TensorLy and TensorLy-Torch dev + run: | + CWD=`pwd` + echo 'Cloning repos in ${CWD}' + mkdir git_repos + cd git_repos + git clone https://github.com/tensorly/tensorly + cd tensorly + python -m pip install -e . + cd .. + git clone https://github.com/tensorly/torch + cd torch + python -m pip install -e . + cd ../.. + - name: Install Pytorch + run: | + python -m pip install --upgrade pip + python -m pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu + - name: Install package + run: | + python -m pip install --upgrade pip setuptools + python -m pip install -e .[dev] + - name: Test with pytest + run: | + pytest -vvv neuralop diff --git a/sources/neuraloperator/.gitignore b/sources/neuraloperator/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..cb51fff82612ec1603131b08b50eda4288ba6bc9 --- /dev/null +++ b/sources/neuraloperator/.gitignore @@ -0,0 +1,81 @@ +# weights and biases +.wandb/ +wandb_api_key.txt + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class +*.DS_Store +*.vscode + +# C extensions +*.so +*.py~ + +# Pycharm +.idea + +# vim temp files +*.swp + +# Sphinx doc +doc/_build/ +doc/source/auto_examples/ +doc/source/modules/generated/ + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg +.pytest_cache/ + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +#Ipython Notebook +.ipynb_checkpoints diff --git a/sources/neuraloperator/CODE_OF_CONDUCT.md b/sources/neuraloperator/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000000000000000000000000000000..b49ec9c2d83067acc7e9ba36b4030e65d974b35b --- /dev/null +++ b/sources/neuraloperator/CODE_OF_CONDUCT.md @@ -0,0 +1,78 @@ +# Code of Conduct + +All participants are expected to uphold this Code of Conduct to ensure a friendly and welcoming environment for everyone. + +Thank you for helping us maintain a welcoming and professional community! + + +## Introduction + +This project hosts diverse communities where participants work together across differences in language, location, nationality, and experience. While most disagreements can be resolved informally, harassment or disruptive behavior will not be tolerated. + +This Code applies to all participants, including (but not limited to) developers, contributors, meeting participants, and community members. + +--- + +## Statement of Intent + +This project is committed to maintaining a **positive, professional work environment**. This requires all participants to follow the rules below. Every individual shares responsibility for the tone and culture of the project. + +--- + +## Code + +Participants are expected to: + +- Treat each other with respect, professionalism, fairness, and sensitivity. +- Never harass, bully, or discriminate against others. +- Avoid demeaning, insulting, or offensive behavior or language. +- Communicate constructively and acknowledge others’ contributions. +- Be honest about qualifications and potential conflicts of interest. +- Respect privacy and confidentiality. +- Be culturally sensitive but not tolerant of disrespectful or inappropriate behavior. +- Promote and enforce this Code—especially if in a leadership role. +- Stay on topic and avoid spamming or off-topic discussion. +- Step down considerately, minimizing disruption when leaving or disengaging from the project. + +--- + +## Glossary + +- **Demeaning behavior**: Reduces another person’s dignity or respect. +- **Discrimination**: Prejudicial treatment based on identity or group membership (e.g., race, gender, religion). +- **Insulting behavior**: Treating others with scorn or disrespect. +- **Acknowledgement**: Credit given to contributors and sources. +- **Harassment**: Conduct that creates an intimidating or offensive environment. +- **Leadership position**: Chairs, maintainers, staff, board members. +- **Participant**: Anyone contributing, including developers, corporate reps, and public contributors. +- **Respect**: Polite and kind treatment of others in the community. +- **Sexual harassment**: Includes degrading images, suggestive conduct, offensive remarks, unwelcome contact, etc. +- **Unwelcome behavior**: Use your judgment. Ask yourself: + - Would I want this behavior directed at me or someone I care about? + - Could someone misinterpret this as harmful or inappropriate? + - Would I behave this way toward someone I respect or admire? + - Would I want this behavior published publicly? +- **Unwelcome sexual advance**: Any verbal or physical sexual conduct that: + - Is tied to conditions of participation or employment. + - Affects decisions impacting the individual. + - Creates an intimidating or hostile environment. +- **Workplace bullying**: Aggressive or unreasonable conduct that undermines work. +- **Work environment**: All forms of collaboration—email, chat, meetings, conferences, etc. + +--- + +## Incident Procedure + +To report a violation or appeal a decision, please contact: [neuraloperator@outlook.com](mailto:neuraloperator@outlook.com) + +Include relevant details (including links, screenshots, etc.). Every effort will be made to maintain a safe, collegial, and fair environment. The project reserves the right to take action, including removing individuals from participation, as necessary. + + + +--- + +## Credits + +This project follows the [Linux Foundation Code of Conduct](https://lfprojects.org/policies/code-of-conduct/) (version of September 14, 2017), which is itself based on the [W3C Code of Ethics and Professional Conduct](https://www.w3.org/Consortium/cepc/), with additional elements from the Cloud Foundry Code of Conduct, and the Hyperledger Project Code of Conduct. + + diff --git a/sources/neuraloperator/CONTRIBUTING.md b/sources/neuraloperator/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..d4150fadc96802e737e50633f4ac28ab92fb1fe2 --- /dev/null +++ b/sources/neuraloperator/CONTRIBUTING.md @@ -0,0 +1,311 @@ +# Contributing to NeuralOperator + +We welcome new contributions to the library! Our mission for NeuralOperator is to provide access to well-documented, robust implementations of neural operator methods from foundations to the cutting edge. The library is primarily intended for methods that directly relate to operator learning: new architectures, meta-algorithms, training methods and benchmark datasets. We are also interested in integrating interactive examples that showcase operator learning in action on small sample problems. + +If your work provides one of the above, we would be thrilled to integrate it into the library. Otherwise, if your work simply relies on a version of the NeuralOperator codebase, we recommend publishing your code separately using a procedure outlined below. + +Thank you for contributing to NeuralOperator! Your contributions help make this library better for the entire scientific machine learning community. + + +## Table of Contents + +- [Development Setup](#development-setup) +- [Development Workflow](#development-workflow) +- [Development Guidelines](#development-guidelines) +- [Adding a New Model or Layer](#adding-a-new-model-or-layer) +- [Getting Help](#getting-help) +- [Publishing Code Built on the Library](#publishing-code-built-on-the-library) +- [License](#license) + +  + +## Development Setup + +### 1. Fork and Clone the Repository + +1. **Fork the repository** on GitHub by clicking the "Fork" button + +2. **Clone the library and connect your fork**: + ```bash + git clone https://github.com/neuraloperator/neuraloperator.git + cd neuraloperator + git remote rename origin upstream + git remote add origin https://github.com//neuraloperator.git + git remote -v + ``` + This should show: + ``` + origin https://github.com//neuraloperator.git (fetch) + origin https://github.com//neuraloperator.git (push) + upstream https://github.com/neuraloperator/neuraloperator.git (fetch) + upstream https://github.com/neuraloperator/neuraloperator.git (push) + ``` + +### 2. Set Up Development Environment + +1. **Create a virtual environment**: + ```bash + python -m venv venv + source venv/bin/activate # On Windows: venv\Scripts\activate + ``` + +2. **Install development dependencies**: + ```bash + pip install -e .[dev] + # OR + pip install neuraloperator[dev] + ``` + + +  + +## Development Workflow + +### 1. Create a Branch and Make Changes + +```bash +# Create and switch to a new branch +git checkout -b feature/your-feature-name + +# Make your changes +# ... edit files ... + +# Stage and commit your changes +git add . +git commit -m "Add: brief description of your changes + +- More detailed explanation of what you changed +- Why you made these changes +- Any relevant context" + +# Push to your fork +git push -u origin feature/your-feature-name +``` + +### 2. Write Tests + +**Always add tests for new functionality!** + +- **For models**: Add tests in `neuralop/models/tests/test_your_model.py` +- **For layers**: Add tests in `neuralop/layers/tests/test_your_layer.py` +- **For utilities**: Add tests in the appropriate test directory + +**Example test structure:** +```python +import pytest +import torch +from neuralop.models import YourModel + +class TestYourModel: + def test_forward_pass(self): + model = YourModel(...) + x = torch.randn(1, 3, 32, 32) + output = model(x) + assert output.shape == expected_shape + + def test_gradient_flow(self): + # Test that gradients flow properly + pass +``` + +### 3. Run Tests and Quality Checks + +```bash +# Run all tests +pytest neuralop + +# Run tests with verbose output +pytest neuralop -v + +# Run specific test file +pytest neuralop/models/tests/test_your_model.py + +# Format code +black . +``` + +### 4. Submit a Pull Request + +Go to your fork on GitHub and click "Compare & pull request". + +Ensure your PR description clearly communicates what you have changed or added. + +  + +## Development Guidelines + +### Code Style +- **Follow PEP 8** style guidelines for Python code +- **Use meaningful names** for variables, functions, and classes +- **Write clear docstrings** using NumPy docstring format +- **Add type hints** where appropriate + +### Code Formatting +Before submitting, ensure your code follows our style guide: + +```bash +# Format with black +black . +``` + +Validate every update made by the ``black`` command + +### Testing Requirements +- **All new code must have tests** +- **Run the full test suite** before submitting PRs +- **Use descriptive test names** that explain what is being tested +- **Test both normal operation and edge cases** +- **Aim for complete code coverage** for new functionality + +### Documentation Standards +- **Update relevant documentation** when adding new features +- **Include clear examples** in docstrings +- **Add interactive examples** to the `examples/` directory when possible +- **Follow existing documentation style** and format +- **Include paper references** and mathematical formulations when relevant + +### Building Documentation +The HTML documentation is built using Sphinx: + +```bash +cd doc +make html +``` + +This builds the docs in `./doc/build/html`. Note that documentation requires additional dependencies from `./doc/requirements_doc.txt`. + +To view documentation locally: +```bash +cd doc/build/html +python -m http.server 8000 +# Visit http://localhost:8000 +``` + +### Git Best Practices +- **Write clear, descriptive commit messages** +- **Keep commits focused and atomic** (one logical change per commit) +- **Rebase your branch** on main before submitting PRs +- **Use conventional commit format** when possible (feat:, fix:, docs:, etc.) + +  + +## Adding a New Model or Layer + +We welcome various types of contributions: + +- **Bug fixes** - Report and fix bugs +- **New features** - Add new models, layers, or datasets +- **Examples** - Create new examples or improve existing ones +- **Performance** - Optimize existing code + +### Adding a New Neural Operator Model + +To add a new neural operator model: + +1. **Create a new file** in `neuralop/models/your_model.py` +2. **Implement the model** as a subclass of `BaseModel` +3. **Add comprehensive tests** in `neuralop/models/tests/test_your_model.py` +4. **Update imports** in the appropriate `__init__.py` files +5. **Add documentation** with examples and mathematical formulations + +**Example structure:** +```python +from neuralop.models import BaseModel + +class YourModel(BaseModel): + """Your model docstring here.""" + + def __init__(self, ...): + super().__init__() + # Your implementation + + def forward(self, x): + # Your forward pass + return x +``` + +### Adding a New Layer + +To add a new layer: + +1. **Create a new file** in `neuralop/layers/your_layer.py` +2. **Ensure the layer** is a subclass of `torch.nn.Module` +3. **Add comprehensive tests** in `neuralop/layers/tests/test_your_layer.py` +4. **Update imports** in the appropriate `__init__.py` files + +> **💡 Pro Tip**: For bonus points, add an interactive example featuring your new method to `./examples`. This helps both us and you: the simpler it is for new users to understand and adapt your method, the more visibility it will get! + +  + +## Getting Help + +### Before Asking for Help +1. **Check the documentation** and existing issues +2. **Search GitHub issues** for similar problems +3. **Provide a minimal reproducible example** +4. **Include error messages** and stack traces +5. **Specify your environment** (OS, Python version, PyTorch version) + +### Contact Methods +- **GitHub Issues**: Create an issue for bugs or feature requests +- **GitHub Discussions**: Use for questions and ideas +- **Documentation**: Check the [official documentation](https://neuraloperator.github.io/) + +  + +## Publishing Code Built on the Library + +If you plan to use `neuralop` as the base of a project, we suggest the following workflow: + +### 1. Set Up Clean Environment +```bash +python -m venv my_project_env +source my_project_env/bin/activate +``` + +### 2. Install NeuralOperator + +**Option A: Latest PyPI release** +```bash +pip install neuralop +``` + +**Option B: From specific commit (for latest features)** +```bash +# Find commit hash from GitHub commit history +pip install git+https://github.com/neuraloperator/neuraloperator.git@ +``` + +### 3. Subclass Functionality + +Create your own models by subclassing: + +```python +from neuralop.models import FNO + +class MyCustomFNO(FNO): + def __init__(self, custom_param, **kwargs): + super().__init__(**kwargs) + self.custom_param = custom_param + # Add your custom layers here + + def forward(self, x): + # Preprocessing + x = self.custom_preprocessing(x) + + # Use the base FNO forward pass + x = super().forward(x) + + # Postprocessing + x = self.custom_postprocessing(x) + + return x +``` + +  + +--- + +## License + +By contributing to NeuralOperator, you agree that your contributions will be licensed as described in the `LICENSE` file in the root directory of this source tree. diff --git a/sources/neuraloperator/LICENSE b/sources/neuraloperator/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..5637378e3734ad545887a7e782f1cf22e4ced42f --- /dev/null +++ b/sources/neuraloperator/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 NeuralOperator developers + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/sources/neuraloperator/README.rst b/sources/neuraloperator/README.rst new file mode 100644 index 0000000000000000000000000000000000000000..4c6d0dba1ce2c93fbd5fea9ed1ebe77c02cf6860 --- /dev/null +++ b/sources/neuraloperator/README.rst @@ -0,0 +1,172 @@ +.. image:: https://img.shields.io/pypi/v/neuraloperator + :target: https://pypi.org/project/neuraloperator/ + :alt: PyPI + +.. image:: https://github.com/NeuralOperator/neuraloperator/actions/workflows/test.yml/badge.svg + :target: https://github.com/NeuralOperator/neuraloperator/actions/workflows/test.yml + + +############################################### +NeuralOperator: Learning in Infinite Dimensions +############################################### + +NeuralOperator is a comprehensive PyTorch library for learning neural operators, +containing the official implementation of Fourier Neural Operators and other neural operator architectures. + +NeuralOperator is part of the PyTorch Ecosystem, check the PyTorch `announcement `_! + + +Unlike regular neural networks, neural operators enable learning mapping between function spaces, +and this library provides all of the tools to do so on your own data. Neural operators are +resolution invariant, so your trained operator can be applied on data of any resolution. + +Checkout the `documentation `_ and our `practical guide `_ for more information! + +============ +Installation +============ + +Just clone the repository and install locally (in editable mode so changes in the code are +immediately reflected without having to reinstall): + +.. code:: + + git clone https://github.com/NeuralOperator/neuraloperator + cd neuraloperator + pip install -e . + pip install -r requirements.txt + +You can also pip install the most recent stable release of the library +on `PyPI `_: + + +.. code:: + + pip install neuraloperator + + +========== +Quickstart +========== + +After you have installed the library, you can start training operators seamlessly: + +.. code-block:: python + + from neuralop.models import FNO + + operator = FNO(n_modes=(64, 64), + hidden_channels=64, + in_channels=2, + out_channels=1) + +Tensorization is also available: you can improve the previous models +by simply using a Tucker Tensor FNO with fewer parameters: + +.. code-block:: python + + from neuralop.models import TFNO + + operator = TFNO(n_modes=(64, 64), + hidden_channels=64, + in_channels=2, + out_channels=1, + factorization='tucker', + implementation='factorized', + rank=0.1) + +This will use a Tucker factorization of the weights. The forward pass +will be efficient by contracting directly the inputs with the factors +of the decomposition. The Fourier layers will have 10% of the parameters +of an equivalent, dense Fourier Neural Operator! + +To use W&B logging features, simply create a file in ``neuraloperator/config`` +called ``wandb_api_key.txt`` and paste your W&B API key there. + + +============ +Contributing +============ + +NeuralOperator is 100% open-source, and we welcome contributions from the community! + +Our mission for NeuralOperator is to provide access to well-documented, robust implementations of +neural operator methods from foundations to the cutting edge, including new architectures, meta-algorithms, training methods and benchmark datasets. +We are also interested in integrating interactive examples that showcase operator +learning in action on small sample problems. + +If your work provides one of the above, we would be thrilled to integrate it into the library. +Otherwise, if your work simply relies on a version of the NeuralOperator codebase, we recommend +publishing your code in a separate repository. + +If you spot a bug or would like to see a new feature, +please report it on our `issue tracker `_ +or open a `Pull Request `_. + +For detailed development setup, testing, and contribution guidelines, please refer to our `Contributing Guide `_. + + +=============== +Code of Conduct +=============== + +All participants are expected to uphold the `Code of Conduct `_ to ensure a friendly and welcoming environment for everyone. + + +===================== +Citing NeuralOperator +===================== + +If you use NeuralOperator in an academic paper, please cite [1]_:: + + @article{kossaifi2025librarylearningneuraloperators, + author = {Jean Kossaifi and + Nikola Kovachki and + Zongyi Li and + David Pitt and + Miguel Liu-Schiaffini and + Robert Joseph George and + Boris Bonev and + Kamyar Azizzadenesheli and + Julius Berner and + Valentin Duruisseaux and + Anima Anandkumar}, + title = {A Library for Learning Neural Operators}, + journal = {arXiv preprint arXiv:2412.10354}, + year = {2025}, + } + +and consider citing [2]_ and [3]_:: + + @article{duruisseaux2025guide, + author = {Valentin Duruisseaux and + Jean Kossaifi and + Anima Anandkumar}, + title = {Fourier Neural Operators Explained: A Practical Perspective}, + journal = {arXiv preprint arXiv:2512.01421}, + year = {2025}, + } + + @article{kovachki2023neuraloperator, + author = {Nikola Kovachki and + Zongyi Li and + Burigede Liu and + Kamyar Azizzadenesheli and + Kaushik Bhattacharya and + Andrew Stuart and + Anima Anandkumar}, + title = {Neural Operator: Learning Maps Between Function Spaces with Applications to PDEs}, + journal = {JMLR}, + volume = {24}, + number = {1}, + articleno = {89}, + numpages = {97}, + year = {2023}, + } + + +.. [1] Kossaifi, J., Kovachki, N., Li, Z., Pitt, D., Liu-Schiaffini, M., Duruisseaux, V., George, R., Bonev, B., Azizzadenesheli, K., Berner, J., and Anandkumar, A., "A Library for Learning Neural Operators", 2025. https://arxiv.org/abs/2412.10354. + +.. [2] Duruisseaux, V., Kossaifi, J., and Anandkumar, A., "Fourier Neural Operators Explained: A Practical Perspective", 2025. https://arxiv.org/abs/2512.01421. + +.. [3] Kovachki, N., Li, Z., Liu, B., Azizzadenesheli, K., Bhattacharya, K., Stuart, A., and Anandkumar, A., “Neural Operator: Learning Maps Between Function Spaces with Applications to PDEs”, JMLR, 24(1):89, 2023. https://arxiv.org/abs/2108.08481. diff --git a/sources/neuraloperator/config/__init__.py b/sources/neuraloperator/config/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/sources/neuraloperator/config/burgers_config.py b/sources/neuraloperator/config/burgers_config.py new file mode 100644 index 0000000000000000000000000000000000000000..182f1ee33b70c7dda1a1a8b445503b2694bcae94 --- /dev/null +++ b/sources/neuraloperator/config/burgers_config.py @@ -0,0 +1,48 @@ +from typing import Any, List, Optional + +from zencfg import ConfigBase +from .distributed import DistributedConfig +from .models import ModelConfig, FNO_Small2d +from .opt import OptimizationConfig, PatchingConfig +from .wandb import WandbConfig + + +class BurgersDatasetConfig(ConfigBase): + folder: str = "neuralop/data/datasets/data/" + batch_size: int = 16 + n_train: int = 800 + test_batch_sizes: List[int] = [16] + n_tests: List[int] = [400] + # full res is 128x101. We redistribute a mini version at 16x17 + spatial_length: int = 16 + temporal_length: int = 17 + temporal_subsample: Optional[int] = None + encode_input: bool = False + encode_output: bool = False + include_endpoint: List[bool] = [True, False] + + +class BurgersOptConfig(ConfigBase): + n_epochs: int = 10000 + training_loss: str = "l2" + testing_loss: str = "l2" + learning_rate: float = 1e-4 + weight_decay: float = 1e-4 + eval_interval: int = 1 + mixed_precision: bool = False + scheduler: str = "ReduceLROnPlateau" # Or 'CosineAnnealingLR' OR 'ReduceLROnPlateau' + scheduler_patience: int = 100 # For ReduceLROnPlateau only + step_size: int = 60 + gamma: float = 0.5 + + +class Default(ConfigBase): + n_params_baseline: Optional[Any] = None + verbose: bool = True + arch: str = "fno" + distributed: DistributedConfig = DistributedConfig() + model: ModelConfig = FNO_Small2d() + opt: BurgersOptConfig = BurgersOptConfig() + data: BurgersDatasetConfig = BurgersDatasetConfig() + patching: PatchingConfig = PatchingConfig() + wandb: WandbConfig = WandbConfig() diff --git a/sources/neuraloperator/config/burgers_pino_config.py b/sources/neuraloperator/config/burgers_pino_config.py new file mode 100644 index 0000000000000000000000000000000000000000..08eae2f0e30b4b580b510efd0c69d7b26f789856 --- /dev/null +++ b/sources/neuraloperator/config/burgers_pino_config.py @@ -0,0 +1,49 @@ +from typing import Any, List, Optional + +from zencfg import ConfigBase +from .distributed import DistributedConfig +from .models import ModelConfig, FNO_Small2d +from .opt import OptimizationConfig, PatchingConfig +from .wandb import WandbConfig + + +class BurgersDatasetConfig(ConfigBase): + folder: str = "neuralop/data/datasets/data/" + batch_size: int = 16 + n_train: int = 800 + test_batch_sizes: List[int] = [16] + n_tests: List[int] = [400] + # full res is 128x101. We redistribute a mini version at 16x17 + spatial_length: int = 16 + temporal_length: int = 17 + temporal_subsample: Optional[int] = None + encode_input: bool = False + encode_output: bool = False + include_endpoint: List[bool] = [True, False] + + +class BurgersOptConfig(OptimizationConfig): + n_epochs: int = 10000 + training_loss: List[str] = ["equation", "ic", "l2"] # ["equation", "l2"... or "ic"...] + testing_loss: str = "l2" + learning_rate: float = 1e-4 + weight_decay: float = 1e-4 + eval_interval: int = 1 + mixed_precision: bool = False + scheduler: str = "ReduceLROnPlateau" # Or 'CosineAnnealingLR' OR 'ReduceLROnPlateau' + scheduler_patience: int = 100 # For ReduceLROnPlateau only + step_size: int = 60 + gamma: float = 0.5 + loss_aggregator: str = "relobralo" # 'relobralo', 'softadapt' + + +class Default(ConfigBase): + n_params_baseline: Optional[Any] = None + verbose: bool = True + arch: str = "fno" + distributed: DistributedConfig = DistributedConfig() + model: ModelConfig = FNO_Small2d() + opt: OptimizationConfig = BurgersOptConfig() + data: BurgersDatasetConfig = BurgersDatasetConfig() + patching: PatchingConfig = PatchingConfig() + wandb: WandbConfig = WandbConfig() diff --git a/sources/neuraloperator/config/burgers_rno_config.py b/sources/neuraloperator/config/burgers_rno_config.py new file mode 100644 index 0000000000000000000000000000000000000000..6026e43fc65855ba6e2b74e7eb6910fde7446fd4 --- /dev/null +++ b/sources/neuraloperator/config/burgers_rno_config.py @@ -0,0 +1,58 @@ +from typing import Any, List, Optional + +from zencfg import ConfigBase +from .distributed import DistributedConfig +from .opt import OptimizationConfig, PatchingConfig +from .wandb import WandbConfig +from .models import ModelConfig + + +class BurgersDatasetConfig(ConfigBase): + folder: str = "neuralop/data/datasets/data/" + batch_size: int = 16 + n_train: int = 800 + test_batch_sizes: List[int] = [16] + n_tests: List[int] = [400] + spatial_length: int = 16 + temporal_length: int = 17 + temporal_subsample: Optional[int] = None + encode_input: bool = False + encode_output: bool = False + include_endpoint: List[bool] = [True, False] + + +class BurgersOptConfig(ConfigBase): + n_epochs: int = 10000 + training_loss: str = "l2" + testing_loss: str = "l2" + learning_rate: float = 1e-3 + weight_decay: float = 0.0 + eval_interval: int = 1 + mixed_precision: bool = False + scheduler: str = "StepLR" + scheduler_patience: int = 100 + step_size: int = 60 + gamma: float = 0.5 + + +class RNO_Small1d(ModelConfig): + model_arch: str = "rno" + data_channels: int = 1 + out_channels: int = 1 + # 1D spatial, use small number of modes + n_modes: List[int] = [8] + hidden_channels: int = 32 + n_layers: int = 2 + rno_skip: bool = False + + +class Default(ConfigBase): + n_params_baseline: Optional[Any] = None + verbose: bool = True + arch: str = "rno" + distributed: DistributedConfig = DistributedConfig() + model: RNO_Small1d = RNO_Small1d() + opt: BurgersOptConfig = BurgersOptConfig() + data: BurgersDatasetConfig = BurgersDatasetConfig() + patching: PatchingConfig = PatchingConfig() + wandb: WandbConfig = WandbConfig() diff --git a/sources/neuraloperator/config/darcy_config.py b/sources/neuraloperator/config/darcy_config.py new file mode 100644 index 0000000000000000000000000000000000000000..436fd0f99b807e20ec74cb67040465a000b0b7ec --- /dev/null +++ b/sources/neuraloperator/config/darcy_config.py @@ -0,0 +1,42 @@ +from typing import Any, List, Optional + +from zencfg import ConfigBase +from .distributed import DistributedConfig +from .models import ModelConfig, FNO_Small2d +from .opt import OptimizationConfig, PatchingConfig +from .wandb import WandbConfig + + +class DarcyOptConfig(OptimizationConfig): + n_epochs: int = 300 + learning_rate: float = 5e-3 + training_loss: str = "h1" + weight_decay: float = 1e-4 + scheduler: str = "StepLR" + step_size: int = 60 + gamma: float = 0.5 + + +class DarcyDatasetConfig(ConfigBase): + folder: str = "~/data/darcy/" + batch_size: int = 8 + n_train: int = 1000 + train_resolution: int = 16 + n_tests: List[int] = [100, 50] + test_resolutions: List[int] = [16, 32] + test_batch_sizes: List[int] = [16, 16] + encode_input: bool = True + encode_output: bool = True + download: bool = True + + +class Default(ConfigBase): + n_params_baseline: Optional[Any] = None + verbose: bool = True + arch: str = "fno" + distributed: DistributedConfig = DistributedConfig() + model: ModelConfig = FNO_Small2d() + opt: OptimizationConfig = DarcyOptConfig() + data: DarcyDatasetConfig = DarcyDatasetConfig() + patching: PatchingConfig = PatchingConfig() + wandb: WandbConfig = WandbConfig() diff --git a/sources/neuraloperator/config/default_config.py b/sources/neuraloperator/config/default_config.py new file mode 100644 index 0000000000000000000000000000000000000000..d322ae91c9a08492b84318290f0f03f05ac0fb29 --- /dev/null +++ b/sources/neuraloperator/config/default_config.py @@ -0,0 +1,111 @@ +from typing import Any, List, Optional + +from zencfg import ConfigBase + + +class Distributed(ConfigBase): + use_distributed: bool = True + wireup_info: str = "mpi" + wireup_store: str = "tcp" + model_parallel_size: int = 2 + seed: int = 666 + + +class FNO(ConfigBase): + n_modes: List[int] = [64, 64] # Default to 2D: [height, width] + width: int = 64 + hidden_channels: int = 256 + n_layers: int = 4 + domain_padding: float = 0.078125 + norm: Optional[Any] = None + fno_skip: str = "linear" + use_channel_mlp: int = 0 + channel_mlp: Optional[Any] = None + channel_mlp_expansion: float = 0.5 + channel_mlp_dropout: int = 0 + separable: bool = False + factorization: Optional[Any] = None + rank: float = 1.0 + fixed_rank_modes: Optional[Any] = None + + +class TFNO(ConfigBase): + n_modes: List[int] = [64, 64] + width: int = 64 + hidden_channels: int = 256 + n_layers: int = 4 + domain_padding: float = 0.078125 + norm: Optional[Any] = None + fno_skip: str = "linear" + use_channel_mlp: int = 0 + channel_mlp: Optional[Any] = None + channel_mlp_expansion: float = 0.5 + channel_mlp_dropout: int = 0 + separable: bool = False + factorization: str = "Tucker" + rank: float = 0.1 + fixed_rank_modes: Optional[Any] = None + + +class Opt(ConfigBase): + n_epochs: int = 500 + learning_rate: float = 1e-3 + training_loss: str = "h1" + weight_decay: float = 1e-4 + mixed_precision: bool = False + scheduler_T_max: int = 500 + scheduler_patience: int = 5 + scheduler: str = "StepLR" + step_size: int = 100 + gamma: float = 0.5 + + +class Data(ConfigBase): + folder: str = "/data/navier_stokes/" + batch_size: int = 16 + n_train: int = 10000 + train_resolution: int = 128 + n_tests: List[int] = [2000, 1000] + test_resolutions: List[int] = [128, 1024] + test_batch_sizes: List[int] = [16, 4] + encode_input: bool = True + encode_output: bool = False + num_workers: int = 0 + pin_memory: bool = False + persistent_workers: bool = False + + +class Patching(ConfigBase): + levels: int = 1 + padding: int = 16 + stitching: bool = True + + +class Wandb(ConfigBase): + log: bool = False + name: Optional[Any] = None + group: str = "wandb_group" + + +class Default(ConfigBase): + n_params_baseline: Optional[Any] = None + verbose: bool = True + arch: str = "fno" + distributed: Distributed = Distributed() + fno: FNO = FNO() + opt: Opt = Opt() + data: Data = Data() + patching: Patching = Patching() + wandb: Wandb = Wandb() + + +class Original_Fno(ConfigBase): + arch: str = "tfno" + tfno: TFNO = TFNO() + wandb: Wandb = Wandb() + + +class Distributed_Mg_Tucker(ConfigBase): + tfno: TFNO = TFNO() + distributed: Distributed = Distributed() + patching: Patching = Patching() diff --git a/sources/neuraloperator/config/distributed.py b/sources/neuraloperator/config/distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..268c025e6a7285f5fe892e9bd8e6fb2f9e591ef0 --- /dev/null +++ b/sources/neuraloperator/config/distributed.py @@ -0,0 +1,25 @@ +from typing import List, Any, Optional + +from zencfg import ConfigBase + + +class DistributedConfig(ConfigBase): + """ + DistributedConfig provides config options for multi-GPU + and multi-node settings. Our current setup depends on ``torchrun``-based + Elastic Launch and the ``nccl`` distributed backend for communication. + + Parameters + ---------- + use_distributed: bool, default False + Whether to use distributed data/model parallelism + model_parallel_size: Optional[int], default 1 + number of GPUs across which to spread model layers, + by default 1. If 1, does not perform **any** model parallelism. + seed: Optional[int] = None + special distributed random torch seed for reproducibility. + """ + + use_distributed: bool = False + model_parallel_size: Optional[int] = 1 + seed: Optional[int] = None diff --git a/sources/neuraloperator/config/fnogno_carcfd_config.py b/sources/neuraloperator/config/fnogno_carcfd_config.py new file mode 100644 index 0000000000000000000000000000000000000000..b612efd2deb8171b6b8f08601c3038344f77d82f --- /dev/null +++ b/sources/neuraloperator/config/fnogno_carcfd_config.py @@ -0,0 +1,36 @@ +from typing import Any, List, Optional + +from zencfg import ConfigBase +from .distributed import DistributedConfig +from .models import ModelConfig, FNOGNO_Small3d +from .opt import OptimizationConfig, PatchingConfig +from .wandb import WandbConfig + + +class CarCFDDatasetConfig(ConfigBase): + root: str = "~/data/car-pressure-data/processed-car-pressure-data" + sdf_query_resolution: int = 32 + n_train: int = 500 + n_test: int = 111 + download: bool = True + + +class CarCFDOptConfig(OptimizationConfig): + n_epochs: int = 300 + learning_rate: float = 5e-3 + training_loss: str = "l2" + weight_decay: float = 1e-4 + scheduler: str = "StepLR" + step_size: int = 60 + gamma: float = 0.5 + + +class Default(ConfigBase): + n_params_baseline: Optional[Any] = None + verbose: bool = True + distributed: DistributedConfig = DistributedConfig() + model: ModelConfig = FNOGNO_Small3d() + opt: OptimizationConfig = CarCFDOptConfig() + data: CarCFDDatasetConfig = CarCFDDatasetConfig() + patching: PatchingConfig = PatchingConfig() + wandb: WandbConfig = WandbConfig() diff --git a/sources/neuraloperator/config/gino_carcfd_config.py b/sources/neuraloperator/config/gino_carcfd_config.py new file mode 100644 index 0000000000000000000000000000000000000000..6beec6a40600f4737ac46b55b41b9f5835510bd0 --- /dev/null +++ b/sources/neuraloperator/config/gino_carcfd_config.py @@ -0,0 +1,37 @@ +from typing import Any, List, Optional + +from zencfg import ConfigBase +from .distributed import DistributedConfig +from .models import ModelConfig, GINO_Small3d +from .opt import PatchingConfig +from .wandb import WandbConfig + + +class CarCFDDatasetConfig(ConfigBase): + root: str = "~/data/car-pressure-data/processed-car-pressure-data" + sdf_query_resolution: int = 32 + n_train: int = 500 + n_test: int = 111 + download: bool = True + + +class CarCFDOptConfig(ConfigBase): + n_epochs: int = 301 + learning_rate: float = 1e-3 + training_loss: str = "l2" + testing_loss: str = "l2" + weight_decay: float = 1e-4 + scheduler: str = "StepLR" + step_size: int = 50 + gamma: float = 0.5 + + +class Default(ConfigBase): + n_params_baseline: Optional[Any] = None + verbose: bool = True + distributed: DistributedConfig = DistributedConfig() + model: ModelConfig = GINO_Small3d() + opt: ConfigBase = CarCFDOptConfig() + data: CarCFDDatasetConfig = CarCFDDatasetConfig() + patching: PatchingConfig = PatchingConfig() + wandb: WandbConfig = WandbConfig() # default empty diff --git a/sources/neuraloperator/config/models.py b/sources/neuraloperator/config/models.py new file mode 100644 index 0000000000000000000000000000000000000000..8bc428bce083ecafda64d5d6f9d148a317dff694 --- /dev/null +++ b/sources/neuraloperator/config/models.py @@ -0,0 +1,235 @@ +from typing import List, Literal, Optional, Any +from zencfg import ConfigBase + + +class ModelConfig(ConfigBase): + arch: str + data_channels: int + out_channels: int + + +class FNOConfig(ModelConfig): + model_arch: str = "fno" + data_channels: int + out_channels: int + n_modes: List[int] + hidden_channels: int + lifting_channel_ratio: int = 2 + projection_channel_ratio: int = 4 + n_layers: int = 4 + domain_padding: float = 0.0 + norm: str = "None" + fno_skip: str = "linear" + implementation: str = "factorized" + use_channel_mlp: bool = True + channel_mlp_expansion: float = 0.5 + channel_mlp_dropout: float = 0 + separable: bool = False + factorization: str = "None" + rank: float = 1.0 + fixed_rank_modes: bool = False + stabilizer: str = "None" + + +class SimpleFNOConfig(FNOConfig): + """ + SimpleFNOConfig: a basic FNO config that provides access to only + the most important FNO parameters. + """ + + data_channels: int + out_channels: int + n_modes: List[int] + hidden_channels: int + projection_channel_ratio: int + + +class FNO_Small2d(SimpleFNOConfig): + """ + FNO_Small2d: a basic, small FNO for 2d problems. + """ + + data_channels: int = 1 + out_channels: int = 1 + n_modes: List[int] = [16, 16] + hidden_channels: int = 24 + projection_channel_ratio: int = 2 + + +class FNO_Medium2d(SimpleFNOConfig): + """ + FNO_Medium2d: a basic, medium-sized FNO for 2d problems. + """ + + data_channels: int = 1 + out_channels: int = 1 + n_modes: List[int] = [64, 64] + hidden_channels: int = 64 + projection_channel_ratio: int = 4 + + +class FNO_Large2d(SimpleFNOConfig): + """ + FNO_Large2d: a large FNO for 2d problems. + """ + + data_channels: int = 1 + out_channels: int = 1 + n_modes: List[int] = [64, 64] + hidden_channels: int = 128 + projection_channel_ratio: int = 2 + + +class FNO_Huge2d(SimpleFNOConfig): + """ + FNO_Huge2d: a giant FNO for 2d problems. + + Note that this will likely be too large for most single-GPU local settings, + and should be paired with tensor factorization, low-rank/sparse optimization + via TensorGRaD, or some other means of reducing memory overhead. + """ + + data_channels: int = 1 + out_channels: int = 1 + n_modes: List[int] = [128, 128] + hidden_channels: int = 128 + projection_channel_ratio: int = 2 + + +class FNO_Medium3d(SimpleFNOConfig): + """ + FNO_Medium3d: a medium FNO for 3d problems. + """ + + data_channels: int = 1 + out_channels: int = 1 + n_modes: List[int] = [32, 32, 32] + hidden_channels: int = 64 + projection_channel_ratio: int = 4 + + +class FNOGNOConfig(ModelConfig): + model_arch: str = "fnogno" + data_channels: int + out_channels: int + gno_coord_dim: int + gno_coord_embed_dim: int + gno_radius: float + gno_transform_type: str + fno_n_modes: List[int] + fno_hidden_channels: int + fno_use_channel_mlp: bool = True + fno_norm: str = "instance_norm" + fno_ada_in_features: int = 32 + fno_factorization: str = "tucker" + fno_rank: float = 1.0 + fno_domain_padding: float = 0.125 + fno_use_channel_mlp: bool = True + fno_channel_mlp_expansion: float = 1.0 + fno_resolution_scaling_factor: int = 1 + + +class FNOGNO_Small3d(FNOGNOConfig): + data_channels: int = 1 + out_channels: int = 1 + gno_coord_dim: int = 3 + gno_coord_embed_dim: int = 16 + gno_radius: float = 0.033 + gno_transform_type: str = "linear" + fno_n_modes: List[int] = [16, 16, 16] + fno_hidden_channels: int = 64 + fno_use_channel_mlp: bool = True + fno_rank: float = 0.4 + fno_domain_padding: float = 0.125 + + +class GINOConfig(ModelConfig): + model_arch: str = "gino" # all GINO configs must use this + data_channels: int + out_channels: int + latent_feature_channels: Optional[int] = None + gno_coord_dim: int = 3 + gno_coord_embed_dim: int = 16 + gno_radius: float = 0.033 + in_gno_transform_type: str = "linear" + out_gno_transform_type: str = "linear" + gno_pos_embed_type: str = "nerf" + gno_weighting_function: Optional[str] = None + gno_weight_function_scale: Optional[float] = None + fno_n_modes: List[int] = [16, 16, 16] + fno_hidden_channels: int = 64 + fno_use_channel_mlp: bool = True + fno_norm: str = "instance_norm" + fno_ada_in_features: int = 32 + fno_factorization: str = "tucker" + fno_rank: float = 0.4 + fno_domain_padding: float = 0.125 + fno_channel_mlp_expansion: float = 1.0 + fno_resolution_scaling_factor: int = 1 + + +class GINO_Small3d(GINOConfig): + data_channels: int = 0 + out_channels: int = 1 + latent_feature_channels: Optional[int] = 1 + gno_coord_dim: int = 3 + gno_coord_embed_dim: int = 16 + gno_radius: float = 0.033 + + +class GINO_Poisson2d(GINOConfig): + data_channels: int = 3 + out_channels: int = 1 + projection_channel_ratio: int = 4 + gno_coord_dim: int = 2 + in_gno_pos_embed_type: Optional[Any] = None + out_gno_pos_embed_type: str = "transformer" + gno_embed_channels: int = 16 + gno_embed_max_positions: int = 600 + gno_use_torch_scatter: bool = True + in_gno_radius: float = 0.16 + out_gno_radius: float = 0.175 + in_gno_transform_type: str = "linear" + out_gno_transform_type: str = "linear" + gno_reduction: str = "mean" + gno_weighting_function: str = "half_cos" + gno_weight_function_scale: float = 0.030625 + gno_use_open3d: bool = False + in_gno_channel_mlp_hidden_layers: List[int] = [256, 512, 256] + out_gno_channel_mlp_hidden_layers: List[int] = [512, 1024, 512] + in_gno_tanh: Optional[Any] = None + out_gno_tanh: Optional[Any] = None + fno_n_modes: List[int] = [20, 20] + fno_hidden_channels: int = 64 + fno_lifting_channel_ratio: int = 4 + fno_n_layers: int = 4 + fno_use_channel_mlp: bool = True + fno_channel_mlp_expansion: float = 0.5 + fno_norm: str = "group_norm" + fno_ada_in_features: int = 8 + fno_factorization: Optional[Any] = None + fno_rank: float = 0.8 + fno_domain_padding: float = 0.0 + + +class OTNOConfig(ModelConfig): + model_arch: str = "otno" + n_modes: List[int] + hidden_channels: int + data_channels: int = 9 + out_channels: int = 1 + lifting_channel_ratio: int = 3 + projection_channel_ratio: int = 3 + norm: str = "group_norm" + use_channel_mlp: bool = True + channel_mlp_expansion: float = 1.0 + domain_padding: float = 0.125 + factorization: str = "tucker" + rank: float = 0.4 + + +class OTNO_Small2d(OTNOConfig): + n_modes: List[int] = [16, 16] + hidden_channels: int = 64 + data_channels: int = 9 + out_channels: int = 1 diff --git a/sources/neuraloperator/config/navier_stokes_config.py b/sources/neuraloperator/config/navier_stokes_config.py new file mode 100644 index 0000000000000000000000000000000000000000..a20236da5db03c896f3b259c7fcf2c3c41511c86 --- /dev/null +++ b/sources/neuraloperator/config/navier_stokes_config.py @@ -0,0 +1,40 @@ +from typing import Any, List, Optional + +from zencfg import ConfigBase +from .distributed import DistributedConfig +from .models import ModelConfig, FNO_Medium2d +from .opt import OptimizationConfig, PatchingConfig +from .wandb import WandbConfig + + +class NavierStokesOptConfig(OptimizationConfig): + n_epochs: int = 600 + learning_rate: float = 3e-4 + training_loss: str = "h1" + weight_decay: float = 1e-4 + scheduler: str = "StepLR" + step_size: int = 100 + gamma: float = 0.5 + + +class NavierStokesDatasetConfig(ConfigBase): + folder: str = "~/data/navier_stokes/" + batch_size: int = 8 + n_train: int = 10000 + train_resolution: int = 128 + n_tests: List[int] = [2000] + test_resolutions: List[int] = [128] + test_batch_sizes: List[int] = [8] + encode_input: bool = True + encode_output: bool = True + + +class Default(ConfigBase): + n_params_baseline: Optional[Any] = None + verbose: bool = True + distributed: DistributedConfig = DistributedConfig() + model: ModelConfig = FNO_Medium2d() + opt: OptimizationConfig = NavierStokesOptConfig() + data: NavierStokesDatasetConfig = NavierStokesDatasetConfig() + patching: PatchingConfig = PatchingConfig() + wandb: WandbConfig = WandbConfig() diff --git a/sources/neuraloperator/config/opt.py b/sources/neuraloperator/config/opt.py new file mode 100644 index 0000000000000000000000000000000000000000..a4c2764103a283d0561dd0a26ca59c78d37d2425 --- /dev/null +++ b/sources/neuraloperator/config/opt.py @@ -0,0 +1,23 @@ +from typing import Optional, Literal +from zencfg import ConfigBase + + +class OptimizationConfig(ConfigBase): + n_epochs: int + training_loss: Literal["h1", "l2"] = "h1" + testing_loss: str = "l2" + learning_rate: float = 3e-4 + weight_decay: float = 1e-4 + eval_interval: int = 1 + mixed_precision: bool = False + scheduler: Literal["StepLR", "ReduceLROnPlateau", "CosineAnnealingLR"] = "StepLR" + scheduler_T_max: int = 500 + scheduler_patience: int = 50 + step_size: int = 100 + gamma: float = 0.5 + + +class PatchingConfig(ConfigBase): + levels: int = 0 + padding: int = 0 + stitching: bool = False diff --git a/sources/neuraloperator/config/otno_carcfd_config.py b/sources/neuraloperator/config/otno_carcfd_config.py new file mode 100644 index 0000000000000000000000000000000000000000..f55c958105b86e430121b594462d5b929fc6d98e --- /dev/null +++ b/sources/neuraloperator/config/otno_carcfd_config.py @@ -0,0 +1,36 @@ +from typing import Any, List, Optional + +from zencfg import ConfigBase +from .distributed import DistributedConfig +from .models import ModelConfig, OTNO_Small2d +from .opt import OptimizationConfig, PatchingConfig +from .wandb import WandbConfig + + +class CarCFDDatasetConfig(ConfigBase): + root: str = "~/processed-car-pressure-data" + n_train: int = 500 + n_test: int = 111 + reg: float = 1e-06 + expand_factor: float = 3.0 + + +class CarCFDOptConfig(OptimizationConfig): + n_epochs: int = 100 + learning_rate: float = 1e-3 + training_loss: str = "l2" + weight_decay: float = 1e-4 + scheduler: str = "StepLR" + step_size: int = 30 + gamma: float = 0.5 + + +class Default(ConfigBase): + n_params_baseline: Optional[Any] = None + verbose: bool = True + distributed: DistributedConfig = DistributedConfig() + model: ModelConfig = OTNO_Small2d() + opt: OptimizationConfig = CarCFDOptConfig() + data: CarCFDDatasetConfig = CarCFDDatasetConfig() + patching: PatchingConfig = PatchingConfig() + wandb: WandbConfig = WandbConfig() diff --git a/sources/neuraloperator/config/poisson_gino_config.py b/sources/neuraloperator/config/poisson_gino_config.py new file mode 100644 index 0000000000000000000000000000000000000000..24708e92a80b737b9955c110f3ebdc3d00de1d00 --- /dev/null +++ b/sources/neuraloperator/config/poisson_gino_config.py @@ -0,0 +1,55 @@ +from typing import Any, List, Optional, Dict + +from zencfg import ConfigBase +from .distributed import DistributedConfig +from .models import ModelConfig, GINO_Poisson2d +from .opt import OptimizationConfig, PatchingConfig +from .wandb import WandbConfig + + +class MGNOPoissonOptConfig(OptimizationConfig): + n_epochs: int = 1000 + training_loss: List[str] = ["equation", "boundary"] + loss_weights: Dict[str, Any] = {"mse": 1.0, "interior": 1e-2, "boundary": 1.0} + pino_method: str = "autograd" + weight_decay: float = 1e-6 + mixed_precision: bool = False + learning_rate: float = 1e-4 + optimizer: str = "Adam" + scheduler: str = "ReduceLROnPlateau" + scheduler_T_max: int = 5000 + scheduler_patience: int = 2 + gamma: float = 0.9 + eval_interval: int = 1 + + +class NonlinearPoissonDatasetConfig(ConfigBase): + file: str = "~/data/nonlin_poisson/nonlinear_poisson.obj" + batch_size: int = 1 + test_batch_size: int = 1 + n_train: int = 7000 + n_test: int = 3000 + n_in: int = 5000 + n_out: int = 100 + n_eval: int = 6000 + n_bound: int = 4000 + query_resolution: int = 64 + train_out_res: int = 400 + padding: int = 1 + single_instance: bool = False + input_min: int = 100 + input_max: int = 5000 + sample_random_in: Optional[Any] = None + sample_random_out: Optional[Any] = None + return_queries_dict: bool = True + + +class Default(ConfigBase): + n_params_baseline: Optional[Any] = None + verbose: bool = True + distributed: DistributedConfig = DistributedConfig() + model: ModelConfig = GINO_Poisson2d() + opt: OptimizationConfig = MGNOPoissonOptConfig() + data: ConfigBase = NonlinearPoissonDatasetConfig() + patching: PatchingConfig = PatchingConfig() + wandb: WandbConfig = WandbConfig() diff --git a/sources/neuraloperator/config/test_config.py b/sources/neuraloperator/config/test_config.py new file mode 100644 index 0000000000000000000000000000000000000000..e4bdc15fb8d1b8c3c016ddfc96514d64fbf700f4 --- /dev/null +++ b/sources/neuraloperator/config/test_config.py @@ -0,0 +1,47 @@ +from typing import Any, List, Optional + +from zencfg import ConfigBase +from .distributed import DistributedConfig +from .datasets import NavierStokesDatasetConfig +from .models import ModelConfig, SimpleFNOConfig +from .opt import OptimizationConfig, PatchingConfig +from .wandb import WandbConfig + + +class TestConfig(ConfigBase): + n_params_baseline: Optional[Any] = None + verbose: bool = True + distributed: DistributedConfig = DistributedConfig() + model: ModelConfig = SimpleFNOConfig( + data_channels=1, + out_channels=1, + n_modes=[64, 64], + hidden_channels=64, + n_layers=4, + projection_channel_ratio=4, + ) + opt: OptimizationConfig = OptimizationConfig( + n_epochs=600, + learning_rate=3e-4, + training_loss="h1", + weight_decay=1e-4, + scheduler="StepLR", + step_size=100, + gamma=0.5, + ) + data: NavierStokesDatasetConfig = NavierStokesDatasetConfig( + batch_size=8, + n_train=10000, + train_resolution=128, + n_tests=[2000], + test_resolutions=[128], + test_batch_sizes=[8], + encode_input=True, + encode_output=True, + ) + patching: PatchingConfig = PatchingConfig() + wandb: WandbConfig = WandbConfig( + log=False, # turn this to True to log to wandb + entity="my_entity", + project="my_project", + ) diff --git a/sources/neuraloperator/config/the_well/mhd_64_config.py b/sources/neuraloperator/config/the_well/mhd_64_config.py new file mode 100644 index 0000000000000000000000000000000000000000..0f4a7e054c1447e6d0da87639eea86ea50183ed6 --- /dev/null +++ b/sources/neuraloperator/config/the_well/mhd_64_config.py @@ -0,0 +1,41 @@ +from typing import Any, List, Optional + +from zencfg import ConfigBase +from ..distributed import DistributedConfig +from ..models import ModelConfig, FNO_Medium3d +from ..opt import OptimizationConfig, PatchingConfig +from ..wandb import WandbConfig + + +class MHD64OptConfig(OptimizationConfig): + n_epochs: int = 600 + learning_rate: float = 3e-4 + training_loss: str = "h1" + weight_decay: float = 1e-4 + scheduler: str = "StepLR" + step_size: int = 100 + gamma: float = 0.5 + + +class MHD_64_DatasetConfig(ConfigBase): + root: str = "~/data/the_well" + n_train: int = 10 + n_steps_input: int = 1 + n_steps_output: int = 1 + batch_size: int = 1 + n_test: int = 10 + test_batch_size: int = 1 + input_timesteps: int = 1 + output_timesteps: int = 51 # 15 + max_rollout_len: int = 100 + + +class Default(ConfigBase): + n_params_baseline: Optional[Any] = None + verbose: bool = True + distributed: DistributedConfig = DistributedConfig() + model: ModelConfig = FNO_Medium3d(data_channels=7, out_channels=7) + opt: OptimizationConfig = MHD64OptConfig() + data: MHD_64_DatasetConfig = MHD_64_DatasetConfig() + patching: PatchingConfig = PatchingConfig() + wandb: WandbConfig = WandbConfig() diff --git a/sources/neuraloperator/config/uqno_config.py b/sources/neuraloperator/config/uqno_config.py new file mode 100644 index 0000000000000000000000000000000000000000..0776f73d683a22bfff9e8ef48342581add1cfb4c --- /dev/null +++ b/sources/neuraloperator/config/uqno_config.py @@ -0,0 +1,69 @@ +from typing import Any, List, Optional, Dict + +from zencfg import ConfigBase +from .distributed import DistributedConfig +from .models import ModelConfig, FNO_Medium2d +from .opt import OptimizationConfig, PatchingConfig +from .wandb import WandbConfig + + +class SolutionModelOptConfig(OptimizationConfig): + n_epochs: int = 300 + resume: bool = False + learning_rate: float = 5e-3 + training_loss: str = "h1" + weight_decay: float = 1e-4 + mixed_precision: bool = False + scheduler_T_max: int = 500 + scheduler_patience: int = 5 + scheduler: str = "StepLR" + step_size: int = 60 + gamma: float = 0.5 + eval_interval: int = 1 + + +class ResidualModelOptConfig(OptimizationConfig): + n_epochs: int = 300 + learning_rate: float = 5e-3 + training_loss: str = "h1" + weight_decay: float = 1e-4 + mixed_precision: bool = False + scheduler_T_max: int = 500 + scheduler_patience: int = 5 + scheduler: str = "StepLR" + step_size: int = 60 + gamma: float = 0.5 + eval_interval: int = 1 + + +class UQNODarcyDatasetConfig(ConfigBase): + root: str = "~/data/darcy" + batch_size: int = 4 + n_train_total: int = 4000 + n_train_solution: int = 2500 + n_train_residual: int = 1000 + n_calib_residual: int = 500 + train_resolution: int = 421 + n_test: int = 1000 + test_resolution: int = 421 + test_batch_size: int = 4 + encode_input: bool = True + encode_output: bool = True + + +class UQNO_OptConfig(ConfigBase): + alpha: float = 0.9 + delta: float = 0.95 + solution: SolutionModelOptConfig = SolutionModelOptConfig() + residual: ResidualModelOptConfig = ResidualModelOptConfig() + + +class Default(ConfigBase): + n_params_baseline: Optional[Any] = None + verbose: bool = True + distributed: DistributedConfig = DistributedConfig() + model: ModelConfig = FNO_Medium2d() + opt: UQNO_OptConfig = UQNO_OptConfig() + data: UQNODarcyDatasetConfig = UQNODarcyDatasetConfig() + patching: PatchingConfig = PatchingConfig() + wandb: WandbConfig = WandbConfig() diff --git a/sources/neuraloperator/config/wandb.py b/sources/neuraloperator/config/wandb.py new file mode 100644 index 0000000000000000000000000000000000000000..92671b0ad22a14561294794dade3bb2a89ed318e --- /dev/null +++ b/sources/neuraloperator/config/wandb.py @@ -0,0 +1,37 @@ +from typing import Optional +from zencfg import ConfigBase + + +class WandbConfig(ConfigBase): + """WandbConfig provides config options for setting up + an interface with [Weights and Biases](https://wandb.ai). + + + Parameters + ---------- + log: bool, default False + whether to log outputs to W&B + entity: Optional[str], default None + W&B username/entity to which to log + project: Optional[str], default None + Project name within W&B account to which to log. + name: Optional[str], default None + Name of the logged run on W&B + group: str, default None + If provided, will group this run along with all other + runs tagged to the same group. + sweep: bool, default False + whether to perform an automatic W&B sweep. Deprecated. + log_output: bool, default True + Whether to optionally log model outputs at each eval step + to W&B, if logging to W&B (``log = True``) + + """ + + log: bool = False + entity: Optional[str] = None + project: Optional[str] = None + name: Optional[str] = None + group: Optional[str] = None + sweep: bool = False + log_output: bool = True diff --git a/sources/neuraloperator/constraints.txt b/sources/neuraloperator/constraints.txt new file mode 100644 index 0000000000000000000000000000000000000000..f72a525e88a56925913c95b48b03f1b951be4564 --- /dev/null +++ b/sources/neuraloperator/constraints.txt @@ -0,0 +1,2 @@ +numpy>=1.26.4 +torch_harmonics>=0.7 \ No newline at end of file diff --git a/sources/neuraloperator/doc/Makefile b/sources/neuraloperator/doc/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..d0c3cbf1020d5c292abdedf27627c6abe25e2293 --- /dev/null +++ b/sources/neuraloperator/doc/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line, and also +# from the environment for the first two. +SPHINXOPTS ?= +SPHINXBUILD ?= sphinx-build +SOURCEDIR = source +BUILDDIR = build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/sources/neuraloperator/doc/make.bat b/sources/neuraloperator/doc/make.bat new file mode 100644 index 0000000000000000000000000000000000000000..747ffb7b3033659bdd2d1e6eae41ecb00358a45e --- /dev/null +++ b/sources/neuraloperator/doc/make.bat @@ -0,0 +1,35 @@ +@ECHO OFF + +pushd %~dp0 + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set SOURCEDIR=source +set BUILDDIR=build + +%SPHINXBUILD% >NUL 2>NUL +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.https://www.sphinx-doc.org/ + exit /b 1 +) + +if "%1" == "" goto help + +%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% +goto end + +:help +%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% + +:end +popd diff --git a/sources/neuraloperator/doc/requirements_doc.txt b/sources/neuraloperator/doc/requirements_doc.txt new file mode 100644 index 0000000000000000000000000000000000000000..eefac7054c1697f66078ac5a3a7f625ae32a0e75 --- /dev/null +++ b/sources/neuraloperator/doc/requirements_doc.txt @@ -0,0 +1,10 @@ +setuptools>=40.0,<80 +matplotlib +myst-nb +numpydoc +sphinx +sphinx-gallery +sphinx-design +tensorly_sphinx_theme +torchtnt +torch-harmonics \ No newline at end of file diff --git a/sources/neuraloperator/doc/source/_static/css/custom.css b/sources/neuraloperator/doc/source/_static/css/custom.css new file mode 100644 index 0000000000000000000000000000000000000000..8eecf275f9f5a62ab21bf5edf184e3461facc555 --- /dev/null +++ b/sources/neuraloperator/doc/source/_static/css/custom.css @@ -0,0 +1,105 @@ +/* Custom styles for neuraloperator documentation */ + +/* Override sidebar background color - slightly gray */ +#sidebar { + background-color: #f5f5f5 !important; /* Slightly gray background */ +} + +/* Override top navigation bar - same as left panel */ +.navbar.top-navbar { + background-color: #f5f5f5 !important; /* Same slightly gray as left panel */ + border-bottom: 2px solid #dee2e6 !important; /* Line separation under top bar */ + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1) !important; /* Subtle shadow for depth */ +} + +/* Ensure navbar text remains readable on slightly gray background */ +.navbar.top-navbar .navbar-item, +.navbar.top-navbar .navbar-link { + color: #333333 !important; /* Dark text on slightly gray */ +} + +.navbar.top-navbar .navbar-item:hover, +.navbar.top-navbar .navbar-link:hover { + background-color: #e9ecef !important; /* Slightly lighter gray on hover */ + color: #333333 !important; +} + +.navbar.top-navbar .navbar-item.is-active { + background-color: #e9ecef !important; + color: #333333 !important; +} + +/* Ensure main content area stays white */ +.main-content, +.content { + background-color: #ffffff !important; +} + +/* Custom sidebar menu styling */ +.sidebar-menu { + background-color: inherit; +} + +.sidebar-menu-toc { + background-color: inherit; +} + +/* Ensure sidebar text remains readable */ +#sidebar a { + color: #333 !important; +} + +#sidebar a:hover { + color: #007bff !important; +} + +/* Style for selected/current section in sidebar */ +#sidebar .toctree-l1.current > a, +#sidebar .toctree-l1.current > a.reference.internal { + background-color: #495057 !important; /* Dark gray background for selected section */ + color: #ffffff !important; /* White text on dark gray */ + border-radius: 4px !important; + padding: 8px 12px !important; + margin: 2px 0 !important; +} + +/* Style for active/current page in sidebar */ +#sidebar .toctree-l1.current > a.current, +#sidebar .toctree-l1.current > a.current.reference.internal { + background-color: #343a40 !important; /* Even darker gray for current page */ + color: #ffffff !important; + font-weight: bold !important; +} + +/* Reduce width of left and right panels */ +#sidebar { + flex: 0 0 230px !important; /* Fixed width of 230px for sidebar */ + max-width: 230px !important; + min-width: 230px !important; +} + +/* Adjust main content area to take up more space */ +.main-column { + flex: 1 !important; + min-width: 0 !important; /* Allow content to shrink */ +} + +/* Override Bulma column classes for narrower panels */ +.column.is-3-desktop { + flex: 0 0 230px !important; + max-width: 230px !important; +} + +.column.is-one-third-tablet { + flex: 0 0 230px !important; + max-width: 230px !important; +} + +/* Ensure responsive behavior is maintained */ +@media screen and (max-width: 768px) { + #sidebar { + flex: 0 0 100% !important; + max-width: 100% !important; + min-width: 100% !important; + } +} diff --git a/sources/neuraloperator/doc/source/_static/images/Burgers.jpg b/sources/neuraloperator/doc/source/_static/images/Burgers.jpg new file mode 100644 index 0000000000000000000000000000000000000000..31671fd4f79b4f8cd8e87985f9f1a60930d17c5b --- /dev/null +++ b/sources/neuraloperator/doc/source/_static/images/Burgers.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3319e31c181bf6574a3095dbb8b0fafdfe57ed0e9a602aedde986b6752a114a4 +size 22897 diff --git a/sources/neuraloperator/doc/source/_static/images/Darcy.jpg b/sources/neuraloperator/doc/source/_static/images/Darcy.jpg new file mode 100644 index 0000000000000000000000000000000000000000..7e3810db15521274f86da1dca8b426b8e7c41f07 --- /dev/null +++ b/sources/neuraloperator/doc/source/_static/images/Darcy.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8bfb00ab2868c93e8c8986e0c623632f02270893be4bce2efb1bea8ad46c71ea +size 25880 diff --git a/sources/neuraloperator/doc/source/_static/images/GKN_compare.jpg b/sources/neuraloperator/doc/source/_static/images/GKN_compare.jpg new file mode 100644 index 0000000000000000000000000000000000000000..5066f5beeeb69f609a4cf9805233c6f367dea965 --- /dev/null +++ b/sources/neuraloperator/doc/source/_static/images/GKN_compare.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d486c0382ad887dafa8d53d0219dd0029027eea663ac7ce44d6d9f326c5e0c9d +size 67021 diff --git a/sources/neuraloperator/doc/source/_static/images/KF-Attractor.jpg b/sources/neuraloperator/doc/source/_static/images/KF-Attractor.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a193fca47bbd7ca26c7882f52142a1a9516dcc42 --- /dev/null +++ b/sources/neuraloperator/doc/source/_static/images/KF-Attractor.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:724bed872f21cd27de6074b6a1aaf7bd7ca15f9ccaac6cc704e3fc8bdc1874d6 +size 339925 diff --git a/sources/neuraloperator/doc/source/_static/images/KF-stats.jpg b/sources/neuraloperator/doc/source/_static/images/KF-stats.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d2e0e577e7dca0567c39b75235a1dec5b8145e2e --- /dev/null +++ b/sources/neuraloperator/doc/source/_static/images/KF-stats.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d0f85b27768230b64ce19664d731604a002ca776e4b634496ae8e98822079c17 +size 135652 diff --git a/sources/neuraloperator/doc/source/_static/images/KF-vorticity.jpg b/sources/neuraloperator/doc/source/_static/images/KF-vorticity.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1b9372b2d00d776894502bc47e0cf53a23b29153 --- /dev/null +++ b/sources/neuraloperator/doc/source/_static/images/KF-vorticity.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:639b5ead29b79e772c151c4a126fa140811220f2d917122dd53d3268d21bdb83 +size 115245 diff --git a/sources/neuraloperator/doc/source/_static/images/KS-stats.jpg b/sources/neuraloperator/doc/source/_static/images/KS-stats.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d4dfb023aab22dd8fddf6638793b347bfae111ee --- /dev/null +++ b/sources/neuraloperator/doc/source/_static/images/KS-stats.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7d6a9aca7539f5c5aba7c2bbf94fbe6cb1abf05f3679c5a03509d98642f376ce +size 176576 diff --git a/sources/neuraloperator/doc/source/_static/images/KS-trajectory.jpg b/sources/neuraloperator/doc/source/_static/images/KS-trajectory.jpg new file mode 100644 index 0000000000000000000000000000000000000000..f2495e2cdebf43191fa607b139ffb6d5c4deb176 --- /dev/null +++ b/sources/neuraloperator/doc/source/_static/images/KS-trajectory.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9c70a823174d5c5ad683dfc5d068b82f066c4be096da686563cac7c2e8ce2ec1 +size 431093 diff --git a/sources/neuraloperator/doc/source/_static/images/fft_shift.png b/sources/neuraloperator/doc/source/_static/images/fft_shift.png new file mode 100644 index 0000000000000000000000000000000000000000..fe5791e9404cb94f8dd79ad37baef8b682425b25 --- /dev/null +++ b/sources/neuraloperator/doc/source/_static/images/fft_shift.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2cd1a9232f38a93db67b7495c9ada9f3218fb5055a199845480721866f386e5e +size 402155 diff --git a/sources/neuraloperator/doc/source/_static/images/filters.jpg b/sources/neuraloperator/doc/source/_static/images/filters.jpg new file mode 100644 index 0000000000000000000000000000000000000000..3b62f99f0ca5c2bc0614569c55d987d97c61de50 --- /dev/null +++ b/sources/neuraloperator/doc/source/_static/images/filters.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b103a723f7e062828b25b9b30a321a44a57a109e7f87a24f54c5c92ba4b09ef4 +size 136888 diff --git a/sources/neuraloperator/doc/source/_static/images/fourier_bayesian.jpg b/sources/neuraloperator/doc/source/_static/images/fourier_bayesian.jpg new file mode 100644 index 0000000000000000000000000000000000000000..857419a54e4ce0cad91a82ce60f601dce4c28bbd --- /dev/null +++ b/sources/neuraloperator/doc/source/_static/images/fourier_bayesian.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fd50381f94f6280c78612a1abf9b081c23317210133ad6cb606de848f1345dd3 +size 131981 diff --git a/sources/neuraloperator/doc/source/_static/images/fourier_error.jpg b/sources/neuraloperator/doc/source/_static/images/fourier_error.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d60a47166de22c462046280105f9cbfd4fb19f5c --- /dev/null +++ b/sources/neuraloperator/doc/source/_static/images/fourier_error.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:54c0e9ece5df894a9f28d4fbd1297485d86ea6276f4bac8a40436f498385d756 +size 107924 diff --git a/sources/neuraloperator/doc/source/_static/images/fourier_layer.jpg b/sources/neuraloperator/doc/source/_static/images/fourier_layer.jpg new file mode 100644 index 0000000000000000000000000000000000000000..4f3b2a5f3fb9cd16b9ef146fb99c5636ea2b41dd --- /dev/null +++ b/sources/neuraloperator/doc/source/_static/images/fourier_layer.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:55f734c2e5a75e9e8fbc2f7cf8c4e71c936ad0c8023201fc5fc7625f0293235a +size 53716 diff --git a/sources/neuraloperator/doc/source/_static/images/fourier_layer2.jpg b/sources/neuraloperator/doc/source/_static/images/fourier_layer2.jpg new file mode 100644 index 0000000000000000000000000000000000000000..bb2495da644f07b719125f1d5b4209772fd39fb7 --- /dev/null +++ b/sources/neuraloperator/doc/source/_static/images/fourier_layer2.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:050e3b782ffd3c3b959ec95375f4aaee17c9ceea116972be6bcbaac6eda3cafa +size 31697 diff --git a/sources/neuraloperator/doc/source/_static/images/fourier_ns1e4.jpg b/sources/neuraloperator/doc/source/_static/images/fourier_ns1e4.jpg new file mode 100644 index 0000000000000000000000000000000000000000..babdd6a1ab10147366d72911406a5616af8624a7 --- /dev/null +++ b/sources/neuraloperator/doc/source/_static/images/fourier_ns1e4.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5ec5adfc4020e541163ad5826bf25cd6e305aad473f4eaaa50f316bccbf1eef2 +size 78170 diff --git a/sources/neuraloperator/doc/source/_static/images/graph.jpg b/sources/neuraloperator/doc/source/_static/images/graph.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6d7941f15690b7379784043302bc575721bdbe37 --- /dev/null +++ b/sources/neuraloperator/doc/source/_static/images/graph.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e3e9047b33c71bbfddb95c3d1ae3c9e0b54bc0d12aa2659b5d30bcb2cc5b6c5b +size 42332 diff --git a/sources/neuraloperator/doc/source/_static/images/grids.jpg b/sources/neuraloperator/doc/source/_static/images/grids.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1fc87db1975863117c9d603bc785c87eb92b5cd5 --- /dev/null +++ b/sources/neuraloperator/doc/source/_static/images/grids.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:decd87195768acfa79e3093c1524e918f46053b5b5b8aa30bc0c854aedaa7c33 +size 151293 diff --git a/sources/neuraloperator/doc/source/_static/images/nik_kernel.jpg b/sources/neuraloperator/doc/source/_static/images/nik_kernel.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d08e18dffb4b133d71ef1d3f148de22dcdecac7f --- /dev/null +++ b/sources/neuraloperator/doc/source/_static/images/nik_kernel.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d9707ff53c80faca7c374f229e7ff0dbc3d1d058433fd8b4e7654bf594657ffe +size 54280 diff --git a/sources/neuraloperator/doc/source/_static/images/pdes_examples.jpg b/sources/neuraloperator/doc/source/_static/images/pdes_examples.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1e2048b43c08d9cc4c20f7f5f9bb793090d00c04 --- /dev/null +++ b/sources/neuraloperator/doc/source/_static/images/pdes_examples.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b18be5db466f646622841f3c42b592f46ece7de47d925c277172dc0f78830c0d +size 84495 diff --git a/sources/neuraloperator/doc/source/_static/images/uai_16to241.jpg b/sources/neuraloperator/doc/source/_static/images/uai_16to241.jpg new file mode 100644 index 0000000000000000000000000000000000000000..4791b7fad204eb72eaa785c28788b33abbffd66d --- /dev/null +++ b/sources/neuraloperator/doc/source/_static/images/uai_16to241.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:58abc66181c768025a2cbffe1ffb7bee5b29de7bb3337be401f5d0d49ddfa090 +size 58316 diff --git a/sources/neuraloperator/doc/source/_static/logos/nauraloperator_logo_square.png b/sources/neuraloperator/doc/source/_static/logos/nauraloperator_logo_square.png new file mode 100644 index 0000000000000000000000000000000000000000..8ba02bd3c1e47e4a4ce5340373d87f6156c145e3 --- /dev/null +++ b/sources/neuraloperator/doc/source/_static/logos/nauraloperator_logo_square.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:762f783e1678e4c8072e74e86c9548c0aa5359c00672063a26ba4144bada3c73 +size 117973 diff --git a/sources/neuraloperator/doc/source/_static/logos/neuraloperator_logo.png b/sources/neuraloperator/doc/source/_static/logos/neuraloperator_logo.png new file mode 100644 index 0000000000000000000000000000000000000000..c29d1a8e6b97f681b5df26ef642e329ea5e4c91d --- /dev/null +++ b/sources/neuraloperator/doc/source/_static/logos/neuraloperator_logo.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:56404d8530c14b5659a84f9cd18a02f26920654c888618c6001bb9514229607d +size 97632 diff --git a/sources/neuraloperator/doc/source/_static/logos/neuraloperator_logo_long.png b/sources/neuraloperator/doc/source/_static/logos/neuraloperator_logo_long.png new file mode 100644 index 0000000000000000000000000000000000000000..100364ddc62a6b06cbfbd047a315daae551f6b72 --- /dev/null +++ b/sources/neuraloperator/doc/source/_static/logos/neuraloperator_logo_long.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bd4c753099e4f919294db80ac8273f902615cbe461fdcbb4c5d9f46d0b1ae325 +size 126191 diff --git a/sources/neuraloperator/doc/source/_templates/class.rst b/sources/neuraloperator/doc/source/_templates/class.rst new file mode 100644 index 0000000000000000000000000000000000000000..d787bea503aadd929f1c6f0aadcfe1d29f37b89a --- /dev/null +++ b/sources/neuraloperator/doc/source/_templates/class.rst @@ -0,0 +1,11 @@ +:mod:`{{module}}`.{{objname}} +{{ underline }}============== + +.. currentmodule:: {{ module }} + +.. autoclass:: {{ objname }} + :members: + +.. raw:: html + +
diff --git a/sources/neuraloperator/doc/source/_templates/function.rst b/sources/neuraloperator/doc/source/_templates/function.rst new file mode 100644 index 0000000000000000000000000000000000000000..d8c9bd4807ccda4b0bc5ca19df460b377c6ae7bc --- /dev/null +++ b/sources/neuraloperator/doc/source/_templates/function.rst @@ -0,0 +1,10 @@ +:mod:`{{module}}`.{{objname}} +{{ underline }}==================== + +.. currentmodule:: {{ module }} + +.. autofunction:: {{ objname }} + +.. raw:: html + +
diff --git a/sources/neuraloperator/doc/source/compress_images.sh b/sources/neuraloperator/doc/source/compress_images.sh new file mode 100644 index 0000000000000000000000000000000000000000..5ab7e8318071865a9a9985e89fd2c01444a08f0d --- /dev/null +++ b/sources/neuraloperator/doc/source/compress_images.sh @@ -0,0 +1,13 @@ +# Adapted from https://stackoverflow.com/questions/59111396/loop-through-the-directories-to-get-the-image-files +# Usage +# chmod 755 compress_images.bash +# bash compress_images.sh ./_static/images + +find "$1" \( -iname \*.png \) -print0 | while read -r -d $'\0' file; do + # base="${file##*/}" $base is the file name with all the directory stuff stripped off + # dir="${file%/*}" $dir is the directory with the file name stripped off + # target="${file%.*}" This is the full name without extension + target="${file%.*}.jpg" + sips -s format jpeg -s formatOptions low ${file} --out ${target} + git rm ${file} +done diff --git a/sources/neuraloperator/doc/source/conf.py b/sources/neuraloperator/doc/source/conf.py new file mode 100644 index 0000000000000000000000000000000000000000..3f9240cda1fef4df88b4cf16f287232195b1f17f --- /dev/null +++ b/sources/neuraloperator/doc/source/conf.py @@ -0,0 +1,125 @@ +# Configuration file for the Sphinx documentation builder. +# +# This file only contains a selection of the most common options. For a full +# list see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +# -- Path setup -------------------------------------------------------------- + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +# import os +# import sys +# sys.path.insert(0, os.path.abspath('.')) +from pathlib import Path + +# -- Project information ----------------------------------------------------- + +project = 'neuraloperator' +from datetime import datetime +year = datetime.now().year +copyright = f'{year}, Jean Kossaifi, David Pitt, Nikola Kovachki, Zongyi Li and Anima Anandkumar' +author = 'Jean Kossaifi, David Pitt, Nikola Kovachki, Zongyi Li and Anima Anandkumar' + +# The full version, including alpha/beta/rc tags +import neuralop +release = neuralop.__version__ + +# -- General configuration --------------------------------------------------- + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.autodoc', + 'sphinx.ext.autosummary', + 'sphinx.ext.todo', + 'sphinx.ext.viewcode', + 'sphinx.ext.githubpages', + 'sphinx.ext.mathjax', #'sphinx.ext.imgmath', + 'numpydoc.numpydoc', + 'sphinx_gallery.gen_gallery', + 'sphinx_design', +] + +# -- sphinx_gallery configuration --------------------------------- + +sg_gallery_dir = 'auto_examples' +sg_examples_dir = '../../examples' + +sphinx_gallery_conf = { + 'examples_dirs': [sg_examples_dir], # path to your example scripts + 'gallery_dirs': [sg_gallery_dir], # path to where to save gallery generated output + 'nested_sections': True, # ensure we can nest multiple levels in the gallery toctree + 'matplotlib_animations': True, # ensure that we can render MPL animations in the gallery +} + +# -- Template configuration + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = [] + +# -- NumpyDoc configuration --------------------------------------- +numpydoc_class_members_toctree = False +numpydoc_show_class_members = True +numpydoc_show_inherited_class_members = False + +# generate autosummary even if no references +autosummary_generate = True +autodoc_member_order = 'bysource' +autodoc_default_flags = ['members'] + +# Napoleon +napoleon_google_docstring = False +napoleon_use_rtype = False + +# imgmath/mathjax +imgmath_image_format = 'svg' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = 'tensorly_sphinx_theme' +html_logo = '_static/logos/neuraloperator_logo.png' +html_show_sphinx = False + +html_theme_options = { + 'github_url': 'https://github.com/neuraloperator/neuraloperator', + # 'google_analytics' : 'G-QSPLEF75VT', + 'nav_links' : [('Install', 'install'), + ('Theory Guide', 'theory_guide/index'), + ('User Guide', 'user_guide/index'), + ('API', 'modules/api'), + ('Examples', 'auto_examples/index'), + ('Developer\'s Guide', 'dev_guide/index'), + ], + # 'external_nav_links' : [('TensorLy', 'http://tensorly.org/dev')] +} + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +html_css_files = [ + 'css/custom.css', +] + +# Remove the permalinks ("¶" symbols) +html_permalinks_icon = "" + diff --git a/sources/neuraloperator/doc/source/dev_guide/index.rst b/sources/neuraloperator/doc/source/dev_guide/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..c48598d7afc7d967ac9c4cb881b3934c9f0eb3e2 --- /dev/null +++ b/sources/neuraloperator/doc/source/dev_guide/index.rst @@ -0,0 +1,440 @@ +.. _dev_guide: + +================= +Development guide +================= + +This guide provides essential information for developers contributing to NeuralOperator. + +We welcome new contributions to the library! Our mission for NeuralOperator is to +provide access to well-documented, robust implementations of neural operator methods +from foundations to the cutting edge. +The library is primarily intended for methods that directly relate to operator learning: +new architectures, meta-algorithms, training methods and benchmark datasets. +We are also interested in integrating interactive examples that showcase operator +learning in action on small sample problems. + +If your work provides one of the above, we would be thrilled to integrate it into the +library. Otherwise, if your work simply relies on a version of the NeuralOperator +codebase, we recommend publishing your code separately using a procedure outlined +in the :ref:`Publishing code built on the library ` +section. + +.. raw:: html + +
+ +Development Setup +----------------- + +.. _fork-and-clone: + +Fork and Clone the Repository +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +1. **Fork the repository** on GitHub by clicking the "Fork" button + +2. **Clone the library and connect your fork**: + + .. code-block:: bash + + git clone https://github.com/neuraloperator/neuraloperator.git + cd neuraloperator + git remote rename origin upstream + git remote add origin https://github.com//neuraloperator.git + git remote -v + + This should show: + + .. code-block:: text + + origin https://github.com//neuraloperator.git (fetch) + origin https://github.com//neuraloperator.git (push) + upstream https://github.com/neuraloperator/neuraloperator.git (fetch) + upstream https://github.com/neuraloperator/neuraloperator.git (push) + +.. raw:: html + +
+ +Set Up Environment +~~~~~~~~~~~~~~~~~~ + +1. **Create a virtual environment**: + + .. code-block:: bash + + python -m venv venv + source venv/bin/activate # On Windows: venv\Scripts\activate + +2. **Install development dependencies**: + + .. code-block:: bash + + pip install -e .[dev] + # OR + pip install neuraloperator[dev] + +.. raw:: html + +
+ + +Development Workflow +-------------------- + +.. _create-branch: + +.. raw:: html + +
+ +Create a Branch and Make Changes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code-block:: bash + + # Create and switch to a new branch + git checkout -b feature/your-feature-name + + # Make your changes + # ... edit files ... + + # Stage and commit your changes + git add . + git commit -m "Add: brief description of your changes + + - More detailed explanation of what you changed + - Why you made these changes + - Any relevant context" + + # Push to your fork + git push -u origin feature/your-feature-name + +.. raw:: html + +
+ +Write Tests +~~~~~~~~~~~ + +**Always add tests for new functionality!** + +- **For models**: Add tests in ``neuralop/models/tests/test_your_model.py`` +- **For layers**: Add tests in ``neuralop/layers/tests/test_your_layer.py`` +- **For utilities**: Add tests in the appropriate test directory + +**Example test structure:** + +.. code-block:: python + + import pytest + import torch + from neuralop.models import YourModel + + class TestYourModel: + def test_forward_pass(self): + model = YourModel(...) + x = torch.randn(1, 3, 32, 32) + output = model(x) + assert output.shape == expected_shape + + def test_gradient_flow(self): + # Test that gradients flow properly + pass + +.. raw:: html + +
+ +Run Tests and Quality Checks +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code-block:: bash + + # Run all tests + pytest neuralop + + # Run tests with verbose output + pytest neuralop -v + + # Run specific test file + pytest neuralop/models/tests/test_your_model.py + + # Format code + black . + +.. raw:: html + +
+ +Submit a Pull Request +~~~~~~~~~~~~~~~~~~~~~ + +After having forked and cloned the repository as described in +the :ref:`Fork and Clone the Repository ` section, +and created a branch and committed changes as described in +the :ref:`Create a Branch and Make Changes ` section, +you can now submit your pull request: + +1. **Push your branch to your fork**: + + .. code-block:: bash + + git push -u origin feature/your-feature-name + + +2. **Go to your fork on GitHub** and you should see a banner suggesting to + create a pull request, or click "Compare & pull request". + +3. **Fill out the PR description**: + + - Provide a clear title that describes your changes + - Write a detailed description explaining what you've changed or added + - Reference any related issues using `#issue_number` + - Include screenshots or examples if applicable + +4. **Submit the pull request** by clicking "Create pull request". + +Ensure your PR description clearly communicates what you have changed or added, why you made these changes, and any relevant context for reviewers. + +.. raw:: html + +
+ +Development Guidelines +---------------------- + +.. raw:: html + +
+ +Code Style +~~~~~~~~~~ + +- **Follow PEP 8** style guidelines for Python code +- **Use meaningful names** for variables, functions, and classes +- **Write clear docstrings** using NumPy docstring format +- **Add type hints** where appropriate + +.. raw:: html + +
+ +Code Formatting +~~~~~~~~~~~~~~~ + +Before submitting, ensure your code follows our style guide: + +.. code-block:: bash + + # Format with black + black . + +Validate every update made by the ``black`` command + +.. raw:: html + +
+ +Testing Requirements +~~~~~~~~~~~~~~~~~~~~ + +- **All new code must have tests** +- **Run the full test suite** before submitting PRs +- **Use descriptive test names** that explain what is being tested +- **Test both normal operation and edge cases** +- **Aim for complete code coverage** for new functionality + +.. raw:: html + +
+ +Building Documentation +~~~~~~~~~~~~~~~~~~~~~~ + +The HTML documentation is built using Sphinx: + +.. code-block:: bash + + cd doc + make html + +This builds the docs in ``./doc/build/html``. Note that documentation requires additional dependencies from ``./doc/requirements_doc.txt``. + +To view documentation locally: + +.. code-block:: bash + + cd doc/build/html + python -m http.server 8000 + # Visit http://localhost:8000 + +.. raw:: html + +
+ +Git Best Practices +~~~~~~~~~~~~~~~~~~ + +- **Write clear, descriptive commit messages** +- **Keep commits focused and atomic** (one logical change per commit) +- **Rebase your branch** on main before submitting PRs +- **Use conventional commit format** when possible (feat:, fix:, docs:, etc.) + +.. raw:: html + +
+ +Documentation Standards +~~~~~~~~~~~~~~~~~~~~~~~ + +To ensure code clarity and future maintainability, NeuralOperator adheres to simple style principles. + +In general, docstrings use the NumPy format: + +.. code-block:: python + + def function(arg1: type1, arg2: type2=default) + """ + Parameters + ---------- + arg1 : type1 + description of what arg1 'means' + for the function's behavior + arg2 : type2, optional + description arg2 + by default default + """ + +For *classes*, this docstring should go directly below the class declaration: + +.. code-block:: python + + class MyClass(Superclass): + """ + docstring goes here + """ + def __init__(self, ...): + # Full NumPy docstring not needed here. + +We also adhere to good in-line commenting practices. When a block's function is not +obvious on its own, add in-line comments with a brief description. For tensor operations, +shape annotations are especially helpful where applicable. + +.. raw:: html + +
+ +Adding a New Model or Layer +--------------------------- + +We welcome various types of contributions: + +- **Bug fixes** - Report and fix bugs +- **New features** - Add new models, layers, or datasets +- **Examples** - Create new examples or improve existing ones +- **Performance** - Optimize existing code + +.. raw:: html + +
+ +Adding a New Neural Operator Model +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To add a new neural operator model: + +1. **Create a new file** in ``neuralop/models/your_model.py`` +2. **Implement the model** as a subclass of ``BaseModel`` +3. **Add comprehensive tests** in ``neuralop/models/tests/test_your_model.py`` +4. **Update imports** in the appropriate ``__init__.py`` files +5. **Add documentation** with examples and mathematical formulations + +**Example structure:** + +.. code-block:: python + + from neuralop.models import BaseModel + + class YourModel(BaseModel): + """Your model docstring here.""" + + def __init__(self, ...): + super().__init__() + # Your implementation + + def forward(self, x): + # Your forward pass + return x + +.. raw:: html + +
+ +Adding a New Layer +~~~~~~~~~~~~~~~~~~ + +To add a new layer: + +1. **Create a new file** in ``neuralop/layers/your_layer.py`` +2. **Ensure the layer** is a subclass of ``torch.nn.Module`` +3. **Add comprehensive tests** in ``neuralop/layers/tests/test_your_layer.py`` +4. **Update imports** in the appropriate ``__init__.py`` files + +.. note:: + + **💡 Pro Tip**: For bonus points, add an interactive example featuring your new method to ``./examples``. This helps both us and you: the simpler it is for new users to understand and adapt your method, the more visibility it will get! + +.. raw:: html + +
+ +Getting Help +------------ + +If you need assistance while contributing to NeuralOperator, here are the best ways to get help: + +.. raw:: html + +
+ +Before Asking for Help +~~~~~~~~~~~~~~~~~~~~~~ + +1. **Check the documentation** and existing issues +2. **Search GitHub issues** for similar problems +3. **Provide a minimal reproducible example** +4. **Include error messages** and stack traces +5. **Specify your environment** (OS, Python version, PyTorch version) + +.. raw:: html + +
+ +Contact Methods +~~~~~~~~~~~~~~~ + +- **GitHub Issues**: Create an issue for bugs or feature requests +- **GitHub Discussions**: Use for questions and ideas +- **Documentation**: Check the `official documentation `_ + +.. raw:: html + +
+ + +License +------- + +By contributing to NeuralOperator, you agree that your contributions will be licensed as described in the `LICENSE` file in the root directory of this source tree. + +.. raw:: html + +
+ +Acknowledgments +--------------- + +Thank you for contributing to NeuralOperator! Your contributions help make this library better for the entire scientific machine learning community. + diff --git a/sources/neuraloperator/doc/source/index.rst b/sources/neuraloperator/doc/source/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..5bfd9a4924ca41d582a38e9e309a8ee456ba0670 --- /dev/null +++ b/sources/neuraloperator/doc/source/index.rst @@ -0,0 +1,174 @@ +:no-toc: +:no-localtoc: +:no-pagination: + +.. neural-operator documentation + +.. only:: html + + .. raw:: html + +

+ +.. only:: html + + .. raw:: html + +
+

Neural Operators in PyTorch

+
+

+ +.. only:: latex + + Neural Operators in PyTorch + =========================== + +.. image:: _static/logos/neuraloperator_logo_long.png + :align: center + :width: 500 + + + +NeuralOperator is a comprehensive PyTorch library for learning neural operators, +containing the official implementation of Fourier Neural Operators and other neural operator architectures. + +NeuralOperator is part of the PyTorch Ecosystem, check the PyTorch `announcement `_! + + +Unlike regular neural networks, neural operators enable learning mapping between function spaces, +and this library provides all of the tools to do so on your own data. Neural operators are +resolution invariant, so your trained operator can be applied on data of any resolution. + +.. raw:: html + +
+ + +Quickstart +========== + +This guide will walk you through the standard ML workflow of loading data, creating a neural operator, +training it on the data and saving the trained model for later use. (Check out :ref:`gallery_examples` for more info) + +First install the library ``pip install neuraloperator`` (see :doc:`install` for more options). + +To create a Fourier Neural Operator model: + + +.. code-block:: python + + from neuralop.models import FNO + + operator = FNO( + n_modes=(16, 16), + hidden_channels=64, + in_channels=2, + out_channels=1 + ) + +To save the weights of the trained model: + +.. code-block:: python + + model.save_checkpoint(save_folder='./checkpoints/', save_name='example_fno') + +And to load the weights later: + +.. code-block:: python + + from neuralop.models import FNO + model = FNO.from_checkpoint(save_folder='./checkpoints/', save_name='example_fno') + +``neuraloperator`` comes prepackaged with an example dataset of flows governed by the Darcy flow equation. + +To import the data: + +.. code-block:: python + + import torch + from neuralop.data.datasets import load_darcy_flow_small + + train_loader, test_loaders, data_processor = load_darcy_flow_small( + n_train=1000, + batch_size=32, + n_tests=[100], + test_resolutions=[32], + test_batch_sizes=[32], + ) + +Similar to the API provided by ``torchvision``, this dataset includes training and test data for use in standard PyTorch training loops, +as well as a ``preprocessor`` object that automates the transforms to convert the data into the form best understood by the model. + +We provide a ``Trainer`` object that automates the logic of a basic neural operator training loop to speed up experimentation (see :doc: `auto_examples` for more information). + +.. code-block:: python + + from neuralop.training import Trainer + + # Create the trainer + trainer = Trainer( + model=model, + n_epochs=20, + data_processor=data_processor, + verbose=True) + + # train the model + trainer.train( + train_loader=train_loader, + test_loaders=test_loaders, + optimizer=optimizer, + scheduler=scheduler, + regularizer=False, + training_loss=train_loss, + eval_losses=eval_losses + ) + +Weight tensorization is also provided out of the box: you can improve the previous models +by simply using a Tucker Tensor FNO with fewer parameters: + +.. code-block:: python + + from neuralop.models import TFNO + + operator = TFNO( + n_modes=(16, 16), + hidden_channels=64, + in_channels=2, + out_channels=1, + factorization='tucker', + implementation='factorized', + rank=0.1 + ) + +This will use a Tucker factorization of the weights. The forward pass +will be efficient by contracting directly the inputs with the factors +of the decomposition. The Fourier layers will have 10% of the parameters +of an equivalent, dense Fourier Neural Operator! + + +.. toctree:: + :maxdepth: 2 + :hidden: + + install + theory_guide/index + user_guide/index + modules/api + auto_examples/index + dev_guide/index + +.. only:: html + + .. raw:: html + +
+
+ + + + diff --git a/sources/neuraloperator/doc/source/install.rst b/sources/neuraloperator/doc/source/install.rst new file mode 100644 index 0000000000000000000000000000000000000000..53ff12d0bf45f32662b4ce2787aed92973612c8c --- /dev/null +++ b/sources/neuraloperator/doc/source/install.rst @@ -0,0 +1,107 @@ +========================= +Installing NeuralOperator +========================= + +The ``neuraloperator`` Python package provides all necessary tools for implementing operator learning. +Once installed, you can import it as ``neuralop``:: + + import neuralop + +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Basic Install +------------- + +Pre-requisites +++++++++++++++ + +You will need to have Python 3 installed, as well as NumPy, Scipy, PyTorch, TensorLy and TensorLy-Torch. +If you are starting with Python or generally want a pain-free experience, we recommend that you +install the `Anaconda distribution `_. It comes ready to use with all prerequisite packages. + +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Installing with pip ++++++++++++++++++++ + +We periodically package `neuraloperator` for release on PyPI. This version is not guaranteed to be up-to-date with +the latest changes to our code. + +To install via pip, simply run, in your terminal:: + + pip install -U neuraloperator + +(the `-U` is optional, use it if you want to update the package). + +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Building ``neuraloperator`` from source ++++++++++++++++++++++++++++++++++++++++ + +First ensure that you are in an environment with Python 3, NumPy, SciPy, PyTorch, TensorLy and TensorLy-Torch. +Then clone the repository and cd there:: + + git clone https://github.com/neuraloperator/neuraloperator + cd neuraloperator + + +Then, install the requirements :: + + pip install -r requirements.txt + + +Then install the package (here in editable mode with `-e`, or equivalently `--editable`):: + + pip install -e . + + +.. raw:: html + +
+ +~~~~~~~~~~~~~~~~~~~~ + +Advanced dependencies +--------------------- + +.. _open3d_dependency: + +Fast 3D spatial computing with Open3D ++++++++++++++++++++++++++++++++++++++ + +To accelerate spatial computing for 3D applications, we include +`Open3D `_ as an optional dependency. Open3D includes +utilities for reading 3D mesh files and fast 3D neighbor search. To install:: + + pip install open3d + +Note that Open3D is only +compatible with specific builds of PyTorch and CUDA. Check the sub-package +`Open3D-ML `_ documentation for more details. + +~~~~~~~~~~~~~~~~~~~~~ + +.. _torch_scatter_dependency: + +Sparse computations with PyTorch-Scatter +++++++++++++++++++++++++++++++++++++++++ + +We use the package ``torch_scatter`` (available on PyPI) to speed up neighborhood reductions during +the final stage of the ``IntegralTransform`` layer, linked here: :ref:`gno_api`. + +``torch_scatter`` uses compiled CUDA kernels +to perform this reduction, providing both memory efficiency and speed advantages over a native PyTorch implementation. + +However, since these kernels are precompiled, it is crucial to install the version of ``torch_scatter`` that is built for +your specific combination of OS, PyTorch and CUDA. All available wheels can be found `here `_. + +.. note :: + The latest PyTorch version for which ``torch_scatter`` is built is 2.5.1, so you should downgrade if you are using + the latest (``torch>=2.6.0``) release: + + +To force-downgrade PyTorch, run + +.. code :: + + pip install -U torch==2.5.1 diff --git a/sources/neuraloperator/doc/source/modules/api.rst b/sources/neuraloperator/doc/source/modules/api.rst new file mode 100644 index 0000000000000000000000000000000000000000..4bec20f9408cc36b5cdb09e4e06f105db434f33d --- /dev/null +++ b/sources/neuraloperator/doc/source/modules/api.rst @@ -0,0 +1,832 @@ +.. _api_ref: + +############# +API reference +############# + +:mod:`neuralop`: Neural Operators in Python + +.. automodule:: neuralop.models + :no-members: + :no-inherited-members: + +.. _neuralop_models_ref: + +====== +Models +====== + +In :mod:`neuralop.models`, we provide neural operator models you can directly use on your applications. + +.. _fno_api: + +FNO +--- + +We provide a general Fourier Neural Operator (FNO) that supports most usecases. + +It works for any dimension, which is inferred based on `n_modes` +(a tuple with the number of modes to keep in the Fourier domain for each dimension.) + +.. autosummary:: + :toctree: generated + :template: class.rst + + FNO + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. _tfno_api: + +Tensorized FNO (TFNO) +--------------------- + +.. autosummary:: + :toctree: generated + :template: class.rst + + TFNO + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. _sfno_api: + +Spherical Fourier Neural Operators (SFNO) +----------------------------------------- + +.. autosummary:: + :toctree: generated + :template: class.rst + + SFNO + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. _gino_api: + +Geometry-Informed Neural Operators (GINO) +----------------------------------------- + +.. autosummary:: + :toctree: generated + :template: class.rst + + GINO + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. _local_no_api: + +Local Neural Operators (LocalNO) +-------------------------------- + +.. autosummary:: + :toctree: generated + :template: class.rst + + LocalNO + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. _uno_api: + +U-shaped Neural Operators (U-NO) +-------------------------------- + +.. autosummary:: + :toctree: generated + :template: class.rst + + UNO + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. _rno_api: + +Recurrent Neural Operators (RNO) +-------------------------------- + +.. autosummary:: + :toctree: generated + :template: class.rst + + RNO + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. _otno_api: + +Optimal Transport Neural Operators (OTNO) +----------------------------------------- + +.. autosummary:: + :toctree: generated + :template: class.rst + + OTNO + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. _uqno_api: + +Uncertainty Quantification Neural Operators (UQNO) +-------------------------------------------------- + +.. autosummary:: + :toctree: generated + :template: class.rst + + UQNO + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. _fnogno_api: + +Fourier/Geometry Neural Operators (FNOGNO) +------------------------------------------ + +.. autosummary:: + :toctree: generated + :template: class.rst + + FNOGNO + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. _codano_api: + +Codomain Attention Neural Operators (CODANO) +-------------------------------------------- + +.. autosummary:: + :toctree: generated + :template: class.rst + + CODANO + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. raw:: html + +
+ +.. _neuralop_layers_ref: + +====== +Layers +====== + +.. automodule:: neuralop.layers + :no-members: + :no-inherited-members: + + + +In addition to the full architectures, we also provide +in :mod:`neuralop.layers` building blocks, +in the form of PyTorch layers, that you can use to build your own models: + +.. _fno_blocks_api: + +FNO Blocks +---------- + +.. automodule:: neuralop.layers.fno_block + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: class.rst + + FNOBlocks + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. _rno_block_api: + +RNO Blocks +---------- + +.. automodule:: neuralop.layers.rno_block + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: class.rst + + RNOBlock + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. _spectral_conv_api: + +Fourier Convolutions +-------------------- +.. automodule:: neuralop.layers.spectral_convolution + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: class.rst + + SpectralConv + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. _spherical_conv_api: + +Spherical Convolutions +---------------------- + +.. automodule:: neuralop.layers.spherical_convolution + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: class.rst + + SphericalConv + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +.. _gno_api: + +Graph convolutions and kernel integration +----------------------------------------- + +.. automodule:: neuralop.layers.gno_block + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: class.rst + + GNOBlock + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. automodule:: neuralop.layers.integral_transform + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: class.rst + + IntegralTransform + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. _local_no_blocks_api: + +Local NO Blocks +--------------- +.. automodule:: neuralop.layers.local_no_block + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: class.rst + + LocalNOBlocks + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. _diff_conv_api: + +Local Integral/Differential Convolutions +---------------------------------------- + +.. automodule:: neuralop.layers.differential_conv + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: class.rst + + FiniteDifferenceConvolution + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. _disco_conv_api: + +Discrete-Continuous (DISCO) Convolutions +---------------------------------------- + +.. automodule:: neuralop.layers.discrete_continuous_convolution + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: class.rst + + DiscreteContinuousConv2d + DiscreteContinuousConvTranspose2d + EquidistantDiscreteContinuousConv2d + EquidistantDiscreteContinuousConvTranspose2d + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Codomain Attention (Transformer) Blocks +--------------------------------------- +.. automodule:: neuralop.layers.coda_layer + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: class.rst + + CODALayer + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Channel MLP +----------- + +.. automodule:: neuralop.layers.channel_mlp + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: class.rst + + ChannelMLP + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Embeddings +---------- + +Apply positional embeddings as additional channels on a function: + +.. automodule:: neuralop.layers.embeddings + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: class.rst + + GridEmbeddingND + GridEmbedding2D + SinusoidalEmbedding + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Neighbor search +--------------- + +Find neighborhoods on arbitrary coordinate meshes: + +.. automodule:: neuralop.layers.neighbor_search + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: class.rst + + NeighborSearch + +.. autosummary:: + :toctree: generated + :template: function.rst + + native_neighbor_search + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Domain Padding +-------------- + +.. automodule:: neuralop.layers.padding + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: class.rst + + DomainPadding + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Skip Connections +---------------- + +.. automodule:: neuralop.layers.skip_connections + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: function.rst + + skip_connection + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Normalization Layers +-------------------- + +.. automodule:: neuralop.layers.normalization_layers + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: class.rst + + AdaIN + InstanceNorm + BatchNorm + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Complex-value Support +--------------------- + +.. automodule:: neuralop.layers.complex + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: class.rst + + ComplexValued + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. raw:: html + +
+ + +================= +Model Dispatching +================= +We provide a utility function to create model instances from a configuration. +It has the advantage of doing some checks on the parameters it receives. + +.. automodule:: neuralop.models.base_model + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: function.rst + + get_model + available_models + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. raw:: html + +
+ +======== +Training +======== +We provide functionality that automates the boilerplate code associated with +training a machine learning model to minimize a loss function on a dataset: + +.. automodule:: neuralop.training + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: class.rst + + Trainer + IncrementalFNOTrainer + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Optimizers +---------- + +.. automodule:: neuralop.training.tensorgrad + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: class.rst + + TensorGRaD + TensorGRaDProjector + UnstructuredSparseProjector + +.. autosummary:: + :toctree: generated + :template: function.rst + + fno_tensorgrad_param_groups + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Training Utilities +------------------ + +.. automodule:: neuralop.training.torch_setup + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: function.rst + + setup + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Multi-Grid Patching +------------------- + +.. automodule:: neuralop.training.patching + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: class.rst + + MultigridPatching2D + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. raw:: html + +
+ +============== +Loss Functions +============== + +Data Losses +----------- + +.. automodule:: neuralop.losses.data_losses + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: class.rst + + LpLoss + H1Loss + HdivLoss + PointwiseQuantileLoss + MSELoss + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Equation Losses +--------------- + +Physics-informed loss functions: + +.. automodule:: neuralop.losses.equation_losses + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: class.rst + + BurgersEqnLoss + ICLoss + PoissonInteriorLoss + PoissonBoundaryLoss + PoissonEqnLoss + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Meta Losses +----------- + +Meta-losses for weighting composite loss functions. + +.. automodule:: neuralop.losses.meta_losses + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: class.rst + + WeightedSumLoss + Relobralo + SoftAdapt + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Differentiation +--------------- + +Numerical differentiation utilities: + +.. automodule:: neuralop.losses.differentiation + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: class.rst + + FourierDiff + FiniteDiff + +.. autosummary:: + :toctree: generated + :template: function.rst + + non_uniform_fd + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Spectral Projection +------------------- + +Spectral projection utilities for enforcing physical constraints: + +.. automodule:: neuralop.layers.spectral_projection + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: function.rst + + spectral_projection_divergence_free + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. raw:: html + +
+ +==== +Data +==== + +In `neuralop.data`, we provide APIs for standardizing PDE datasets (`.datasets`) and transforming raw data into model inputs (`.transforms`). + +Datasets +-------- + +We ship a small dataset for testing: + +.. automodule:: neuralop.data.datasets + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: function.rst + + load_darcy_flow_small + +We provide downloadable datasets for Darcy-Flow, Navier-Stokes, and Car-CFD. + +.. automodule:: neuralop.data.datasets.darcy + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: class.rst + + DarcyDataset + + +.. automodule:: neuralop.data.datasets.navier_stokes + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: class.rst + + NavierStokesDataset + + +.. automodule:: neuralop.data.datasets.car_cfd_dataset + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: class.rst + + CarCFDDataset + +.. _burgers_dataset_api: + +.. automodule:: neuralop.data.datasets.burgers + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: class.rst + + Burgers1dTimeDataset + +.. autosummary:: + :toctree: generated + :template: function.rst + + load_mini_burgers_1dtime + + +.. note:: + Additional datasets are available with optional dependencies: + + * **The Well Datasets**: Large-scale collection of diverse physics simulations + (requires `the_well` package) + * **Spherical Shallow Water Equations**: For spherical coordinate systems + (requires `torch_harmonics` package) + + These datasets are conditionally imported and may not be available + depending on your installation. + + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +DataProcessors +-------------- + +Much like PyTorch's `Torchvision.Datasets` module, our `data` module also includes +utilities to transform data from its raw form into the form expected by models and +loss functions: + +.. automodule:: neuralop.data.transforms.data_processors + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: class.rst + + DefaultDataProcessor + MGPatchingDataProcessor + IncrementalDataProcessor + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Normalizers +----------- + +Data normalization utilities: + +.. automodule:: neuralop.data.transforms.normalizers + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: class.rst + + UnitGaussianNormalizer + DictUnitGaussianNormalizer + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. raw:: html + +
+ +================= +Utility Functions +================= + +.. automodule:: neuralop.utils + :no-members: + :no-inherited-members: + +.. autosummary:: + :toctree: generated + :template: function.rst + + count_model_params + count_tensor_params + spectrum_2d + compute_rank + compute_stable_rank + compute_explained_variance diff --git a/sources/neuraloperator/doc/source/sg_execution_times.rst b/sources/neuraloperator/doc/source/sg_execution_times.rst new file mode 100644 index 0000000000000000000000000000000000000000..1ffb1feb19d36d5dcf637c448e6c745fb8ecd4b3 --- /dev/null +++ b/sources/neuraloperator/doc/source/sg_execution_times.rst @@ -0,0 +1,76 @@ + +:orphan: + +.. _sphx_glr_sg_execution_times: + + +Computation times +================= +**11:53.239** total execution time for 14 files **from all galleries**: + +.. container:: + + .. raw:: html + + + + + + + + .. list-table:: + :header-rows: 1 + :class: table table-striped sg-datatable + + * - Example + - Time + - Mem (MB) + * - :ref:`sphx_glr_auto_examples_models_plot_UNO_darcy.py` (``../../examples/models/plot_UNO_darcy.py``) + - 05:43.786 + - 0.0 + * - :ref:`sphx_glr_auto_examples_models_plot_FNO_darcy.py` (``../../examples/models/plot_FNO_darcy.py``) + - 02:29.545 + - 0.0 + * - :ref:`sphx_glr_auto_examples_training_plot_incremental_FNO_darcy.py` (``../../examples/training/plot_incremental_FNO_darcy.py``) + - 01:43.751 + - 0.0 + * - :ref:`sphx_glr_auto_examples_models_plot_SFNO_swe.py` (``../../examples/models/plot_SFNO_swe.py``) + - 00:47.029 + - 0.0 + * - :ref:`sphx_glr_auto_examples_layers_plot_DISCO_convolutions.py` (``../../examples/layers/plot_DISCO_convolutions.py``) + - 00:27.260 + - 0.0 + * - :ref:`sphx_glr_auto_examples_data_plot_darcy_flow.py` (``../../examples/data/plot_darcy_flow.py``) + - 00:26.995 + - 0.0 + * - :ref:`sphx_glr_auto_examples_data_gen_plot_burgers_2d_solver.py` (``../../examples/data_gen/plot_burgers_2d_solver.py``) + - 00:05.091 + - 0.0 + * - :ref:`sphx_glr_auto_examples_layers_plot_embeddings.py` (``../../examples/layers/plot_embeddings.py``) + - 00:03.764 + - 0.0 + * - :ref:`sphx_glr_auto_examples_data_gen_plot_diffusion_advection_solver.py` (``../../examples/data_gen/plot_diffusion_advection_solver.py``) + - 00:03.122 + - 0.0 + * - :ref:`sphx_glr_auto_examples_training_plot_count_flops.py` (``../../examples/training/plot_count_flops.py``) + - 00:01.531 + - 0.0 + * - :ref:`sphx_glr_auto_examples_data_plot_darcy_flow_spectrum.py` (``../../examples/data/plot_darcy_flow_spectrum.py``) + - 00:01.228 + - 0.0 + * - :ref:`sphx_glr_auto_examples_layers_plot_fourier_continuation.py` (``../../examples/layers/plot_fourier_continuation.py``) + - 00:00.089 + - 0.0 + * - :ref:`sphx_glr_auto_examples_layers_plot_neighbor_search.py` (``../../examples/layers/plot_neighbor_search.py``) + - 00:00.048 + - 0.0 + * - :ref:`sphx_glr_auto_examples_training_checkpoint_FNO_darcy.py` (``../../examples/training/checkpoint_FNO_darcy.py``) + - 00:00.000 + - 0.0 diff --git a/sources/neuraloperator/doc/source/theory_guide/advantages.rst b/sources/neuraloperator/doc/source/theory_guide/advantages.rst new file mode 100644 index 0000000000000000000000000000000000000000..0d4b8f847deeb48b2c13b0fd8b8f64f6467f4208 --- /dev/null +++ b/sources/neuraloperator/doc/source/theory_guide/advantages.rst @@ -0,0 +1,372 @@ +.. _neural_op_advantages: + +============================== +Advantages of Neural Operators +============================== + +This guide explores the key advantages of neural operators over traditional +neural networks and numerical methods for solving partial differential equations +and learning mappings between function spaces. + +Introduction +============ + +Neural operators represent a fundamental advancement in machine learning for +scientific computing, offering unique capabilities that address the limitations +of both traditional neural networks and classical numerical methods. +Unlike conventional approaches that operate on fixed discretizations, +neural operators are naturally formulated to work with functions, +enabling them to learn mappings between infinite-dimensional function spaces. + +The advantages of neural operators stem from their mathematical foundation in +operator theory and their ability to maintain consistency across different discretizations. +This guide examines these advantages in detail, drawing from both theoretical insights +and practical applications. + +.. raw:: html + +
+ +Mathematical Well-Posedness +=========================== + +The ground-truth mapping is an operator. + +The fundamental advantage of neural operators lies in their mathematical foundation. +In scientific computing, the problems we aim to solve are inherently operator learning tasks. +Consider a general differential equation: + +.. math:: + \mathcal{L}u = f + +where :math:`\mathcal{L}` is a differential operator, :math:`f` is the input function, +and :math:`u` is the solution function. + +Neural operators are designed to approximate these true operators directly, +rather than learning discretized approximations. This alignment with the underlying mathematical structure +ensures that the learned mapping respects the continuous nature of the problem. + + + +.. raw:: html + +
+ +Function Representation and Computational Flexibility +===================================================== + +The ability to output continuous functions is useful for follow-up computations. + +One of the most significant advantages of neural operators is their ability +to output continuous functions that can be queried at arbitrary coordinates. +This capability enables: + +**Arbitrary Resolution Inference** + Neural operators can be evaluated at any resolution without retraining, + enabling zero-shot super-resolution. This is particularly valuable when + high-resolution predictions are needed but training data is only available at + lower resolutions. + +.. raw:: html + +
+ +**Downstream Operations** + Since neural operators output functions rather than discrete values, + they enable natural computation of derivatives, integrals, and other mathematical + operations on the solution. + +.. raw:: html + +
+ +**Consistent Interpolation** + The output functions are consistent across different query points, + avoiding artifacts that might arise from discrete-to-continuous interpolation. + + + +.. raw:: html + +
+ +Universal Approximation Capability +================================== + +Fourier neural operators (and other neural operators) are universal operator approximators, +in the sense that any sufficiently smooth operator can be approximated to arbitrary accuracy using a +Fourier neural operator (see Theorem 5 in [4]). + +This also emphasizes the broad applicability of neural operators, as the same architecture +can be applied to diverse scientific problems, from fluid dynamics to materials science. + +Note however that, just like universal function approximation theorems for neural networks, +these are only theoretical guarantees, and there can be an important gap between theory and practice. +Although a sufficiently smooth operator can, in theory, be approximated by a neural operator +to any desired level of accuracy, achieving that accuracy in practice may not be possible because of +errors incurred when discretizing the input and output functions, and because of challenging optimization +landscapes which can result in suboptimally trained neural operators. + +.. raw:: html + +
+ +Solving Parametrized PDEs +========================= + +Traditional numerical methods solve one specific instance of a PDE with fixed parameters, +boundary conditions, and initial conditions. Neural operators, in contrast, +can learn solution operators for entire families of PDEs: + +**Parameter Flexibility** + A single neural operator can handle different parameter values + (e.g., different viscosities, conductivities, or material properties) without retraining. + +.. raw:: html + +
+ +**Boundary Condition Generalization** + The same model can work with various boundary conditions, from Dirichlet to Neumann + to mixed conditions. + +.. raw:: html + +
+ +**Geometry Adaptation** + Neural operators can generalize across different domain geometries, + making them valuable for shape optimization and design problems. + +.. raw:: html + +
+ +**Multi-Physics Capability** + A single operator can learn mappings for coupled systems involving multiple + physics phenomena. + +This capability is particularly valuable in engineering applications where rapid +evaluation across parameter spaces is essential for optimization, uncertainty +quantification, and design exploration. + +.. raw:: html + +
+ +Flexible Inference and Resolution Invariance +============================================ + +Neural operators can be queried at arbitrary resolution + +**Discretization Invariance** + Neural operators produce consistent results regardless of the input discretization. + The same model can process inputs on regular grids, irregular meshes, or even + point clouds, maintaining mathematical consistency. + +.. raw:: html + +
+ +**Resolution Convergence** + The approximation quality improves as the input resolution increases, with the + error vanishing in the limit of infinite resolution. + +.. raw:: html + +
+ +**Multi-Scale Capability** + A single neural operator can capture phenomena across multiple scales, + from fine-scale details to large-scale patterns. + +.. raw:: html + +
+ +**Computational Efficiency** + Once trained, neural operators can produce high-resolution solutions much + faster than traditional numerical methods, often achieving speedups of 100-1,000,000x! + + +.. raw:: html + +
+ +Data Efficiency and Training Advantages +======================================= + +Neural operators can learn from mixed-resolution datasets + +**Mixed-Resolution Training** + Neural operators can be trained on datasets containing samples at different resolutions, + making efficient use of available computational resources and data. + +.. raw:: html + +
+ +**Curriculum Learning** + Training can follow a curriculum: start with low-resolution samples for fast + initial learning, then progressively incorporate higher-resolution data for fine-tuning. + +.. raw:: html + +
+ +**Faster Training** + The ability to use low-resolution data for initial training significantly + reduces computational costs while maintaining learning effectiveness. + +.. raw:: html + +
+ +**Data Augmentation** + The same physical system can be represented at multiple resolutions, + effectively increasing the training dataset size. + +.. raw:: html + +
+ +**Transfer Learning** + Models trained on one resolution can be fine-tuned for different resolutions + with minimal additional training. + +.. raw:: html + +
+ +Practical Implementation Benefits +================================= + +**Memory Efficiency** + Neural operators can process high-resolution inputs without requiring + proportionally large memory, as they operate in function space rather than on dense + discretizations. + +.. raw:: html + +
+ +**Parallelization** + The function-to-function mapping nature of neural operators enables efficient + parallelization across different spatial and temporal scales. + +.. raw:: html + +
+ +**Robustness** + The continuous nature of the learned operators provides robustness to noise and + discretization artifacts. + +.. raw:: html + +
+ +**Interpretability** + The learned operators often have interpretable structure, with different components + corresponding to different physical phenomena. + +.. raw:: html + +
+ +Comparison with Traditional Methods +=================================== + +The advantages of neural operators become clear when compared to alternative approaches: + +**Traditional Neural Networks vs. Neural Operators** + + ================================ ================================== + Traditional Neural Networks Neural Operators + ================================ ================================== + Fixed discretization Resolution-invariant + Vector-to-vector mapping Function-to-function mapping + Limited generalization Universal approximation + Resolution-dependent training Mixed-resolution training + Discrete outputs Continuous function outputs + Single problem instance Parametrized family of problems + ================================ ================================== + +**Traditional Numerical Methods vs. Neural Operators** + + ================================ ================================== + Traditional Numerical Methods Neural Operators + ================================ ================================== + Solve one instance Learn solution operators + Require explicit PDE form Black-box, data-driven + Slow on fine grids Fast at all resolutions + High computational cost Fast inference after training + Parameter-specific Parameter-agnostic + ================================ ================================== + + +.. raw:: html + +
+ + +Conclusion +========== + +Neural operators represent a paradigm shift in scientific computing, offering advantages +that address fundamental limitations of both traditional neural networks and classical +numerical methods. Their mathematical foundation in operator theory, combined with +practical benefits like resolution invariance and computational efficiency, +makes them uniquely suited for the challenges of modern scientific computing. + +The key advantages (well-posedness, function representation, universal approximation, +parametrized PDE solving, flexible inference, and data efficiency) work together to +enable new capabilities in scientific computing that were previously impossible or +computationally prohibitive. + +As the field continues to develop, these advantages will likely expand further, +opening new possibilities for scientific discovery and engineering applications. + +.. raw:: html + +
+ +References +========== + +.. [1] Principled Approaches for Extending Neural Architectures to Function Spaces for Operator Learning, + Julius Berner, Miguel Liu-Schiaffini, Jean Kossaifi, Valentin Duruisseaux, + Boris Bonev, Kamyar Azizzadenesheli, Anima Anandkumar, 2025. + arXiv:2506.10973. https://arxiv.org/abs/2506.10973 + +.. raw:: html + +
+ +.. [2] Fourier Neural Operators Explained: A Practical Perspective + Valentin Duruisseaux, Jean Kossaifi, Anima Anandkumar, 2025. + https://arxiv.org/abs/2512.01421. + +.. raw:: html + +
+ +.. [3] Neural operator: Graph kernel network for partial differential equations, + Zongyi Li, Nikola Kovachki, Kamyar Azizzadenesheli, Burigede Liu, + Kaushik Bhattacharya, Andrew Stuart, Anima Anandkumar, 2020. + +.. raw:: html + +
+ +.. [4] Fourier Neural Operator for Parametric Partial Differential Equations, + Zongyi Li, Nikola Kovachki, Kamyar Azizzadenesheli, Burigede Liu, + Kaushik Bhattacharya, Andrew Stuart, Anima Anandkumar, 2020. + +.. raw:: html + +
+ +.. [5] Universal Approximation and Error Bounds for Fourier Neural Operators, + Nikola Kovachki, Samuel Lanthaler, and Siddhartha Mishra. + J. Mach. Learn. Res., vol. 22, no. 1, 2021. diff --git a/sources/neuraloperator/doc/source/theory_guide/applications.rst b/sources/neuraloperator/doc/source/theory_guide/applications.rst new file mode 100644 index 0000000000000000000000000000000000000000..0bd22a8b218ac7f0c99a9e6b3b29f01abe6db723 --- /dev/null +++ b/sources/neuraloperator/doc/source/theory_guide/applications.rst @@ -0,0 +1,526 @@ +.. _neural_op_applications: + +============================ +Neural Operator Applications +============================ + +This guide presents examples of neural operator applications across scientific and +engineering domains [1]_, demonstrating their transformative impact on computational +science and real-world problem solving. + +Introduction +============ + +Neural operators have been successfully applied to a wide variety of scientific and +engineering problems, from fluid dynamics and climate modeling to materials +science and biomedical applications. Their ability to learn mappings between +function spaces makes them particularly well-suited for problems involving +continuous physical phenomena governed by partial differential equations. + +The examples presented here span multiple scales, from molecular dynamics to climate systems, +and demonstrate the versatility of neural operators in handling complex, +multi-physics problems that were previously computationally prohibitive or +intractable with traditional methods. This is not an exhaustive list, but rather +a selection of representative applications that showcase the potential of neural operators. + +.. raw:: html + +
+ +Fluid and Solid Mechanics +========================= + +**Computational Mechanics Applications** + +Neural operators have fostered significant advancements in computational mechanics, +including modeling porous media, fluid mechanics, and solid mechanics [2]_ [3]_. +They offer substantial speedups over traditional numerical solvers while achieving +competitive accuracies and expanding their features [4]_ [5]_. + +**Turbulent Flow Modeling** + +Fourier Neural Operators (FNOs) constitute the first machine learning-based method +to successfully model turbulent flows with zero-shot super-resolution capabilities [6]_. +This breakthrough enables researchers to predict complex fluid behavior at resolutions +that were previously computationally prohibitive. The ability to generalize across +different Reynolds numbers and flow geometries makes FNOs particularly valuable for +industrial applications where traditional computational fluid dynamics methods would +require extensive computational resources. + +**Stabilization Techniques** + +Sobolev losses and dissipativity-inducing regularization terms are effective in +stabilizing long autoregressive rollouts for highly turbulent flows [7]_. These +techniques ensure that neural operators maintain physical consistency over extended +time periods, which is crucial for applications such as weather forecasting and +climate modeling where long-term stability is essential. + +**Large-Scale Simulations** + +Neural operators have also been used in large eddy simulations of three-dimensional +turbulence [5]_ and to learn the stress-strain fields in digital composites [8]_. +These applications demonstrate the versatility of neural operators in handling +complex multi-physics problems that involve multiple length and time scales. The +ability to learn from high-fidelity simulation data and then rapidly predict +solutions for new configurations makes neural operators invaluable for design +optimization and uncertainty quantification. + +**Probabilistic Modeling** + +Finally, neural operators have been used in combination with diffusion models on function +spaces to learn distributions over solutions when given sparse or noisy observations [9]_. +This capability is particularly important for real-world applications where data may be +incomplete or uncertain, enabling robust predictions even in the presence of measurement +noise or missing information. + +.. raw:: html + +
+ +Nuclear Fusion and Plasma Physics +================================= + +**Magnetohydrodynamic Simulations** + +Neural operators have been used to accelerate magnetohydrodynamic (MHD) simulations +for plasma evolution both from state and camera data [10]_ [11]_. This represents a +significant advancement in fusion energy research, where understanding plasma behavior +is crucial for developing sustainable fusion reactors. The ability to rapidly simulate +complex plasma dynamics enables researchers to explore a wider range of operating +conditions and design parameters than would be possible with traditional methods. + +**Plasma Instability Analysis** + +Instabilities arising in long-term rollouts using neural operators for plasma evolution +have been studied [12]_, together with the potential of learning across different MHD +simulation codes, data fidelities, and subsets of state variables. This research is +critical for understanding how plasma instabilities develop and propagate in fusion +devices, which directly impacts the efficiency and safety of fusion reactors. + +**Tokamak Discharge Classification** + +Furthermore, neural operators have been used for labeling the confinement states of +tokamak discharges [13]_. This application is particularly important for real-time +control of fusion experiments, where rapid classification of plasma states can help +operators make informed decisions about experimental parameters and safety protocols. +The ability to process high-dimensional plasma data in real-time represents a major +step forward in fusion energy research and development. + +.. raw:: html + +
+ +Geoscience and Environmental Engineering +======================================== + +**Seismic Wave Propagation and Inversion** + +In the geosciences, FNOs and UNOs have been used for seismic wave propagation and +inversion [14]_ [15]_. These applications are crucial for understanding Earth's +internal structure and for oil and gas exploration. The ability to rapidly process +seismic data and invert for subsurface properties enables geophysicists to make +more informed decisions about resource exploration and geological hazard assessment. + +**Earth Surface Movement Modeling** + +Extensions of generative models to function spaces have been employed to model earth +surface movements in response to volcanic eruptions or earthquakes, or subsidence +due to excessive groundwater extraction [16]_ [17]_. These applications are essential +for understanding natural hazards and their impact on human populations. The ability +to predict ground deformation patterns helps in disaster preparedness and mitigation +planning, particularly in regions prone to seismic activity or volcanic eruptions. + +**Multiphase Flow in Porous Media** + +Neural operators have also been used to model multiphase flow in porous media, which +is critical for applications such as contaminant transport, carbon capture and storage, +hydrogen storage, and nuclear waste storage [18]_ [19]_ [20]_. These applications are +increasingly important as society seeks to address climate change through carbon +capture technologies and transition to clean energy sources. The ability to accurately +model fluid flow in complex geological formations is crucial for ensuring the safety +and effectiveness of these technologies. + +.. raw:: html + +
+ +Weather and Climate Forecasting +=============================== + +**Numerical Weather Prediction** + +Versions of FNOs can match the accuracy of physics-based numerical weather +prediction systems while being orders-of-magnitude faster [4]_ [21]_. This represents +a paradigm shift in weather forecasting, enabling more frequent and higher-resolution +forecasts that can better capture local weather phenomena. The speed advantage of +neural operators allows for ensemble forecasting and rapid updates as new data becomes +available, which is crucial for severe weather warnings and emergency response. + +**Spherical Geometry Handling** + +To facilitate stable simulations of atmospheric dynamics on the earth, the spherical +Fourier neural operator (SFNO) has been introduced to extend FNOs to spherical +geometries [22]_. This development is particularly important for global weather +and climate modeling, where the Earth's spherical geometry must be properly +accounted for to avoid numerical artifacts and maintain physical consistency. +The SFNO enables accurate modeling of atmospheric circulation patterns and +large-scale climate phenomena. + +**Climate Data Downscaling** + +The super-resolution capabilities of FNOs have also been leveraged for downscaling +of climate data, i.e., predicting climate variables at high resolutions from +low-resolution simulations [23]_. This capability is essential for regional +climate impact assessments, where high-resolution local climate information is +needed for planning and adaptation strategies. The ability to downscale global +climate models to local scales enables more accurate assessment of climate change +impacts on specific regions and communities. + +**Climate Tipping Points** + +Additionally, neural operators have been utilized for tipping point forecasting, +with potential applications to climate tipping points [24]_. This research is +critical for understanding the potential for abrupt climate changes and their +cascading effects on global climate systems. The ability to identify and predict +climate tipping points could provide early warning systems for catastrophic +climate changes and inform mitigation strategies. + +.. raw:: html + +
+ +Medicine and Healthcare +======================= + +**Medical Imaging Applications** + +Neural operators have been used in multiple settings to improve medical imaging, +such as ultrasound computer tomography [25]_ [26]_ [27]_. These applications represent +a significant advancement in medical diagnostics, enabling more accurate and +rapid imaging procedures that can improve patient outcomes and reduce healthcare costs. + +**Lung Disease Diagnosis** + +As an example, they have been used on radio-frequency data from lung ultrasounds +to accurately reconstruct lung aeration maps, which can be used for diagnosing +and monitoring acute and chronic lung diseases [27]_. This application is particularly +important for respiratory medicine, where early detection of lung conditions can +significantly improve treatment outcomes. The ability to process ultrasound data +in real-time enables point-of-care diagnostics in resource-limited settings. + +**MRI Reconstruction** + +FNOs supplemented with local integral and differential kernels have been used for +MRI reconstructions [28]_ [29]_. This development is crucial for reducing scan times +and improving image quality in magnetic resonance imaging. The ability to reconstruct +high-quality images from undersampled data enables faster and more comfortable +patient experiences while maintaining diagnostic accuracy. + +**Medical Device Design** + +Neural operators have also been used to improve the design of medical devices, +such as catheters with reduced risk of catheter-associated urinary tract infection [30]_. +This application demonstrates the potential of neural operators in biomedical +engineering, where understanding fluid dynamics and material properties is crucial +for designing safer and more effective medical devices. + +**Spatial Transcriptomics** + +Finally, GNOs have been used for spatial transcriptomics data classification [31]_. +This application is at the forefront of precision medicine, where understanding +the spatial organization of gene expression in tissues can provide insights into +disease mechanisms and potential therapeutic targets. The ability to process +high-dimensional biological data efficiently enables researchers to explore +complex biological systems at unprecedented resolution. + +.. raw:: html + +
+ +Computer Vision +=============== + +Neural operators have been effectively adapted to computer vision tasks. +They have served as efficient token mixers in vision transformers [28]_, sped up diffusion +model sampling for faster image and media generation [29]_, and have been applied in +image classification [30]_ and segmentation [31]_. + +Their ability to handle images at multiple resolutions and integrate with existing deep +learning methods makes them a versatile tool for vision applications. + +.. raw:: html + +
+ +References +========== + +.. [1] Principled Approaches for Extending Neural Architectures to Function Spaces for Operator Learning, + Julius Berner, Miguel Liu-Schiaffini, Jean Kossaifi, Valentin Duruisseaux, + Boris Bonev, Kamyar Azizzadenesheli, Anima Anandkumar, 2025. + arXiv:2506.10973. https://arxiv.org/abs/2506.10973 + +.. raw:: html + +
+ +.. [2] Learning deep implicit Fourier neural operators (IFNOs) with applications to heterogeneous material modeling, + Huaiqian You, Quinn Zhang, Colton J Ross, Chung-Hao Lee, Yue Yu, 2022. + Computer Methods in Applied Mechanics and Engineering, 398, 115296. + +.. raw:: html + +
+ +.. [3] Fourier Neural Operator for Fluid Flow in Small-Shape 2D Simulated Porous Media Dataset, + A Choubineh, J Chen, DA Wood, F Coenen, F Ma, 2023. + Algorithms, 16(1), 24. + +.. raw:: html + +
+ +.. [4] FourCastNet: Accelerating Global High-Resolution Weather Forecasting Using Adaptive Fourier Neural Operators, + Thorsten Kurth, Shashank Subramanian, Peter Harrington, Jaideep Pathak, Morteza Mardani, + David Hall, Andrea Miele, Karthik Kashinath, Anima Anandkumar, 2023. + Proceedings of the Platform for Advanced Scientific Computing Conference. + +.. raw:: html + +
+ +.. [5] Fourier neural operator approach to large eddy simulation of three-dimensional turbulence, + Zhijie Li, Wenhui Peng, Zelong Yuan, Jianchun Wang, 2022. + Theoretical and Applied Mechanics Letters, 12(6), 100389. + +.. raw:: html + +
+ +.. [6] Efficient super-resolution of near-surface climate modeling using the Fourier neural operator, + P Jiang, Z Yang, J Wang, C Huang, P Xue, TC Chakraborty, 2023. + Journal of Advances in Modeling Earth Systems, 15. + +.. raw:: html + +
+ +.. [7] Learning the stress-strain fields in digital composites using Fourier neural operator, + Meer Mehran Rashid, Tanu Pittie, Souvik Chakraborty, N.M. Anoop Krishnan, 2022. + iScience, 25(11), 105452. + +.. raw:: html + +
+ +.. [8] Guided Diffusion Sampling on Function Spaces with Applications to PDEs, + Jiachen Yao, Abbas Mammadov, Julius Berner, Gavin Kerrigan, Jong Chul Ye, + Kamyar Azizzadenesheli, Anima Anandkumar, 2025. + arXiv:2505.17004. + +.. raw:: html + +
+ +.. [9] Plasma surrogate modelling using Fourier neural operators, + Vignesh Gopakumar, Stanislas Pamela, Lorenzo Zanisi, Zongyi Li, Ander Gray, + Daniel Brennand, Nitesh Bhatia, Gregory Stathopoulos, Matt Kusner, + Marc Peter Deisenroth, Anima Anandkumar, 2024. + Nuclear Fusion, 64(5), 056025. + +.. raw:: html + +
+ +.. [10] Neural-Parareal: Self-improving acceleration of fusion MHD simulations using time-parallelisation and neural operators, + S.J.P. Pamela, N. Carey, J. Brandstetter, R. Akers, L. Zanisi, J. Buchanan, + V. Gopakumar, M. Hoelzl, G. Huijsmans, K. Pentland, T. James, G. Antonucci, 2025. + Computer Physics Communications, 307, 109391. + +.. raw:: html + +
+ +.. [11] Robust Confinement State Classification with Uncertainty Quantification through Ensembled Data-Driven Methods, + Yoeri Poels, Cristina Venturini, Alessandro Pau, Olivier Sauter, Vlado Menkovski, + the TCV team, the WPTE team, 2025. + arXiv:2502.17397. + +.. raw:: html + +
+ +.. [12] Seismic wave propagation and inversion with neural operators, + Yan Yang, Angela F Gao, Jorge C Castellanos, Zachary E Ross, + Kamyar Azizzadenesheli, Robert W Clayton, 2021. + The Seismic Record, 1(3), 126-134. + +.. raw:: html + +
+ +.. [13] Accelerating Time-Reversal Imaging with Neural Operators for Real-time Earthquake Locations, + Hongyu Sun, Yan Yang, Kamyar Azizzadenesheli, Robert W Clayton, Zachary E Ross, 2022. + arXiv:2210.06636. + +.. raw:: html + +
+ +.. [14] Generative adversarial neural operators, + Md Ashiqur Rahman, Manuel A Florez, Anima Anandkumar, Zachary E Ross, + Kamyar Azizzadenesheli, 2022. + arXiv:2205.03017. + +.. raw:: html + +
+ +.. [15] Variational Autoencoding Neural Operators, + Jacob H Seidman, Georgios Kissas, George J Pappas, Paris Perdikaris, 2023. + arXiv:2302.10351. + +.. raw:: html + +
+ +.. [16] Real-time high-resolution CO2 geological storage prediction using nested Fourier neural operators, + Gege Wen, Zongyi Li, Qirui Long, Kamyar Azizzadenesheli, Anima Anandkumar, + Sally M Benson, 2023. + Energy Environ. Sci., 16(4), 1732-1741. + +.. raw:: html + +
+ +.. [17] Fourier Neural Operator based surrogates for CO2 storage in realistic geologies, + Anirban Chandra, Marius Koch, Suraj Pawar, Aniruddha Panda, + Kamyar Azizzadenesheli, Jeroen Snippe, Faruk O Alpak, Farah Hariri, + Clement Etienam, Pandu Devarakota, Anima Anandkumar, Detlef Hohl, 2025. + arXiv:2503.11031. + +.. raw:: html + +
+ +.. [18] Huge ensembles part i: Design of ensemble weather forecasts using spherical Fourier neural operators, + Ankur Mahesh, William Collins, Boris Bonev, Noah Brenowitz, Yair Cohen, + Joshua Elms, Peter Harrington, Karthik Kashinath, Thorsten Kurth, + Joshua North, 2024. + arXiv:2408.03100. + +.. raw:: html + +
+ +.. [19] Spherical Fourier neural operators: learning stable dynamics on the sphere, + Boris Bonev, Thorsten Kurth, Christian Hundt, Jaideep Pathak, Maximilian Baust, + Karthik Kashinath, Anima Anandkumar, 2023. + Proceedings of the 40th International Conference on Machine Learning (ICML). + +.. raw:: html + +
+ +.. [20] Fourier Neural Operators for Arbitrary Resolution Climate Data Downscaling, + Qidong Yang, Paula Harder, Venkatesh Ramesh, Alex Hernandez-Garcia, + Daniela Szwarcman, Prasanna Sattigeri, Campbell D Watson, David Rolnick, 2023. + ICLR 2023 Workshop on Tackling Climate Change with Machine Learning. + +.. raw:: html + +
+ +.. [21] Tipping Point Forecasting in Non-Stationary Dynamics on Function Spaces, + Miguel Liu-Schiaffini, Clare E Singer, Nikola Kovachki, Sze Chai Leung, Tapio Schneider, Hyunji Jane Bae, + Kamyar Azizzadenesheli, Anima Anandkumar, 2023. + arXiv:2308.08794. + +.. raw:: html + +
+ +.. [22] Ultrasound Lung Aeration Map via Physics-Aware Neural Operators, + Jiayun Wang, Oleksii Ostras, Masashi Sode, Bahareh Tolooshams, Zongyi Li, + Kamyar Azizzadenesheli, Gianmarco Pinton, Anima Anandkumar, 2025. + arXiv:2501.01157. + +.. raw:: html + +
+ +.. [23] A Unified Model for Compressed Sensing MRI Across Undersampling Patterns, + Armeet Singh Jatyani, Jiayun Wang, Aditi Chandrashekar, Zihui Wu, + Miguel Liu-Schiaffini, Bahareh Tolooshams, Anima Anandkumar, 2024. + arXiv:2410.16290. + +.. raw:: html + +
+ +.. [24] AI-aided geometric design of anti-infection catheters, + Tingtao Zhou, Xuan Wan, Daniel Zhengyu Huang, Zongyi Li, Zhiwei Peng, + Anima Anandkumar, John F Brady, Paul W Sternberg, Chiara Daraio, 2024. + Science Advances, 10(1). + +.. raw:: html + +
+ +.. [25] Neural Operator Learning for Ultrasound Tomography Inversion, + Haocheng Dai, Michael Penwarden, Robert M Kirby, Sarang Joshi, 2023. + arXiv:2304.03297. + +.. raw:: html + +
+ +.. [26] Neural Born Series Operator for Biomedical Ultrasound Computed Tomography, + Zhijun Zeng, Yihang Zheng, Youjia Zheng, Yubing Li, Zuoqiang Shi, He Sun, 2023. + arXiv:2312.15575. + +.. raw:: html + +
+ +.. [27] Graph Neural Operators for Classification of Spatial Transcriptomics Data, + Junaid Ahmed, Alhassan S Yasin, 2023. + arXiv:2302.00658. + +.. raw:: html + +
+ +.. [28] Adaptive Fourier neural operators: Efficient token mixers for transformers, + John Guibas, Morteza Mardani, Zongyi Li, Andrew Tao, Anima Anandkumar, + Bryan Catanzaro, 2021. + arXiv:2111.13587. + +.. raw:: html + +
+ +.. [29] Fast sampling of diffusion models via operator learning, + Hongkai Zheng, Weili Nie, Arash Vahdat, Kamyar Azizzadenesheli, Anima Anandkumar, 2023. + International Conference on Machine Learning. + +.. raw:: html + +
+ +.. [30] Resolution-invariant image classification based on Fourier neural operators, + Samira Kabri, Tim Roith, Daniel Tenbrinck, Martin Burger, 2023. + International Conference on Scale Space and Variational Methods in Computer Vision. + +.. raw:: html + +
+ +.. [31] FNOSeg3D: Resolution-Robust 3D Image Segmentation with Fourier Neural Operator, + Ken CL Wong, Hongzhi Wang, Tanveer Syeda-Mahmood, 2023. + 2023 IEEE 20th International Symposium on Biomedical Imaging (ISBI). + + +.. raw:: html + +
\ No newline at end of file diff --git a/sources/neuraloperator/doc/source/theory_guide/fno.rst b/sources/neuraloperator/doc/source/theory_guide/fno.rst new file mode 100644 index 0000000000000000000000000000000000000000..5190ca6ed0be72b561e1a1b0466c25e07c4bc17f --- /dev/null +++ b/sources/neuraloperator/doc/source/theory_guide/fno.rst @@ -0,0 +1,558 @@ +.. _fno_intro: + +======================== +Fourier Neural Operators +======================== + + +This guide introduces the Fourier neural operator (FNO) which can be used to solve a family of PDEs from scratch. +It is the first work that can learn resolution-invariant solution operators for the Navier-Stokes equation, +achieving state-of-the-art accuracy among all existing deep learning methods and +up to 1000x faster than traditional solvers. + +Check out the original FNO paper [1]_ and the comprehensive practical guide to FNOs [2]_ for more details. + +.. raw:: html + +
+ +Operator learning +================= + +Problems in science and engineering involve solving +partial differential equations (PDE) systems. +Unfortunately, these PDEs can be very hard. +Traditional PDE solvers such as finite element methods (FEM) and finite difference methods (FDM) +rely on discretizing the space into a very fine mesh. +This can be slow and inefficient. + +Thinking in continuous space gives us an advantage when dealing with PDEs since these typically +involve solving for functions on a continuous domain. +We want to design mesh-independent, resolution-invariant operators. + +In the previous :ref:`neuralop_intro` guide, +we introduced the neural operators that use neural networks +to learn the solution operators for PDEs. +That is, given the initial conditions or the boundary conditions, +the neural network directly outputs the solution of the PDE on a fixed discretization or mesh, +kind of like an image-to-image mapping. + +The neural operator is mesh-independent, +different from the standard deep learning methods such as CNN. +It can be trained on one mesh and evaluated on another. +By parameterizing the model in function space, +it learns the continuous solution function instead of discretized vectors. + + + ========================================== ====================================== + Conventional PDE solvers Neural operators + ========================================== ====================================== + Solve one instance Learn a family of PDEs + Require the explicit form Black-box, data-driven + Speed-accuracy trade-off on resolution Resolution-invariant, mesh-invariant + Slow on fine grids; fast on coarse grids Slow to train; fast to evaluate + ========================================== ====================================== + +Operator learning can be viewed as an image-to-image problem. +In the Fourier Neural Operator, +the Fourier layer can be viewed as a substitute for the convolution layer. + + +.. raw:: html + +
+ +Framework of Neural Operators +============================= + +Just like how neural networks consist of linear transformations and non-linear activation functions, +neural operators consist of linear operators and non-linear activation operators. + +Let :math:`v` be the input vector, :math:`u` be the output vector. +A standard deep neural network can be written in the form: + +.. math:: + u = (K_l \circ \sigma_l \circ \ldots \circ \sigma_1 \circ K_0)(v) + +where :math:`K` are the linear layer or convolution layer, +and :math:`\sigma` are the activation function such as ReLU. + +The neural operator shares a similar framework. +The only difference is that now :math:`v` and :math:`u` are functions with can be given on different discretizations +(say, some inputs are :math:`28 \times 28`, some are :math:`256 \times 256`, +and some are in triangular mesh). +To deal with functions input, the linear transformation :math:`K` is formulated as an integral operator. +Let :math:`x, y` be the points in the domain. + +The map :math:`K: v_{t} \mapsto v_{t+1}` is parameterized as + +.. math:: + v'(x) = \int \kappa(x,y) v(y) dy + W v(x) + +where :math:`\kappa` is a kernel function and :math:`W` is the bias term. + +For the Fourier neural operator, we formulate :math:`K` as a convolution +and implement it using the Fourier transform. + +.. raw:: html + +
+ +Fourier Layer +============= +Real-world images have lots of edges and shapes, +so CNNs can capture them well with a local convolution kernel. +On the other hand, the inputs and outputs of PDEs are continuous functions. +It is more efficient to represent them in Fourier space and do a global convolution. + +There are two main motivations for using the Fourier transform. +First, it is fast. A full standard integration of :math:`n` points has complexity :math:`O(n^2)`, +while convolution via Fourier transform on a regular grid is quasilinear. +Second, it is efficient. The inputs and outputs of PDEs are continuous functions. +So it is usually more efficient to represent them in Fourier space. + +Convolution in the spatial domain is equivalent to a pointwise multiplication in the Fourier domain. To implement the (global) convolution operator, +we first do a Fourier transform, then a linear transform, and an inverse Fourier transform. +As shown in the top part of the figure: + +.. image:: /_static/images/fourier_layer.jpg + :width: 800 + +The Fourier layer just consists of three steps: + - Fourier transform :math:`\mathcal{F}` + - Linear transform on the lower Fourier modes :math:`R` + - Inverse Fourier transform :math:`\mathcal{F}^{-1}` + + +We then add the output of the Fourier layer +with the bias term :math:`W v` (a linear transformation) +and apply the activation function :math:`\sigma`. +Simple as it is. + +In practice, it is usually sufficient to only take the lower-frequency modes +and truncate out these higher-frequency modes. +Therefore, we apply the linear transformation on the lower-frequency modes +and set the higher modes to zeros. + +Notice that the activation functions shall be applied on the spatial domain. +They help to recover the higher-frequency modes and non-periodic boundary +which are left out in the Fourier layers. +Therefore, it is necessary to add them after the inverse Fourier transform at each layer. + +.. _fourier_layer_impl : +.. raw:: html + +
+ +Implementation +============== + +We can easily create a 2D Fourier layer using `neuralop` as follows: + +.. code:: python + + from neuralop.models.spectral_convolution import FactorizedSpectralConv + fourier_layer = FactorizedSpectralConv(in_channels=in_channels, out_channels=out_channels, n_modes=(modes1, modes2)) + +To illustrate the implementation details of the Fourier layer, we provide a simple implementation from scratch that is equivalent to the above code based on PyTorch's fast Fourier transform (FFT) :code:`torch.fft.rfft()` and :code:`torch.fft.irfft()`. + +.. code:: python + + import torch + import torch.nn as nn + + class SpectralConv2d(nn.Module): + """ + 2D spectral convolution layer for Fourier Neural Operators. + Performs convolution in Fourier space by truncating high-frequency modes. + """ + def __init__(self, + in_channels, # Number of input channels + out_channels, # Number of output channels + modes1, # Number of Fourier modes to multiply in the first dimension + modes2): # Number of Fourier modes to multiply in the second dimension + super(SpectralConv2d, self).__init__() + + self.in_channels = in_channels + self.out_channels = out_channels + self.modes1 = modes1 + self.modes2 = modes2 + + self.scale = (1 / (in_channels * out_channels)) + self.weights1 = nn.Parameter(self.scale * torch.rand(in_channels, out_channels, self.modes1, self.modes2, dtype=torch.cfloat)) + self.weights2 = nn.Parameter(self.scale * torch.rand(in_channels, out_channels, self.modes1, self.modes2, dtype=torch.cfloat)) + + def forward(self, x): + """ + Forward pass of the spectral convolution layer. + + Parameters + ---------- + x : torch.Tensor + Input tensor (batch_size, in_channels, height, width) + + Returns + ------- + torch.Tensor + Output tensor (batch_size, out_channels, height, width) + """ + batchsize = x.shape[0] + # Compute Fourier coefficients + x_ft = torch.fft.rfft2(x) + + # Multiply relevant Fourier modes + out_ft = torch.zeros(batchsize, self.out_channels, x.size(-2), x.size(-1)//2 + 1, dtype=torch.cfloat, device=x.device) + out_ft[:, :, :self.modes1, :self.modes2] = \ + self.compl_mul2d(x_ft[:, :, :self.modes1, :self.modes2], self.weights1) + out_ft[:, :, -self.modes1:, :self.modes2] = \ + self.compl_mul2d(x_ft[:, :, -self.modes1:, :self.modes2], self.weights2) + + # Return to physical space + x = torch.fft.irfft2(out_ft, s=(x.size(-2), x.size(-1))) + return x + + def compl_mul2d(self, input, weights): + """ + Complex matrix multiplication for Fourier coefficients. + + Parameters + ---------- + input : torch.Tensor + Input Fourier coefficients + weights : torch.Tensor + Learnable weight matrix + + Returns + ------- + torch.Tensor + Result of the complex matrix multiplication + """ + # (batch, in_channel, x,y ), (in_channel, out_channel, x, y) -> (batch, out_channel, x, y) + return torch.einsum("bixy,ioxy->boxy", input, weights) + +where the input :code:`x` has the shape :code:`(N, C, H, W)`, +:code:`self.weights1` and :code:`self.weights2` are the weight matrices; +:code:`self.modes1` and :code:`self.modes2` truncate the lower-frequency modes; +and :code:`compl_mul2d()` is the matrix multiplication for complex numbers. + +Note in the forward call above that :code:`torch.fft.rfft()` returns a matrix +of size :code:`n` along each dim that indexes Fourier modes :code:`0, 1, 2, ... n//2, -n//2, -n//2 - 1, ...-1`. Since our +inputs are real-valued, we take the real-valued FFT, which is skew-symmetric, so information is repeated across +one axis. Therefore it is sufficient to keep only two of the four corners of the FFT matrix. + +.. raw:: html + +
+ +Shifting the FFT signal +----------------------- + +.. _fft_shift_explanation: + +Equivalently, we could also apply a periodic FFT-shift using :code:`torch.fft.fftshift` to move the zero-frequency component +to the center of the FFT matrix, such that the matrix would be indexed with modes :code:`-n//2, -n//2 + 1, ...-1, 0, 1, ...` +as shown below: + +.. figure:: /_static/images/fft_shift.png + :width: 800 + + Visualizing the Fourier coefficients as returned by the Real Fast Fourier Transform implementation in PyTorch. + Using :code:`torch.fft.fftshift`, we move the zero-frequency mode to the center and truncate modes + from the middle out. Note that the last half of modes are only redundant when using the real-valued Fourier + transform. For more details, see the source paper [3]_. + +.. raw:: html + +
+ +Convolutional Filters in Fourier Space +-------------------------------------- + +.. image:: /_static/images/filters.jpg + :width: 800 + +Filters in convolution neural networks are usually local. +They are good for capturing local patterns such as edges and shapes. +Fourier filters are global sinusoidal functions. +They are better for representing continuous functions. + + +.. raw:: html + +
+ +Higher-frequency modes and non-periodic boundary +------------------------------------------------ +The Fourier layer on its own loses higher-frequency modes +and works only with periodic boundary conditions. +However, the Fourier neural operator as a whole does not have these limitations +(examples shown in the experiments). +The encoder-decoder structure +helps to recover the higher Fourier modes. +And the bias term :math:`W` +helps to recover the non-periodic boundary. + +.. raw:: html + +
+ +Complexity +---------- +The Fourier layer has a quasilinear complexity. +Denote the number of points (pixels) :math:`n` and truncating at :math:`k_{max}` frequency modes. +The multiplication has complexity :math:`O(k_{max}) < O(n)`. +The majority of the computational cost lies in computing the Fourier transform and its inverse. +General Fourier transforms have complexity :math:`O(n^2)`, +however, since we truncate the series the complexity is in fact :math:`O(n k_{max})`, +while the FFT has complexity :math:`O(n \log n)`. + +.. raw:: html + +
+ +Resolution-invariance +--------------------- +The Fourier layers are discretization-invariant, +because they can learn from and evaluate functions +which are discretized in an arbitrary way. +Since parameters are learned directly in Fourier space, +resolving the functions in physical space simply amounts to projecting on the basis +of wave functions which are well-defined everywhere on the space. +This allows us to transfer among discretizations. +If implemented with standard FFT, then it will be restricted to uniform mesh, +but it is still resolution-invariant. + +.. raw:: html + +
+ +Experiments +=========== + +.. raw:: html + +
+ +Burgers Equation +---------------- +The 1D Burgers’ equation is a non-linear PDE with various applications +including modeling the one-dimensional flow of a viscous fluid. It takes the form + +.. math:: + \partial_t u(x,t) + \partial_x ( u^2(x,t)/2) = \nu \partial_{xx} u(x,t), \qquad x \in (0,1), t \in (0,1] + +.. math:: + u(x,0) = u_0(x), \qquad \qquad \:\: x \in (0,1) + +with periodic boundary conditions where :math:`u_0 \in L^2_{\text{per}}((0,1);\mathbb{R})` +is the initial condition and :math:`\nu \in \mathbb{R}_+` is the viscosity coefficient. +We aim to learn the operator mapping the initial condition to the solution +at time one, defined by :math:`u_0 \mapsto u(\cdot, 1)` for any :math:`r > 0`. + + ========== ======== ======== ======== ======== ======== ======== + Networks s=256 s=512 s=1024 s=2048 s=4096 s=8192 + ========== ======== ======== ======== ======== ======== ======== + FCN 0.0958 0.1407 0.1877 0.2313 0.2855 0.3238 + PCA+NN 0.0398 0.0395 0.0391 0.0383 0.0392 0.0393 + LNO 0.0212 0.0221 0.0217 0.0219 0.0200 0.0189 + FNO 0.0149 0.0158 0.0160 0.0146 0.0142 0.0139 + ========== ======== ======== ======== ======== ======== ======== + + +.. raw:: html + +
+ +Darcy Flow +---------- + +We consider the steady state of the 2D Darcy Flow equation +on the unit box which is a second order, linear, elliptic PDE + +.. math:: + - \nabla \cdot (a(x) \nabla u(x)) = f(x) \qquad x \in (0,1)^2 + +.. math:: + u(x) = 0 \qquad \quad \:\:x \in \partial (0,1)^2 + +with a Dirichlet boundary condition where :math:`a \in L^\infty\left({(0,1)}^2;\mathbb{R}_+\right)` is the diffusion coefficient and :math:`f \in L^2\left({(0,1)}^2;\mathbb{R}\right)` is the forcing function. +This PDE has numerous applications including modeling the pressure of the subsurface flow, +the deformation of linearly elastic materials, and the electric potential in conductive materials. +We are interested in learning the operator mapping the diffusion coefficient to the solution, +defined by :math:`a \mapsto u`. Note that although the PDE is linear, the solution operator is not. + + ========== ======== ======== ======== ======== + Networks s=85 s=141 s=211 s=421 + ========== ======== ======== ======== ======== + FCN 0.0253 0.0493 0.0727 0.1097 + PCA+NN 0.0299 0.0298 0.0298 0.0299 + RBM 0.0244 0.0251 0.0255 0.0259 + LNO 0.0520 0.0461 0.0445 - + FNO 0.0108 0.0109 0.0109 0.0098 + ========== ======== ======== ======== ======== + +.. image:: /_static/images/fourier_error.jpg + :width: 800 + +.. raw:: html + +
+ +Benchmarks for time-independent problems (Burgers and Darcy): +------------------------------------------------------------- + + - NN: a simple point-wise feedforward neural network. + - RBM: the classical Reduced Basis Method (using a POD basis). + - FCN: a state-of-the-art neural network architecture based on Fully Convolution Networks. + - PCANN: an operator method using PCA as an autoencoder on both the input and output data and interpolating the latent spaces with a neural network. + - GNO: the original graph neural operator. + - MGNO: the multipole graph neural operator. + - LNO: a neural operator method based on the low-rank decomposition of the kernel. + - FNO: the newly purposed Fourier neural operator. + +.. raw:: html + +
+ +Navier-Stokes Equation +---------------------- + +We consider the 2D Navier-Stokes equation for a viscous, +incompressible fluid in vorticity form on the unit torus: + +.. math:: + \partial_t w(x,t) + u(x,t) \cdot \nabla w(x,t) = \nu \Delta w(x,t) + f(x), \qquad x \in (0,1)^2, t \in (0,T] + +.. math:: + \nabla \cdot u(x,t) = 0, \qquad \qquad x \in (0,1)^2, t \in [0,T] + +.. math:: + w(x,0) = w_0(x), \qquad \qquad \qquad x \in (0,1)^2 + +where :math:`u` is the velocity field, +:math:`w = \nabla \times u` is the vorticity, +:math:`w_0` is the initial vorticity, +:math:`\nu` is the viscosity coefficient, +and :math:`f` is the forcing function. +We are interested in learning the operator mapping the vorticity up to time 10 +to the vorticity up to some later time :math:`T > 10`, +defined by :math:`w|_{(0,1)^2 \times [0,10]} \mapsto w|_{(0,1)^2 \times (10,T]}`. +We experiment with the viscosities +:math:`\nu = 1\mathrm{e}{-3}, 1\mathrm{e}{-4}, 1\mathrm{e}{-5}`, +decreasing the final time :math:`T` as the dynamic becomes chaotic. + + ========= ============ ============= ======== ======== ======== + Configs Parameters Time/epoch ν=1e-3 ν=1e-4 ν=1e-5 + ========= ============ ============= ======== ======== ======== + FNO-3D 6,558,537 38.99s 0.0086 0.0820 0.1893 + FNO-2D 414,517 127.80s 0.0128 0.0973 0.1556 + U-Net 24,950,491 48.67s 0.0245 0.1190 0.1982 + TF-Net 7,451,724 47.21s 0.0225 0.1168 0.2268 + ResNet 266,641 78.47s 0.0701 0.2311 0.2753 + ========= ============ ============= ======== ======== ======== + +.. image:: /_static/images/fourier_ns1e4.jpg + :width: 800 + +.. raw:: html + +
+ +Benchmarks for time-dependent problems (Navier-Stokes): + + - ResNet: 18 layers of 2-d convolution with residual connections. + - U-Net: A popular choice for image-to-image regression tasks consisting of four blocks with 2-d convolutions and deconvolutions. + - TF-Net: A network designed for learning turbulent flows based on a combination of spatial and temporal convolutions. + - FNO-2d: 2D Fourier neural operator with an RNN structure in time. + - FNO-3d: 3D Fourier neural operator that directly convolves in space-time. + + +The FNO-3D has the best performance +when there is sufficient data +(:math:`\nu=1\mathrm{e}{-3}, N=1000` and :math:`\nu=1\mathrm{e}{-4}, N=10000`). +For the configurations where the amount of data is insufficient +(:math:`\nu=1\mathrm{e}{-4}, N=1000` and :math:`\nu=1\mathrm{e}{-5}, N=1000`), +all methods have :math:`>15\%` error with FNO-2D achieving the lowest. +Note that we only present results for spatial resolution :math:`64 \times 64` +since all benchmarks we compare against are designed for this resolution. +Increasing it degrades their performance while FNO achieves the same errors. + +FNO-2D, U-Net, TF-Net, and ResNet all use 2D convolution in the spatial domain +and recurrently propagate in the time domain (2D+RNN). +On the other hand, FNO-3D performs convolution in space-time. + +.. raw:: html + +
+ +Bayesian Inverse Problem +------------------------ + +In this experiment, we use a function space Markov chain Monte Carlo (MCMC) method +to draw samples from the posterior distribution of the initial vorticity +in Navier-Stokes given sparse, noisy observations at time :math:`T=50`. +We compare the Fourier neural operator acting as a surrogate model +with the traditional solvers used to generate our train-test data (both run on GPU). +We generate 25,000 samples from the posterior (with a 5,000 sample burn-in period), +requiring 30,000 evaluations of the forward operator. + +.. image:: /_static/images/fourier_bayesian.jpg + :width: 800 + +The top left panel shows the true initial vorticity while the bottom left panel shows +the true observed vorticity at :math:`T=50` with black dots indicating +the locations of the observation points placed on a :math:`7 \times 7` grid. +The top middle panel shows the posterior mean of the initial vorticity +given the noisy observations estimated with MCMC using the traditional solver. +while the top right panel shows the same thing but using FNO as a surrogate model. +The bottom middle and right panels show the vorticity at :math:`T=50` +when the respective approximate posterior means are used as initial conditions. + +.. raw:: html + +
+ +Conclusion +========== +We propose a neural operator based on the Fourier transform. +It is the first work that learns the resolution-invariant solution operator +for the family of Navier-Stokes equation in the turbulent regime, +where previous graph-based neural operators do not converge. +By construction, the method shares the same learned network parameters +irrespective of the discretization used on the input and output spaces. +It can do zero-shot super-resolution: trained on a lower resolution +and directly evaluated on a higher resolution. +The proposed method consistently outperforms all existing deep learning methods for parametric PDEs. +It achieves error rates that are :math:`30\%` lower on Burgers’ Equation, +:math:`60\%` lower on Darcy Flow, and :math:`30\%` lower on Navier Stokes +(turbulent regime with Reynolds number :math:`10000`). +On a :math:`256 \times 256` grid, +the Fourier neural operator has an inference time of only :math:`0.005` +compared to the :math:`2.2s` of the pseudo-spectral method used to solve Navier-Stokes. + +.. raw:: html + +
+ +References +========== + +.. [1] Fourier Neural Operator for Parametric Partial Differential Equations, + Zongyi Li and Nikola Kovachki and Kamyar Azizzadenesheli + and Burigede Liu and Kaushik Bhattacharya and Andrew Stuart and Anima Anandkumar, 2020. + +.. raw:: html + +
+ +.. [2] Fourier Neural Operators Explained: A Practical Perspective + Valentin Duruisseaux, Jean Kossaifi, Anima Anandkumar, 2025. + https://arxiv.org/abs/2512.01421. + +.. raw:: html + +
+ +.. [3] Multi-Grid Tensorized Fourier Neural Operator for High-Resolution PDEs, + Jean Kossaifi, Nikola Kovachki, Kamyar Azizzadenesheli, Anima Anandkumar, 2024. + TMLR 2024. https://openreview.net/pdf?id=AWiDlO63bH diff --git a/sources/neuraloperator/doc/source/theory_guide/index.rst b/sources/neuraloperator/doc/source/theory_guide/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..d0f8faf857cc343fb9b7414ba931d3d391fedfe0 --- /dev/null +++ b/sources/neuraloperator/doc/source/theory_guide/index.rst @@ -0,0 +1,59 @@ + +Theory Guide +============ + +.. toctree:: + :hidden: + + neural_operators + fno + advantages + applications + +This section contains a comprehensive primer on the theoretical foundations of operator learning, +an introduction to the Fourier Neural Operator, an exploration of the key advantages of neural operators, +and a showcase of diverse applications across scientific and engineering domains. +These guides provide the mathematical background and practical insights needed to understand +neural operators for solving partial differential equations. + +.. card:: Introduction to Neural Operators + :link: neural_operators + :link-type: doc + :class-body: sd-text-muted + :img-bottom: /_static/images/nik_kernel.jpg + + A comprehensive introduction to operator learning and neural operators. + + Learn the mathematical foundations, kernel formulations, and how neural operators + generalize across different discretizations to solve PDEs efficiently. + +.. card:: The Fourier Neural Operator + :link: fno + :link-type: doc + :class-body: sd-text-muted + :img-bottom: /_static/images/fourier_ns1e4.jpg + + A practitioner's guide to the Fourier Neural Operator. + + Discover how FNOs achieve state-of-the-art performance on challenging PDEs + like Navier-Stokes equations with up to 1000x speedup over traditional solvers. + +.. card:: Advantages of Neural Operators + :link: advantages + :link-type: doc + :class-body: sd-text-muted + + Explore the key advantages of neural operators over traditional methods. + + Learn about resolution invariance, universal approximation, flexible inference, + and data efficiency that make neural operators uniquely powerful for scientific computing. + +.. card:: Examples of Neural Operator Applications + :link: applications + :link-type: doc + :class-body: sd-text-muted + + Discover diverse examples of neural operator applications across scientific domains. + + Explore real-world applications in fluid dynamics, climate modeling, materials science, + biomedical engineering, and more, showcasing the transformative impact of neural operators. \ No newline at end of file diff --git a/sources/neuraloperator/doc/source/theory_guide/neural_operators.rst b/sources/neuraloperator/doc/source/theory_guide/neural_operators.rst new file mode 100644 index 0000000000000000000000000000000000000000..6c04d814f1c7f094eac80af54831a31e952e1df8 --- /dev/null +++ b/sources/neuraloperator/doc/source/theory_guide/neural_operators.rst @@ -0,0 +1,472 @@ +.. _neuralop_intro: + +================================= +Neural Operators: an Introduction +================================= + + +This guide introduces neural operators, a class of models that learn +mappings between function spaces and solve partial differential equations. +You can also check out the papers [1]_ [2]_ [3]_ [4]_ for more details. + +Introduction +============ + +Scientific computations are often very costly in terms of time and resources. +For example, running numerical simulations of fluid dynamics or many-body systems +can take days or even months. +This high cost is largely due to the need for numerical solvers to discretize +space and time into extremely fine grids in order to achieve acceptable accuracy. +Solving the resulting large number of equations on these grids is computationally intensive. + + +To address these challenges, researchers have started to develop data-driven +approaches using machine learning. +Rather than explicitly solving the equations for each new scenario, data-driven solvers are +trained on data that pairs problems with their solutions. +Once trained, these solvers can quickly make predictions for new problems based on input data. +Because they do not require breaking the domain into tiny pieces and solving every equation +from scratch, data-driven methods are often much faster than traditional numerical solvers. + +However, data-driven solvers are subject to the quality of the input and training data. +If the training data is not good enough, they will learn to emulate that unreliable data +and will not make good predictions. +In scientific computing, usually, the training data are generated by traditional numerical solvers, +and it can still take days or months for these numerical solvers to generate good enough data. +In some cases, data are gathered directly from experiments, and high-quality training data +may be unavailable. + +Neural networks are often regarded as powerful interpolators, but their ability to extrapolate +to unseen scenarios remains uncertain. This raises questions about their capacity to generalize +beyond the specific conditions represented in the training data. +For example, if training data are generated at a particular resolution, the resulting +learned models may only work effectively at that resolution. +Overall, generalization is a fundamental challenge in machine learning. +As a result, while machine learning-based methods can significantly speed up evaluation, +the process of obtaining and preparing suitable training data can remain time-consuming and difficult. + +To address this challenge, we introduce operator learning. By encoding appropriate structures, +we enable neural networks to learn mappings between functions and to generalize across different discretizations. +This means we can use numerical methods to generate less-accurate, low-resolution data, +yet the trained solver can still produce accurate, high-resolution predictions. +As a result, both training and evaluation can become significantly more efficient and straightforward. + +.. raw:: html + +
+ +Operator Learning +================= + +In mathematics, the term "operator" commonly refers to a mapping between function spaces. +You have likely encountered familiar operators such as differentiation and integration. +Applying a derivative or performing an indefinite integration on a function transforms it into another function, +which are both classic examples of operators acting on function spaces. + +In scientific computing, the core challenge often involves solving differential equations, which inherently relate operators to function spaces. Consider a general differential equation of the form: + +.. math:: + \mathcal{L}u = f + +where :math:`u` and :math:`f` are some functions on the physical domain, and +:math:`\mathcal{L}` is some differential operator that maps +the function :math:`u` to the function :math:`f`. +In most cases, :math:`\mathcal{L}` and :math:`f` are specified, and +the objective is to find the solution :math:`u`. +Viewed from this perspective, solving a PDE is fundamentally an operator learning task: +we wish to learn the mapping from input functions to solution functions. + +Traditionally, neural networks have been designed to model mappings +between finite-dimensional Euclidean spaces, such as classifying an image +(represented as a vector of pixel intensities) into a label, or transforming one image vector into another. +While effective for many tasks, this framework is inherently limited when addressing scientific +and mathematical problems that require learning mappings between entire function spaces. +In these cases, rather than learning simple vector-to-vector transformations, we seek to learn operators: +transformations that act on functions and produce new functions, which is a more complex and general task. + +This challenge is not restricted to the domain of differential equations; operator learning +is implicit in many machine learning applications. +For instance, even images can be more accurately viewed as continuous functions of light intensity +over a spatial domain, rather than as discrete :math:`32 \times 32` pixel arrays. +By embracing this perspective, we gain the flexibility to reason about, and learn mappings between, +functions defined on arbitrary continuous domains, transcending the constraints of fixed discretizations. + +We discuss how to generalize neural networks so that they can learn operators, +the mappings between infinite-dimensional spaces, with a special focus on PDEs. +For a comprehensive guide on principled approaches for extending neural architectures +to function spaces for operator learning, see [3]_. + +.. raw:: html + +
+ +Limitation of Fixed Discretization +================================== + +Solving partial differential equations (PDEs) is a notoriously challenging task. +Rather than working directly with operators on infinite-dimensional function spaces, +the standard approach is to discretize the physical domain and reformulate the problem in a finite-dimensional Euclidean setting. +Over the past century, this has led to the development of powerful numerical methods, +such as the finite element method and the finite difference method, which remain the cornerstone tools for PDE solution. + +.. image:: /_static/images/grids.jpg + :width: 800 + +Three examples of discretization: +The left one is a regular grid used in the finite difference method; +the middle one is a triangulated grid used in the finite element method; +the right one is a cylinder mesh for real-world airfoil problem. + + +Just like how we store images by pixels in *.PNG* and *.JPG* formats, +we need to discretize the domain of PDEs into some grid and solve the equation on the grid. +It really makes the thing easier. +These traditional numerical solvers are awesome, but they have some drawbacks: + + +- The error scales steeply with the resolution, so we often need a high resolution to get good approximations. +- The computation and storage steeply scale with the resolution (i.e. the size of the grid). +- When the equation is solved on one discretization, we cannot change the discretization anymore. + + +While formats like *.PNG* and *.JPG* are well-suited for storing images as grids of pixels, +sometimes it's advantageous to use vector formats such as *.EPS* or *.SVG*, which represent images +in a resolution-independent way and can be scaled or manipulated flexibly. +For certain types of images, vector formats can be both more convenient and more efficient. + +In the same spirit, when dealing with PDEs, we seek a representation that is not tied +to any particular discretization, in other words, a continuous formulation of the problem. +This means learning an operator that acts on functions directly and is invariant to the discretization, +much like how a vector image can be displayed on any device at any resolution. + +From a mathematical perspective, a continuous, discretization-invariant representation +aligns more closely with the true analytic solution of a problem. +This approach is not only conceptually elegant but also carries significant theoretical meaning. +Keeping this motivation in mind, let us now build a rigorous mathematical framework. + +.. raw:: html + +
+ +Problem Setting +=============== + +Consider the standard second order elliptic PDE + +.. math:: + - \nabla \cdot (a(x) \nabla u(x)) = f(x), \quad x \in D + +.. math:: + u(x) = 0, \quad x \in \partial D + +for some bounded, open domain :math:`D \subset \mathbb{R}^d` and a fixed source function +:math:`f`. This equation is prototypical of PDEs arising in +numerous applications including hydrology and elasticity. +For a given function :math:`a`, +the equation has a unique weak solution :math:`u` +and therefore we can define the solution operator :math:`\mathcal{F}_{true}` +as the map from function to function :math:`a \mapsto u`. + +Our goal is to learn a operator :math:`\mathcal{F}` approximating :math:`\mathcal{F}_{true}`, +by using a finite collection of observations of input-output pairs +:math:`\{a_j, u_j\}_{j=1}^N`, where each :math:`a_j` and :math:`u_j` are functions on :math:`D`. +In practice, the training data is solved numerically or observed in experiments. +In other words, functions :math:`a_j` and :math:`u_j` come with discretization. +Let :math:`P_K = \{x_1,\dots,x_K\} \subset D` be a :math:`K`-point discretization of the domain +:math:`D` and assume we have observations :math:`a_j|_{P_K}, u_j|_{P_K}`, for a finite +collection of input-output pairs indexed by :math:`j`. + + +We will show how to learn a discretization-invariant mapping based on discretized data. + +.. raw:: html + +
+ +Kernel Formulation +================== + +For a general PDE of the form: + +.. math:: + (\mathcal{L}_a u)(x)= f(x), \quad x \in D + +.. math:: + u(x) = 0, \quad x \in \partial D. + +Under fairly general conditions on :math:`\mathcal{L}_a`, +we may define the Green’s function :math:`G : D \times D \to \mathbb{R}` as the +unique solution to the problem + +.. math:: + \mathcal{L}_a G(x, \cdot) = \delta_x + +where :math:`\delta_x` is the delta measure on :math:`\mathbb{R}^d` centered at :math:`x`. +Note that :math:`G` will depend on the coefficient :math:`a` thus we will henceforth denote it as :math:`G_a`. +Then the true operator :math:`\mathcal{F}_{true}` can be written as an integral operator of Green’s function: + +.. math:: + u(x) = \int_D G_a(x,y)f(y) \: dy. + +Generally, the Green’s function is continuous at points :math:`x \neq y`, +for example, when :math:`\mathcal{L}_a` is uniformly elliptic. +Hence it is natural to model the kernel via a neural network :math:`\kappa`. +Just as the Green’s function, the kernel network :math:`\kappa` takes input :math:`(x,y)`. +Since the kernel depends on :math:`a`, we let :math:`\kappa` also take input :math:`(a(x),a(y))`, i.e. + +.. math:: + u(x) = \int_D \kappa(x,y,a(x),a(y))f(y) \: dy. + +.. raw:: html + +
+ +As an Iterative Solver +====================== + +In our setting, :math:`f` is an unknown but fixed function. +Instead of performing the kernel convolution with :math:`f`, +we will formulate it as an iterative solver +that approximates :math:`u` via :math:`u_t`, +where :math:`t = 0,\ldots,T` is the time step. + +The algorithm starts from an initialization :math:`u_0`, +for which we use :math:`u_0(x) = (x, a(x))`. +At each time step :math:`t`, it updates :math:`u_{t+1}` via a kernel convolution of :math:`u_{t}`, i.e. + +.. math:: + u_{t+1}(x) = \int_D \kappa(x,y,a(x),a(y))u_{t}(y) \: dy. + +It works like an implicit iteration, where at each iteration the algorithm solves an equation +for :math:`u_{t}(x)` and :math:`u_{t+1}(x)` using the kernel integral. +:math:`u_T` will be output as the final prediction. + +To further take the advantage of neural networks, we will lift :math:`u(x) \in \mathbb{R}^d` +to a high dimensional representation :math:`v(x) \in \mathbb{R}^n`, +with :math:`n` the dimension of the hidden representation. + +The overall algorithmic framework follow: + +.. math:: + v_0(x) = NN_1 (x, a(x)) + +.. math:: + v_{t+1}(x) = \sigma\Big( W v_t(x) + \int_{B(x,r)} \kappa_{\phi}\big(x,y,a(x),a(y)\big) v_t(y)\: \mathrm{d}y \Big) \quad \text{for } \ t=0,\ldots,T-1 + +.. math:: + u(x) = NN_2 (v_T (x)) + +where :math:`NN_1` and :math:`NN_2` are two feed-forward neural networks +that lifts the initialization to hidden representation :math:`v` +and projects the representation back to the solution :math:`u`, respectively. +:math:`\sigma` is an activation function such as ReLU. +The additional term :math:`W \in \mathbb{R}^{n \times n}` is a linear transformation +that acts on :math:`v`. + + +Notice that since the kernel integration happens in the high dimensional representation, +the output of :math:`\kappa_{\phi}` is not a scalar, +but a linear transformation :math:`\kappa_{\phi}\big(x,y,a(x),a(y)\big)\in \mathbb{R}^{n \times n}`. + +.. raw:: html + +
+ +Graph Neural Networks +===================== + +To perform the integration, we again need some discretization. +Assuming a uniform distribution of :math:`y`, +the integral :math:`\int_{B(x,r)} \kappa_{\phi}\big(x,y,a(x),a(y)\big) +v_t(y)\: \mathrm{d}y` can be approximated by a sum: + +.. math:: + \frac{1}{|N(x)|}\sum_{y \in N(x)} \kappa(x,y,a(x),a(y))v_t(y). + + +Observation: The kernel integral is equivalent to message passing on graphs. + + +If you are familiar with graph neural networks, +you may have already realized this formulation is the same as +the aggregation of messages in graph networks. +Message passing graph networks comprise a standard architecture employing edge features +(Gilmer et al, 2017). + +If we properly construct graphs on the spatial domain :math:`D` of the PDE, +the kernel integration can be viewed as an aggregation of messages. +Given node features :math:`v_t(x) \in \mathbb{R}^{n}`, +edge features :math:`e(x,y) \in \mathbb{R}^{n_e}`, +and a graph :math:`G`, the message passing neural network with averaging aggregation is + +.. math:: + v_{t+1}(x) = \sigma\Big(W v_t(x) + \frac{1}{|N(x)|} \sum_{y \in N(x)} \kappa_{\phi}\big(e(x,y)\big) v_t(y)\Big) + +where :math:`W \in \mathbb{R}^{n \times n}`, +:math:`N(x)` is the neighborhood of :math:`x` according to the graph, +:math:`\kappa_{\phi}\big(e(x,y)\big)` is a neural network +taking edge features as input and as output +a matrix in :math:`\mathbb{R}^{n \times n}`. +Relating to our kernel formulation, :math:`e(x,y) = (x,y,a(x),a(y))`. + +.. image:: /_static/images/graph.jpg + :width: 800 + +.. raw:: html + +
+ +Nystrom Approximation +===================== + +Ideally, to use all the information available, +we should construct :math:`K` nodes in the graph for all the points in the discretization +:math:`P_k = \{x_1,\ldots, x_K\}`, which will create :math:`O(K^2)` edges. +It is quite expensive. +Thankfully, we don’t need all the points to get an accurate approximation. +For each graph, the error of Monte Carlo approximation of the kernel integral + +.. math:: + \int_{B(x,r)} \kappa_{\phi}(x, y, a(x), a(y)) v_t(y)\: \mathrm{d}y + +scales with :math:`m^{-1/2}`, where :math:`m` is the number of nodes sampled. + +Since we will sample :math:`N` graphs in total for all :math:`N` training examples :math:`\{a_j, u_j\}^N`, +the overall error of the kernel is much smaller than :math:`m^{-1/2}`, where :math:`m` is the number of nodes sampled. +In practice, sampling :math:`m \sim 200` nodes is sufficient for :math:`K \sim 100,\!000` points. + +The approximation can be further improved by employing advanced Nystrom methods. +For instance, by estimating the significance or influence of each point, +we can strategically allocate more nodes to regions with high complexity or singularities in the PDEs, +leading to greater accuracy where it matters most. + +.. raw:: html + +
+ +Experiments: Poisson Equations +============================== + +Let's first consider a simple Poisson equation: + +.. math:: + -\Delta u = f. + +We set :math:`v_0 = f` and :math:`T=1`, and use one iteration of the graph kernel network +to learn the operator :math:`\mathcal{F}: f \mapsto u`. + +.. raw:: html + +
+ +Poisson equation +---------------- + +.. image:: /_static/images/nik_kernel.jpg + :width: 800 + +As shown in the figure above, we compare the true analytic Green's function :math:`G(x,y)` (left) +with the learned kernel :math:`\kappa_{\phi}(x,y)` (right). +The learned kernel is almost the same as the true kernel, +which means our neural network formulation matches the Green's function expression. + +.. raw:: html + +
+ +2D Poisson equation +------------------- + +.. image:: /_static/images/GKN_compare.jpg + :width: 800 + +By assuming the kernel structure, +graph kernel networks need only a few training examples to learn the shape of the solution :math:`u`. +As shown in the figure above, the graph kernel network can roughly learn :math:`u` with :math:`5` training pairs, +while a feedforward neural network needs at least :math:`100` training examples. + +.. raw:: html + +
+ +Experiments: generalization of resolution +========================================= + + +For the large scale experiments, we use the Darcy equation of the form + +.. math:: + - \nabla \cdot (a(x) \nabla u(x)) = f(x), \quad x \in D + +.. math:: + u(x) = 0, \quad x \in \partial D + +and learn the operator :math:`\mathcal{F}: a \mapsto u`. + +To demonstrate the generalization property, we train the graph kernel network +with nodes sampled from the resolution :math:`s \times s` +and test on a different resolution :math:`s' \times s'` . + + +As shown in the table above for each row, +the test errors on different resolutions are about the same, +which means the graph kernel network can also +generalize in the semi-supervised setting. +A figure for :math:`s=16, s'=241` is shown below (where the error is the absolute squared error): + +.. image:: /_static/images/uai_16to241.jpg + :width: 800 + +.. raw:: html + +
+ +Conclusion +========== + +We proposed using graph networks for operator learning in PDE problems. +By varying the underlying graph and discretization, +the learned kernel is invariant to the discretization. +Experiments confirm that the graph kernel networks are able to generalize among different discretizations. +And in the fixed discretization setting, the graph kernel networks +also have good performance compared to several benchmarks. + +.. raw:: html + +
+ +References +========== + +.. [1] Fourier Neural Operators Explained: A Practical Perspective + Valentin Duruisseaux, Jean Kossaifi, Anima Anandkumar, 2025. + https://arxiv.org/abs/2512.01421. + +.. raw:: html + +
+ +.. [2] Neural operator: Graph kernel network for partial differential equations, + Zongyi Li, Nikola Kovachki, Kamyar Azizzadenesheli, Burigede Liu, Kaushik Bhattacharya, Andrew Stuart, Anima Anandkumar, 2020. + https://arxiv.org/abs/2003.03485 + +.. raw:: html + +
+ +.. [3] Principled Approaches for Extending Neural Architectures to Function Spaces for Operator Learning, + Julius Berner, Miguel Liu-Schiaffini, Jean Kossaifi, Valentin Duruisseaux, Boris Bonev, Kamyar Azizzadenesheli, Anima Anandkumar, 2025. + https://arxiv.org/abs/2506.10973 + +.. raw:: html + +
+ +.. [4] Neural operator: Learning maps between function spaces, + Nikola Kovachki, Zongyi Li, Kamyar Azizzadenesheli, Burigede Liu, Kaushik Bhattacharya, Andrew Stuart, Anima Anandkumar, 2023. + https://arxiv.org/abs/2108.08481. + + + + + diff --git a/sources/neuraloperator/doc/source/user_guide/index.rst b/sources/neuraloperator/doc/source/user_guide/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..c7f08978982e5aa70063cf8b6c91d60b6132b669 --- /dev/null +++ b/sources/neuraloperator/doc/source/user_guide/index.rst @@ -0,0 +1,391 @@ +.. _user_guide: + +User Guide +========== + +NeuralOperator provides all the tools you need +to easily use, build and train neural operators for your own applications +and learn mapping between function spaces, in PyTorch. + + +NeuralOperator library structure +-------------------------------- + +Here are the main components of the library: + +================================= ================================ +Module Description +================================= ================================ +:mod:`neuralop` Main library with core imports +:mod:`neuralop.models` Full ready-to-use neural operators (FNO, SFNO, UNO, UQNO, FNOGNO, GINO, etc.) +:mod:`neuralop.layers` Individual layers to build neural operators +:mod:`neuralop.data` Convenience PyTorch data loaders for PDE datasets and transforms +:mod:`neuralop.training` Utilities to train neural operators end-to-end (Trainer, AdamW, etc.) +:mod:`neuralop.losses` Loss functions for neural operator training (LpLoss, H1Loss, etc.) +:mod:`neuralop.mpu` Multi-processing utilities for distributed training +================================= ================================ + +The main :mod:`neuralop` module provides convenient imports for the most commonly used components: + +- **Models**: FNO, SFNO, UNO, UQNO, FNOGNO, GINO, LocalNO, CODANO, get_model, etc... +- **Training**: Trainer +- **Losses**: LpLoss, H1Loss, WeightedSumLoss, Relobralo, SoftAdapt, FourierDiff, non_uniform_fd, FiniteDiff +- **Data**: datasets, transforms +- **Utilities**: mpu + + + +.. raw:: html + +
+ +Available Neural Operator Models +-------------------------------- + +The :mod:`neuralop.models` module includes several state-of-the-art neural operator architectures: + +- **FNO (Fourier Neural Operator)**: The original Fourier-based neural operator (1D, 2D, 3D variants) +- **TFNO (Tensorized FNO)**: Tensorized version with Tucker factorization (1D, 2D, 3D variants) +- **SFNO (Spherical FNO)**: Spherical harmonics-based FNO for spherical domains (requires torch_harmonics) +- **UNO (U-shaped Neural Operator)**: U-Net inspired architecture for neural operators +- **UQNO (Uncertainty Quantification NO)**: Neural operator with uncertainty quantification +- **FNOGNO (FNO + Graph Neural Operator)**: Hybrid FNO-GNO architecture +- **GINO (Graph Neural Operator)**: Graph-based neural operator for irregular domains +- **LocalNO**: Local neural operator for efficient computation (requires torch_harmonics) +- **CODANO**: Continuous-discrete neural operator + + +.. raw:: html + +
+ +Data Loading and Preprocessing +------------------------------ + +The :mod:`neuralop.data` module provides comprehensive data handling capabilities: + +**Datasets** (:mod:`neuralop.data.datasets`): + +- **Darcy Flow**: Standard benchmark for elliptic PDEs (load_darcy_flow_small, load_darcy_pt) +- **Burgers Equation**: Nonlinear PDE benchmark (load_mini_burgers_1dtime) +- **Navier-Stokes**: Fluid dynamics equations (load_navier_stokes_pt) +- **Spherical SWE**: Shallow water equations on spherical domains (load_spherical_swe, requires torch_harmonics) +- **Car CFD**: Computational fluid dynamics data (load_mini_car) +- **Nonlinear Poisson**: Poisson equation with nonlinear terms (load_nonlinear_poisson_pt) +- **The Well**: Active matter and MHD datasets (requires the_well package) + +**Transforms** (:mod:`neuralop.data.transforms`): + +- **Normalizers**: UnitGaussianNormalizer, DictUnitGaussianNormalizer +- **Data Processors**: DefaultDataProcessor, IncrementalDataProcessor, MGPatchingDataProcessor +- **Patching Transforms**: For handling large-scale problems +- **Base Transforms**: Extensible Transform and DictTransform framework + +.. raw:: html + +
+ +Training Neural Operator Models +------------------------------- + +Our library makes it easy for anyone with data drawn from a system governed by a +PDE to train and test Neural Operator models. +The library provides comprehensive training utilities and loss functions to +get you started quickly. + +.. raw:: html + +
+ +The Trainer Class +~~~~~~~~~~~~~~~~~ + +Most users will train neural operator models on their own data in very similar +ways, using a very standard machine learning training loop. +To speed up this process, we provide a :code:`Trainer` class that automates +much of this boilerplate logic. +Things like loading a model to device, zeroing gradients and computing most +loss functions are taken care of. + +The :code:`Trainer` implements training in a modular fashion, meaning that +more domain-specific logic can easily be implemented. For more specific +documentation, check the :ref:`api_ref`. + +.. raw:: html + +
+ +Available Training Components +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The :mod:`neuralop.training` module provides several key components: + +- **Trainer**: Main training class for neural operator models +- **AdamW**: Optimized Adam optimizer with weight decay +- **IncrementalFNOTrainer**: Specialized trainer for incremental FNO training +- **setup**: PyTorch setup utilities for distributed training +- **load_training_state/save_training_state**: Utilities for checkpointing + +Note: The main :mod:`neuralop` module directly imports `Trainer` for convenience. + +.. raw:: html + +
+ +Loss Functions +~~~~~~~~~~~~~~ + +The :mod:`neuralop.losses` module provides various loss functions: + +- **Data Losses**: LpLoss, H1Loss for standard regression tasks +- **Equation Losses**: Various equation-specific loss functions for physics-informed training +- **Meta Losses**: WeightedSumLoss, Aggregator, Relobralo, SoftAdapt for advanced training strategies +- **Differentiation**: FourierDiff, non_uniform_fd, FiniteDiff for computing derivatives + +.. raw:: html + +
+ +Distributed Training +~~~~~~~~~~~~~~~~~~~~ + +We also provide a simple way to use PyTorch's :code:`DistributedDataParallel` functionality +to hold data across multiple GPUs. +We use PyTorch's :code:`torchrun` elastic launcher, so all you need to do on a +multi-GPU system is the following: + +:: + + torchrun --standalone --nproc_per_node script.py + +You may need to adjust the batch size, model parallel size and world size +in accordance with your specific use case. +See the `torchrun documentation `_ +for more details. + +.. raw:: html + +
+ +CPU Offloading +-------------- + +For training with high-resolution inputs that exceed GPU memory limits, +NeuralOperator supports CPU offloading of activations. +This technique allows training larger models or higher-resolution problems +by temporarily storing intermediate computations on CPU memory. + +.. raw:: html + +
+ +Overview +~~~~~~~~ + +When training neural operators with high-resolution inputs, GPU memory +usage can become a bottleneck. +The peak memory consumption often exceeds CUDA limits because all +intermediate activations in the computation graph are stored on the GPU by default. + +Each activation tensor typically has a shape of: + +.. math:: + + \text{batch_size} \times \text{hidden_dim} \times N_x \times N_y \times \dots + +where :math:`N_x, N_y, \dots` are the spatial or temporal resolutions of the input. +As the computation graph grows deeper during forward and backward passes, +a large number of such intermediate tensors accumulate, leading +to high GPU memory consumption. + +**CPU offloading** addresses this by moving activations to CPU memory +during training, allowing: + +- Training with higher-resolution inputs under limited GPU memory +- Training larger models without reducing batch size +- Better memory utilization across CPU and GPU + +.. note:: + CPU offloading trades memory for compute time, as data transfer between + CPU and GPU adds overhead. + +.. raw:: html + +
+ +Example Usage +~~~~~~~~~~~~~ + +Below is a complete example demonstrating CPU offloading integration +with NeuralOperator training: + +1. Setup and Data Loading +^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. code-block:: python + + import torch + import matplotlib.pyplot as plt + import sys + from functools import wraps + + from neuralop.models import FNO + from neuralop import Trainer, LpLoss, H1Loss + from neuralop.training import AdamW + from neuralop.data.datasets import load_darcy_flow_small + from neuralop.utils import count_model_params + + device = 'cuda' + +Load the dataset: + +.. code-block:: python + + # Load Darcy flow dataset with specified resolutions + train_loader, test_loaders, data_processor = load_darcy_flow_small( + n_train=1000, + batch_size=32, + test_resolutions=[16, 32], + n_tests=[100, 50], + test_batch_sizes=[32, 32], + ) + data_processor = data_processor.to(device) + +2. Model Creation +^^^^^^^^^^^^^^^^^ + +.. code-block:: python + + # Create FNO model with specified parameters + model = FNO( + n_modes=(16, 16), # Fourier modes for each dimension + in_channels=1, # Input channels + out_channels=1, # Output channels + hidden_channels=32, # Hidden layer width + projection_channel_ratio=2 # Channel expansion ratio + ) + model = model.to(device) + + print(f"Model parameters: {count_model_params(model)}") + +3. Enable CPU Offloading +^^^^^^^^^^^^^^^^^^^^^^^^ + +Wrap the model's forward function to enable automatic CPU offloading: + +.. code-block:: python + + def wrap_forward_with_offload(forward_fn): + """ + Wrap a forward function to enable CPU offloading of activations. + + Parameters + ---------- + forward_fn : callable + The original forward function to wrap + + Returns + ------- + callable + Wrapped forward function with CPU offloading enabled + """ + @wraps(forward_fn) + def wrapped_forward(*args, **kwargs): + # Enable CPU offloading context for this forward pass + with torch.autograd.graph.save_on_cpu(pin_memory=True): + return forward_fn(*args, **kwargs) + return wrapped_forward + + # Apply CPU offloading to the model + model.forward = wrap_forward_with_offload(model.forward) + +4. Training Loop +^^^^^^^^^^^^^^^^ + +No changes are needed in your existing training code: + +.. code-block:: python + + # Setup optimizer and loss function + optimizer = AdamW(model.parameters(), lr=8e-3, weight_decay=1e-4) + l2loss = LpLoss(d=2, p=2) + h1loss = H1Loss(d=2) + + # Training step - works exactly as before + for batch_idx, (input_data, target_data) in enumerate(train_loader): + # Move data to device + input_data = input_data.to(device) # Shape: (batch, channels, height, width) + target_data = target_data.to(device) # Shape: (batch, channels, height, width) + + # Forward pass - activations automatically offloaded to CPU + output = model(input_data) + + # Compute loss + loss = l2loss(output, target_data) + + # Backward pass - gradients computed with CPU-stored activations + optimizer.zero_grad() + loss.backward() + optimizer.step() + +.. raw:: html + +
+ +Performance Considerations +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +**Memory vs Speed Trade-off** + CPU offloading reduces GPU memory usage at the cost of increased + training time due to data transfer overhead between CPU and GPU memory. + +.. raw:: html + +
+ +**When to Use** + - Training fails with CUDA out-of-memory errors + - You want to increase batch size or model resolution + - GPU memory is the primary bottleneck + +.. raw:: html + +
+ +**When Not to Use** + - GPU memory is sufficient for your current setup + - Training speed is more critical than memory usage + - CPU memory is also limited + +.. raw:: html + +
+ +**Optimization Tips** + - Use ``pin_memory=True`` for faster CPU-GPU transfers + - Consider gradient checkpointing as an alternative memory-saving technique + - Monitor both GPU and CPU memory usage during training + +.. raw:: html + +
+ +.. warning:: + CPU offloading requires PyTorch version 1.12.0 or higher. Ensure your environment meets this requirement before using this feature. + + + +.. raw:: html + +
+ +Interactive examples with code +------------------------------ +We also provide interactive examples that show our library and neural operator +models in action. +To get up to speed on the code, and look through some interactive examples +to help you hit the ground running, check out our :ref:`gallery_examples`. + +We also provide training recipe scripts for our models on sample problems +in the `scripts` directory. + diff --git a/sources/neuraloperator/examples/GALLERY_HEADER.rst b/sources/neuraloperator/examples/GALLERY_HEADER.rst new file mode 100644 index 0000000000000000000000000000000000000000..d851f700e527f2e3038e85c46bedab5f96a883ec --- /dev/null +++ b/sources/neuraloperator/examples/GALLERY_HEADER.rst @@ -0,0 +1,7 @@ +.. _gallery_examples: + +Examples +======== + +A gallery of interactive examples that showcase how the tools we provide in ``neuraloperator`` can be applied to a variety of problems. +Check out the :ref:`user_guide` for more detailed information on the theory behind neural operators. diff --git a/sources/neuraloperator/examples/data/README.rst b/sources/neuraloperator/examples/data/README.rst new file mode 100644 index 0000000000000000000000000000000000000000..ccbe7b05f1e5116c86220a723955010ded9b818b --- /dev/null +++ b/sources/neuraloperator/examples/data/README.rst @@ -0,0 +1,11 @@ +.. _data_examples : + +Data +---- + +Examples of NO layers in action. + +.. contents:: **Contents** + :local: + :depth: 1 + diff --git a/sources/neuraloperator/examples/data/plot_darcy_flow.py b/sources/neuraloperator/examples/data/plot_darcy_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..b70e6554fdab5a089928d983dc5df899d74672a6 --- /dev/null +++ b/sources/neuraloperator/examples/data/plot_darcy_flow.py @@ -0,0 +1,112 @@ +""" +.. _small_darcy_vis : + +A simple Darcy-Flow dataset +=========================== +An introduction to the small Darcy-Flow example dataset we ship with the package. + +The Darcy-Flow problem is a fundamental partial differential equation (PDE) in fluid mechanics +that describes the flow of a fluid through a porous medium. In this tutorial, we explore the +dataset structure and visualize how the data is processed for neural operator training. + +""" + +# %% +# .. raw:: html +# +#
+# +# Import the library +# ------------------ +# We first import our `neuralop` library and required dependencies. + +import matplotlib.pyplot as plt +from neuralop.data.datasets import load_darcy_flow_small +from neuralop.layers.embeddings import GridEmbedding2D + +# %% +# .. raw:: html +# +#
+# +# Load the dataset +# ---------------- +# Training samples are 16x16 and we load testing samples at both +# 16x16 and 32x32 (to test resolution invariance). + +train_loader, test_loaders, data_processor = load_darcy_flow_small( + n_train=20, + batch_size=4, + test_resolutions=[16, 32], + n_tests=[10, 10], + test_batch_sizes=[4, 2], +) + +train_dataset = train_loader.dataset + +# %% +# .. raw:: html +# +#
+# +# Visualizing the data +# -------------------- +# Let's examine the shape and structure of our dataset at different resolutions. + +for res, test_loader in test_loaders.items(): + print(f"Resolution: {res}") + # Get first batch + batch = next(iter(test_loader)) + x = batch["x"] # Input + y = batch["y"] # Output + + print(f"Testing samples for resolution {res} have shape {x.shape[1:]}") + + +data = train_dataset[0] +x = data["x"] +y = data["y"] + +print(f"Training samples have shape {x.shape[1:]}") + +# Which sample to view +index = 0 + +data = train_dataset[index] +data = data_processor.preprocess(data, batched=False) + +# The first step of the default FNO model is a grid-based +# positional embedding. We will add it manually here to +# visualize the channels appended by this embedding. +positional_embedding = GridEmbedding2D(in_channels=1) +# At train time, data will be collated with a batch dimension. +# We create a batch dimension to pass into the embedding, then re-squeeze +x = positional_embedding(data["x"].unsqueeze(0)).squeeze(0) +y = data["y"] + +# %% +# .. raw:: html +# +#
+# +# Visualizing the processed data +# ------------------------------ +# We can see how the positional embedding adds coordinate information to our input data. +# This helps the neural operator understand spatial relationships in the data. + +fig = plt.figure(figsize=(7, 7)) +ax = fig.add_subplot(2, 2, 1) +ax.imshow(x[0], cmap="gray") +ax.set_title("Input x") +ax = fig.add_subplot(2, 2, 2) +ax.imshow(y.squeeze()) +ax.set_title("Output y") +ax = fig.add_subplot(2, 2, 3) +ax.imshow(x[1]) +ax.set_title("Positional embedding: x-coordinates") +ax = fig.add_subplot(2, 2, 4) +ax.imshow(x[2]) +ax.set_title("Positional embedding: y-coordinates") +fig.suptitle("Visualizing one input sample with positional embeddings", y=0.98) +plt.tight_layout() +fig.show() diff --git a/sources/neuraloperator/examples/data/plot_darcy_flow_spectrum.py b/sources/neuraloperator/examples/data/plot_darcy_flow_spectrum.py new file mode 100644 index 0000000000000000000000000000000000000000..187388c4a0f1d90da9b14095d39135635db398f7 --- /dev/null +++ b/sources/neuraloperator/examples/data/plot_darcy_flow_spectrum.py @@ -0,0 +1,165 @@ +""" +A simple Darcy-Flow spectrum analysis +===================================== +Using ``neuralop.utils.spectrum_2d`` to perform spectrum analysis on our small Darcy-Flow example. + +This tutorial demonstrates how to analyze the spectral characteristics of the Darcy-Flow dataset, +which provides insights into the frequency content and energy distribution of the vector fields. + +For more details on spectrum analysis, users can take a look at this reference: +https://www.astronomy.ohio-state.edu/ryden.1/ast825/ch7.pdf + +Short summary +-------------- +Spectral analysis is useful because it allows researchers to study the distribution of energy +across different scales in a fluid flow. The energy spectrum is analyzed through the Fourier +transform, a mathematical tool that decomposes a function or signal into its constituent frequencies. +In a fluid flow, it is used to analyze the distribution of energy across different scales in a flow. + +Specifically, the Fourier transform is applied to the velocity field of the flow, converting it +into a frequency domain representation. Higher wavenumbers correspond to higher frequencies and +higher energy, and are much harder to solve as we need higher modes to capture the high-frequency +behavior of the flow. Overall, this allows researchers to study the energy spectrum, which +provides insights into the behavior of turbulence and the underlying physical processes. + +""" + +# %% +# .. raw:: html +# +#
+# +# Import dependencies +# -------------------- +# We first import our `neuralop` library and required dependencies. +import numpy as np +import torch +import matplotlib +import matplotlib.pyplot as plt +from neuralop.utils import spectrum_2d +from neuralop.data.datasets import load_darcy_flow_small + +font = {"size": 28} +matplotlib.rc("font", **font) + +torch.manual_seed(0) +np.random.seed(0) + +# %% +# .. raw:: html +# +#
+# +# Define analysis parameters +# -------------------------- +# These parameters control the spectral analysis of our Darcy-Flow dataset +samples = 50 # Number of samples to analyze +s = 16 # Resolution of the dataset (16x16 grid) +dataset_name = "Darcy Flow" + +# %% +# .. raw:: html +# +#
+# +# Loading the Darcy-Flow dataset +# -------------------------------- +# We load the Darcy-Flow dataset with multiple resolutions for spectral analysis +train_loader, test_loaders, data_processor = load_darcy_flow_small( + n_train=50, + batch_size=50, + test_resolutions=[16, 32], + n_tests=[50, 50], + test_batch_sizes=[32], + encode_output=False, +) + +# %% +# .. raw:: html +# +#
+# +# Preparing data for spectral analysis +# ------------------------------------ +# The dataset structure is ['x', 'y'] where 'x' is the permeability field and 'y' is the pressure field +# We'll analyze the pressure fields ('y') for their spectral characteristics +print("Original dataset shape:", train_loader.dataset[:samples]["x"].shape) + +# Extract the pressure fields (output) for spectral analysis +# We want the last two dimensions to represent the spatial dimensions +dataset_pred = train_loader.dataset[:samples][ + "y" +].squeeze() # Remove empty channel dimension + +# Shape of the dataset +shape = dataset_pred.shape +print(f"Pressure field shape: {shape}") + +# %% +# .. raw:: html +# +#
+# +# Creating coordinate grids for spectral analysis +# ------------------------------------------------ +# We need to define the spatial grid for proper spectral analysis +# For 2D grids, we create x and y coordinate arrays +batchsize, size_x, size_y = 1, shape[1], shape[2] + +# Create coordinate grids normalized to [-1, 1] +gridx = torch.tensor(np.linspace(-1, 1, size_x), dtype=torch.float) +gridx = gridx.reshape(1, size_x, 1).repeat([batchsize, 1, size_y]) +gridy = torch.tensor(np.linspace(-1, 1, size_y), dtype=torch.float) +gridy = gridy.reshape(1, 1, size_y).repeat([batchsize, size_x, 1]) +grid = torch.cat((gridx, gridy), dim=-1) + +# %% +# .. raw:: html +# +#
+# +# Computing the energy spectrum +# ----------------------------- +# We compute the 2D energy spectrum of the pressure fields using the spectrum_2d utility +# This gives us insight into how energy is distributed across different spatial frequencies + +# Generate the spectrum of the dataset +# We reshape our samples into the form expected by ``spectrum_2d``: ``(n_samples, h, w)`` +truth_sp = spectrum_2d(dataset_pred.reshape(samples * batchsize, s, s), s) + +# %% +# .. raw:: html +# +#
+# +# Visualizing the energy spectrum +# -------------------------------- +# The energy spectrum shows how much energy is contained in each wavenumber (spatial frequency) +# Higher wavenumbers correspond to smaller spatial scales and higher frequencies + +# Configure pyplot and generate the plot +plt.style.use("classic") +fig, ax = plt.subplots(figsize=(10, 10), dpi=150) +ax.set_facecolor("white") +ax.set_yscale("log") # Log scale for better visualization of energy decay +length = dataset_pred.shape[-1] # The resolution length of the dataset +buffer = 4 # Add a buffer to the plot for better visualization +k = np.arange(length + buffer) * 1.0 + +# Plot the spectrum +ax.plot(truth_sp, color="navy", linestyle="--", linewidth=2.5, label="Energy Spectrum") + +# Customizing the plot +ax.set_xlim(1, 16) +ax.set_ylim(0.01, 20) +ax.set_xlabel("Wavenumber", fontsize=16, fontweight="bold") +ax.set_ylabel("Energy", fontsize=16, fontweight="bold") +ax.set_title( + f"Energy Spectrum of {dataset_name} Dataset", fontsize=18, fontweight="bold", pad=20 +) +ax.tick_params(axis="both", which="major", labelsize=15) + +plt.tight_layout() +plt.show() + +# %% diff --git a/sources/neuraloperator/examples/data/plot_mini_car_cfd.py b/sources/neuraloperator/examples/data/plot_mini_car_cfd.py new file mode 100644 index 0000000000000000000000000000000000000000..7339ddb285bac198fd05079410e86a307e6506ec --- /dev/null +++ b/sources/neuraloperator/examples/data/plot_mini_car_cfd.py @@ -0,0 +1,233 @@ +""" +Visualizing computational fluid dynamics on a car +=================================================== +In this example we visualize a mesh drawn from the :class:`~neuralop.data.datasets.car_cfd_dataset.CarCFDDataset`. + +This tutorial demonstrates how to work with unstructured mesh data from computational fluid dynamics (CFD) +simulations. We will explore the 3D geometry of a car and understand how pressure fields are distributed +over the surface, which is crucial for aerodynamic analysis and neural operator applications. + +The CarCFD dataset contains: +- 3D triangular mesh data representing the car surface +- Pressure fields computed from CFD simulations +- Query points for neural operator training +""" + +# %% +# .. raw:: html +# +#
+# +# Import dependencies +# -------------------- +# We first import our `neuralop` library and required dependencies. +import numpy as np +import torch +import matplotlib +import matplotlib.pyplot as plt +from neuralop.data.datasets import load_mini_car + +font = {"size": 12} +matplotlib.rc("font", **font) + +torch.manual_seed(0) +np.random.seed(0) + +# %% +# .. raw:: html +# +#
+# +# Understanding the data structure +# --------------------------------- +# The data in a ``MeshDataModule`` is structured as a dictionary of tensors and important scalar values encoding +# a 3D triangle mesh over the surface of a car. +# Each sample includes the coordinates of all triangle vertices and the centroids of each triangle face. +# +# In this case, the creators used OpenFOAM to simulate the surface air pressure on car geometries in a wind tunnel. +# The 3D Navier-Stokes equations were simulated for a variety of inlet velocities over each surface using the +# **OpenFOAM** computational solver to predict pressure at every vertex on the mesh. +# Each sample here also has an inlet velocity scalar and a pressure field that maps 1-to-1 with the vertices on the mesh. +# The :class:`CarCFDDataset ` (full dataset) is stored in triangle mesh files for downstream processing. +# For the sake of simplicity, we've packaged a few examples of the data after processing in tensor form to visualize here: + +data_list = load_mini_car() +sample = data_list[0] +print(f"Available data keys: {sample.keys()}") + +# %% +# .. raw:: html +# +#
+# +# Visualizing the car surface with pressure distribution +# ------------------------------------------------------ +# Let's take a look at the vertices and pressure values to understand the 3D structure +# and how pressure varies across the car surface. + +fig = plt.figure(figsize=(10, 8)) +ax = fig.add_subplot(projection="3d") + +# By default the data is normalized into the unit cube. To get a +# better look at it, we scale the z-direction up. +scatter = ax.scatter(sample["vertices"][:, 0], sample["vertices"][:, 1], + sample["vertices"][:, 2] * 2, s=2, c=sample["press"].numpy(), cmap="viridis") +ax.set_xlim(0,2) +ax.set_ylim(0,2) +ax.set_xlabel("x") +ax.set_ylabel("y") +ax.set_zlabel("z") +ax.view_init(elev=20, azim=150, roll=0, vertical_axis="y") +ax.set_title("Pressure distribution over car mesh vertices") +fig.colorbar(scatter, pad=0.2, label="normalized pressure", ax=ax) +plt.draw() +# %% +# .. raw:: html +# +#
+# +# Understanding query points for neural operator training +# -------------------------------------------------------- +# Each sample in the ``CarCFDDataset`` also includes a set of latent query points on which we learn a function +# to enable learning with an FNO in the middle of our geometry-informed models. Let's visualize the queries +# on top of the car from before: +fig = plt.figure(figsize=(8,10)) +ax = fig.add_subplot(projection="3d") +scatter = ax.scatter(sample["vertices"][:, 0], sample["vertices"][:, 1], sample["vertices"][:, 2] * 2, s=4, label="Car surface") +queries = sample["query_points"].view(-1, 3) # unroll our cube tensor into a point cloud +ax.scatter(queries[:, 0], queries[:, 1], queries[:, 2] * 2, s=1, alpha=0.5, label="Latent queries") + +ax.set_xlim(0, 2) +ax.set_ylim(0, 2) +ax.set_xlabel("x") +ax.set_ylabel("y") +ax.set_zlabel("z") +ax.legend() +ax.view_init(elev=20, azim=150, roll=0, vertical_axis="y") +ax.set_title("Query points and car surface vertices") +# %% +# .. raw:: html +# +#
+# +# Neighbor search between 3D point clouds +# ---------------------------------------- +# In :doc:`../layers/plot_neighbor_search` we demonstrate our neighbor search +# on a simple 2D point cloud. Let's try that again with our 3D car surface points here. + +from neuralop.layers.neighbor_search import native_neighbor_search + +verts = sample["vertices"] +query_point = queries[3300] +nbr_data = native_neighbor_search(data=verts, queries=query_point.unsqueeze(0), radius=0.5) + +# %% Visualizing neighborhoods +# Let's plot the new neighbors we just found on top of the car surface point cloud. +fig = plt.figure(figsize=(8, 10)) +ax1 = fig.add_subplot(2, 1, 1, projection="3d") +ax2 = fig.add_subplot(2, 1, 2, projection="3d") +neighbors = verts[nbr_data["neighbors_index"]] + +# Plotting just one query point vs. the car +ax1.scatter(verts[:, 0], verts[:, 1], verts[:, 2]*2, s=1, alpha=0.1) +ax1.scatter(query_point[0], query_point[1], query_point[2]*2, s=10, c="red", label="Single query") +ax1.view_init(elev=20, azim=-20, roll=0, vertical_axis="y") +ax1.legend() +ax1.set_xlim(0, 2) +ax1.set_ylim(0, 2) +ax1.set_xlabel("x") +ax1.set_ylabel("y") +ax1.set_zlabel("z") +ax1.view_init(elev=20, azim=-20, roll=0, vertical_axis="y") +ax1.grid(False) +ax1.set_title("One query point") + +# Plotting all query points and neighbors +ax2.scatter(verts[:, 0], verts[:, 1], verts[:, 2]*2, s=0.5, alpha=0.4, label="Car surface") +ax2.scatter(queries[:, 0], queries[:, 1], queries[:, 2]*2, s=0.5, alpha=0.2, label="Latent queries") +ax2.scatter(neighbors[:, 0], neighbors[:, 1], neighbors[:, 2]*2, s=10, label="Neighbors on\ncar surface",) +ax2.legend() +ax2.set_xlim(0, 2) +ax2.set_ylim(0, 2) +ax2.set_xlabel("x") +ax2.set_ylabel("y") +ax2.set_zlabel("z") +ax2.view_init(elev=20, azim=-20, roll=0, vertical_axis="y") +ax2.set_title("Neighbor points from car for one query point") +ax2.grid(False) + +for ax in ax1, ax2: + ax.set_xticks([]) + ax.set_yticks([]) + ax.set_zticks([]) +plt.draw() + + +# %% +# .. raw:: html +# +#
+# +# Connecting neighbors to query +# ------------------------------ +# First, let's make a simple utiltiy to add arrows to our 3D plot: + +import numpy as np +from matplotlib import pyplot as plt +from matplotlib.patches import FancyArrowPatch +from mpl_toolkits.mplot3d import proj3d + + +class Arrow3D(FancyArrowPatch): + def __init__(self, xs, ys, zs, *args, **kwargs): + super().__init__((0, 0), (0, 0), *args, **kwargs) + self._verts3d = xs, ys, zs + + def do_3d_projection(self, renderer=None): + xs3d, ys3d, zs3d = self._verts3d + xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, self.axes.M) + self.set_positions((xs[0], ys[0]), (xs[1], ys[1])) + + return np.min(zs) + + +# Creating plots +fig = plt.figure(figsize=(8, 10)) +ax1 = fig.add_subplot(projection="3d") +neighbors = verts[nbr_data["neighbors_index"]] + +# Plotting just one query point vs. the car +ax1.scatter(verts[:, 0], verts[:, 1], verts[:, 2]*2, s=1, alpha=0.1) +ax1.scatter(query_point[0], query_point[1], query_point[2]*2, s=10, c="red", label="Single query") +ax1.scatter(neighbors[:, 0], neighbors[:, 1], neighbors[:, 2]*2, s=10, label="Neighbors on\ncar surface",) + +ax1.view_init(elev=20, azim=-20, roll=0, vertical_axis="y") +ax1.legend() +ax1.set_xlim(0, 2) +ax1.set_ylim(0, 2) +ax1.set_xlabel("x") +ax1.set_ylabel("y") +ax1.set_zlabel("z") +ax1.view_init(elev=20, azim=-20, roll=0, vertical_axis="y") +ax1.grid(False) +ax1.set_title("One query point") + + +for ax in [ax1]: + ax.set_xticks([]) + ax.set_yticks([]) + ax.set_zticks([]) + +# Add arrows between neighbors and query +arrow_prop_dict = dict(mutation_scale=1, arrowstyle="-|>", color="red", shrinkA=1, shrinkB=1, alpha=0.1) +for nbr in neighbors: + a = Arrow3D( + [query_point[0], nbr[0]], + [query_point[1], nbr[1]], + [query_point[2] * 2, nbr[2] * 2], + **arrow_prop_dict, + ) + ax1.add_artist(a) + +fig.tight_layout() +plt.draw() diff --git a/sources/neuraloperator/examples/data_gen/GALLERY_HEADER.rst b/sources/neuraloperator/examples/data_gen/GALLERY_HEADER.rst new file mode 100644 index 0000000000000000000000000000000000000000..73e5d9dc219390db721755bd516458ce9f13afa1 --- /dev/null +++ b/sources/neuraloperator/examples/data_gen/GALLERY_HEADER.rst @@ -0,0 +1,7 @@ +.. _data_gen_examples : + +Data Generation +--------------- + +Examples demonstrating the use of our built-in finite difference solver +to generate PDE data. \ No newline at end of file diff --git a/sources/neuraloperator/examples/data_gen/burgers2d.gif b/sources/neuraloperator/examples/data_gen/burgers2d.gif new file mode 100644 index 0000000000000000000000000000000000000000..cc136625320137bbed23011aacddc7b1c1a84c2b --- /dev/null +++ b/sources/neuraloperator/examples/data_gen/burgers2d.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f463572239770bc515379013aa6ebb147f6b2b5fc56928e5d77c08360f9be91f +size 6056709 diff --git a/sources/neuraloperator/examples/data_gen/plot_burgers_2d_solver.py b/sources/neuraloperator/examples/data_gen/plot_burgers_2d_solver.py new file mode 100644 index 0000000000000000000000000000000000000000..c0fe820db62540cfdcf25d0220f0f27fe6dcdb39 --- /dev/null +++ b/sources/neuraloperator/examples/data_gen/plot_burgers_2d_solver.py @@ -0,0 +1,133 @@ +""" +.. _burgers_2d_fd_vis : + +A finite difference solver for Burgers' equation in 2 dimensions +=============================================================== +An intro to our loss module's finite difference utility demonstrating +its use to create a simple numerical solver for Burgers' equation in 2d. +""" + +# %% +# .. raw:: html +# +#
+# +# Import the library +# ------------------ +# We first import our `neuralop` library and required dependencies. +import torch +import numpy as np +import matplotlib.pyplot as plt +import matplotlib.animation as animation +from neuralop.losses.differentiation import FiniteDiff + +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + +# %% +# .. raw:: html +# +#
+# +# Defining our problem +# -------------------- +# We aim to solve the 2D viscous Burger's equations: +# +# .. math:: +# \frac{\partial u}{\partial t} + u \frac{\partial u}{\partial x} + v \frac{\partial u}{\partial y} = \nu \left(\frac{\partial^2 u}{\partial x^2} + \frac{\partial^2 u}{\partial y^2}\right) +# +# .. math:: +# \frac{\partial v}{\partial t} + u \frac{\partial v}{\partial x} + v \frac{\partial v}{\partial y} = \nu \left(\frac{\partial^2 v}{\partial x^2} + \frac{\partial^2 v}{\partial y^2}\right) + +## Simulation parameters +Lx, Ly = 2.0, 2.0 # Domain lengths +nx, ny = 64, 64 # Grid resolution +T = 1 # Total simulation time +dt = 0.001 # Time step +nu = 0.04 # Viscosity + +## Create grid +X = torch.linspace(0, Lx, nx, device=device).repeat(ny, 1).T +Y = torch.linspace(0, Ly, ny, device=device).repeat(nx, 1) +dx = Lx / (nx - 1) +dy = Ly / (ny - 1) +nt = int(T / dt) + +## Initialize finite difference operator +fd = FiniteDiff(dim=2, h=(dx, dy)) + +## Initial condition +u = -torch.sin(2 * np.pi * Y).to(device) +v = torch.cos(2 * np.pi * X).to(device) + + +# %% +# .. raw:: html +# +#
+# +# Simulate evolution using numerical solver +# ----------------------------------------- + +u_evolution = [u.clone()] +v_evolution = [v.clone()] + +for _ in range(nt): + # Compute first-order derivatives + u_x = fd.dx(u) + u_y = fd.dy(u) + v_x = fd.dx(v) + v_y = fd.dy(v) + + # Compute second-order derivatives + u_xx = fd.dx(u_x) + u_yy = fd.dy(u_y) + v_xx = fd.dx(v_x) + v_yy = fd.dy(v_y) + + # Evolve in time using Euler's method + u_next = u + dt * (-u * u_x - v * u_y + nu * (u_xx + u_yy)) + v_next = v + dt * (-u * v_x - v * v_y + nu * (v_xx + v_yy)) + + u, v = u_next.clone(), v_next.clone() + u_evolution.append(u.clone()) + v_evolution.append(v.clone()) + +u_evolution = torch.stack(u_evolution).cpu().numpy() +v_evolution = torch.stack(v_evolution).cpu().numpy() + +# %% +# .. raw:: html +# +#
+# +# Animating the solution +# ---------------------- + +num_frames = 100 +frame_indices = ( + torch.linspace(0, len(u_evolution) - 1, num_frames, dtype=torch.int).cpu().numpy() +) +u_frames = u_evolution[frame_indices] +v_frames = v_evolution[frame_indices] + +fig, axs = plt.subplots(1, 2, figsize=(12, 6)) +cmap_u = axs[0].imshow(u_frames[0], extent=[0, Lx, 0, Ly], origin="lower", cmap="plasma") +axs[0].set_title("Velocity u") +plt.colorbar(cmap_u, ax=axs[0], shrink=0.75) +cmap_v = axs[1].imshow(v_frames[0], extent=[0, Lx, 0, Ly], origin="lower", cmap="plasma") +axs[1].set_title("Velocity v") +plt.colorbar(cmap_v, ax=axs[1], shrink=0.75) + + +def update(frame): + cmap_u.set_data(u_frames[frame]) + cmap_v.set_data(v_frames[frame]) + axs[0].set_title(f"Velocity u (Time: {frame_indices[frame] * dt:.3f})") + axs[1].set_title(f"Velocity v (Time: {frame_indices[frame] * dt:.3f})") + axs[0].set_xticks([]) + axs[0].set_yticks([]) + axs[1].set_xticks([]) + axs[1].set_yticks([]) + return cmap_u, cmap_v + +ani = animation.FuncAnimation(fig, update, frames=len(u_frames), interval=50, blit=False) \ No newline at end of file diff --git a/sources/neuraloperator/examples/data_gen/plot_diffusion_advection_solver.py b/sources/neuraloperator/examples/data_gen/plot_diffusion_advection_solver.py new file mode 100644 index 0000000000000000000000000000000000000000..7cba7c8411a40f291e5e7607fac93ac2bcd0f726 --- /dev/null +++ b/sources/neuraloperator/examples/data_gen/plot_diffusion_advection_solver.py @@ -0,0 +1,125 @@ +""" +.. _diffusion_advection_fd_vis : + +A simple finite-difference solver for the diffusion-advection equation +====================================================================== +An intro to our loss module's finite difference utility demonstrating +its use to create a simple numerical solver for the diffusion-advection equation. +""" +# %% +# .. raw:: html +# +#
+# +# Import the library +# ------------------ +# We first import our `neuralop` library and required dependencies. +import torch +import numpy as np +import matplotlib.pyplot as plt +import matplotlib.animation as animation + +from neuralop.losses.differentiation import FiniteDiff + +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + + +# %% +# .. raw:: html +# +#
+# +# Defining our problem +# -------------------- +# We aim to solve the 2D diffusion advection equation: +# +# .. math:: +# \frac{\partial u}{\partial t} + c_x \frac{\partial u}{\partial x} + c_y \frac{\partial u}{\partial y} = \nu \left(\frac{\partial^2 u}{\partial x^2} + \frac{\partial^2 u}{\partial y^2}\right) + f(x,y,t) +# +# Where :math:`f(x,y,t)` is a source term and :math:`c_x` and :math:`c_y` are advection speeds in x and y. +# We set simulation parameters below: + +## Simulation parameters +Lx, Ly = 2.0, 2.0 # Domain lengths +nx, ny = 64, 64 # Grid resolution +T = 1.6 # Total simulation time +dt = 0.001 # Time step +nu = 0.02 # diffusion coefficient +cx, cy = 1.0, 0.6 # advection speeds + +## Create grid +X = torch.linspace(0, Lx, nx, device=device).repeat(ny, 1).T +Y = torch.linspace(0, Ly, ny, device=device).repeat(nx, 1) +dx = Lx / (nx - 1) +dy = Ly / (ny - 1) +nt = int(T / dt) + +## Initialize finite difference operator +fd = FiniteDiff(dim=2, h=(dx, dy)) + + +## Initial condition and source term +u = ( + -torch.sin(2 * np.pi * Y) * torch.cos(2 * np.pi * X) + + 0.3 * torch.exp(-((X - 0.75) ** 2 + (Y - 0.5) ** 2) / 0.02) + - 0.3 * torch.exp(-((X - 1.25) ** 2 + (Y - 1.5) ** 2) / 0.02) +).to(device) + + +def source_term(X, Y, t): + return 0.2 * torch.sin(3 * np.pi * X) * torch.cos(3 * np.pi * Y) * torch.cos(4 * np.pi * t) + +# %% +# .. raw:: html +# +#
+# +# Simulate evolution using numerical solver +# ----------------------------------------- +u_evolution = [u.clone()] + +t = torch.tensor(0.0) +for _ in range(nt): + # Compute derivatives + u_x = fd.dx(u) + u_y = fd.dy(u) + u_xx = fd.dx(u_x) + u_yy = fd.dy(u_y) + + # Evolve one step in time using Euler's method + u = u + dt * (-cx * u_x - cy * u_y + nu * (u_xx + u_yy) + source_term(X, Y, t)) + t += dt + u_evolution.append(u.clone()) + +u_evolution = torch.stack(u_evolution).cpu().numpy() + + +# %% +# .. raw:: html +# +#
+# +# Animate our solution +# -------------------- + +num_frames = 100 +frame_indices = ( + torch.linspace(0, len(u_evolution) - 1, num_frames, dtype=torch.int).cpu().numpy() +) +u_frames = u_evolution[frame_indices] + +fig, ax = plt.subplots(figsize=(6, 6)) +cmap_u = ax.imshow(u_frames[0], extent=[0, Lx, 0, Ly], origin="lower", cmap="plasma") +ax.set_title("Advection-Diffusion: u") +plt.colorbar(cmap_u, ax=ax, shrink=0.75) + + +def update(frame): + cmap_u.set_data(u_frames[frame]) + ax.set_title(f"Time: {frame_indices[frame] * dt:.3f}") + ax.set_xticks([]) + ax.set_yticks([]) + return (cmap_u,) + + +ani = animation.FuncAnimation(fig, update, frames=len(u_frames), interval=50, blit=False) \ No newline at end of file diff --git a/sources/neuraloperator/examples/layers/GALLERY_HEADER.rst b/sources/neuraloperator/examples/layers/GALLERY_HEADER.rst new file mode 100644 index 0000000000000000000000000000000000000000..382804df56fff83a56044d303d87807fe85a47c5 --- /dev/null +++ b/sources/neuraloperator/examples/layers/GALLERY_HEADER.rst @@ -0,0 +1,6 @@ +.. _layer_examples : + +Layers +------ + +Examples of individual layers which comprise operators or parts of operators for composition into end-to-end models. diff --git a/sources/neuraloperator/examples/layers/einstein.jpg b/sources/neuraloperator/examples/layers/einstein.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d352aca639ee2c3671fe6f9f5835982c7109e812 --- /dev/null +++ b/sources/neuraloperator/examples/layers/einstein.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3e1f218f8367b715f4f05589e09261988fcd64926d327dccaa82d6142016e3e0 +size 52845 diff --git a/sources/neuraloperator/examples/layers/plot_DISCO_convolutions.py b/sources/neuraloperator/examples/layers/plot_DISCO_convolutions.py new file mode 100644 index 0000000000000000000000000000000000000000..8b04150ba62ec10a3d856f573cf5ab2cc38f3c0e --- /dev/null +++ b/sources/neuraloperator/examples/layers/plot_DISCO_convolutions.py @@ -0,0 +1,316 @@ +""" + +DISCO Convolutions +================== + +This tutorial demonstrates Discrete-Continuous (DISCO) convolutions, which are +the building blocks of localized neural operator frameworks. DISCO convolutions +are crucial for: + +- Learning localized patterns in data +- Handling both equidistant and unstructured grids +- Enabling efficient computation on irregular domains +- Bridging discrete and continuous representations + +The tutorial covers various DISCO convolution types and their applications +in neural operator architectures. + +""" + +# %% +# .. raw:: html +# +#
+# +# Preparation + + +import os +import torch +import torch.nn as nn +import numpy as np +import math +from functools import partial + +from matplotlib import image + +from torch_harmonics.quadrature import ( + legendre_gauss_weights, + lobatto_weights, + clenshaw_curtiss_weights, +) + +import matplotlib.pyplot as plt + +cmap = "inferno" +device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") + +from neuralop.layers.discrete_continuous_convolution import ( + DiscreteContinuousConv2d, + DiscreteContinuousConvTranspose2d, + EquidistantDiscreteContinuousConv2d, + EquidistantDiscreteContinuousConvTranspose2d, +) + +# %% +# .. raw:: html +# +#
+# +# Let's start by loading an example image +try: + _script_dir = os.path.dirname(os.path.abspath(__file__)) +except NameError: + _script_dir = os.getcwd() +einstein_path = os.path.join(_script_dir, "einstein.jpg") + +nx = 90 +ny = 120 + +img = image.imread(einstein_path) +data = nn.functional.interpolate( + torch.from_numpy(img).unsqueeze(0).unsqueeze(0), size=(ny, nx) +).squeeze() +plt.imshow(data, cmap=cmap) +plt.show() + +# %% +# .. raw:: html +# +#
+# +# Let's create a grid on which the data lives + +x_in = torch.linspace(0, 2, nx) +y_in = torch.linspace(0, 3, ny) + +x_in, y_in = torch.meshgrid(x_in, y_in, indexing="ij") +grid_in = torch.stack([x_in.reshape(-1), y_in.reshape(-1)]) + +# compute the correct quadrature weights +# IMPORTANT: this needs to be done right in order for the DISCO convolution to be normalized proeperly +w_x = 2 * torch.ones_like(x_in) / nx +w_y = 3 * torch.ones_like(y_in) / ny +q_in = (w_x * w_y).reshape(-1) + +# %% +# .. raw:: html +# +#
+# +# Visualize the grid + +plt.figure( + figsize=(4, 6), +) +plt.scatter(grid_in[0], grid_in[1], s=0.2) +plt.xlim(0, 2) +plt.ylim(0, 3) +plt.show() + + +# %% +# .. raw:: html +# +#
+# +# Format data into the same format and plot it on the grid + +data = data.permute(1, 0).flip(1).reshape(-1) + +plt.figure(figsize=(4,6)) +plt.tripcolor(grid_in[0], grid_in[1], data, cmap=cmap) +# plt.colorbar() +plt.xlim(0, 2) +plt.ylim(0, 3) +plt.show() + +# %% +# .. raw:: html +# +#
+# +# For the convolution output we require an output mesh +nxo = 90 +nyo = 120 + +x_out = torch.linspace(0, 2, nxo) +y_out = torch.linspace(0, 3, nyo) + +x_out, y_out = torch.meshgrid(x_out, y_out, indexing="ij") +grid_out = torch.stack([x_out.reshape(-1), y_out.reshape(-1)]) + +# compute the correct quadrature weights +w_x = 2 * torch.ones_like(x_out) / nxo +w_y = 3 * torch.ones_like(y_out) / nyo +q_out = (w_x * w_y).reshape(-1) + +# %% +# .. raw:: html +# +#
+# +# Initialize the convolution and set the weights to something resembling an edge filter/finit differences +conv = DiscreteContinuousConv2d( + 1, + 1, + grid_in=grid_in, + grid_out=grid_out, + quadrature_weights=q_in, + kernel_shape=[2, 4], + radius_cutoff=5 / nyo, + periodic=False, +).float() + +# initialize a kernel resembling an edge filter +w = torch.zeros_like(conv.weight) +w[0, 0, 1] = 1.0 +w[0, 0, 3] = -1.0 +conv.weight = nn.Parameter(w) +psi = conv.get_local_filter_matrix() + +# %% +# .. raw:: html +# +#
+# +# Apply the DISCO convolution to the data and plot it +# in order to compute the convolved image, we need to first bring it into the right shape with `batch_size x n_channels x n_grid_points` +out = conv(data.reshape(1, 1, -1)) + +print(out.shape) + +plt.figure(figsize=(4,6)) +plt.imshow(torch.flip(out.squeeze().detach().reshape(nxo, nyo).transpose(0,1), dims=(-2, )), cmap=cmap) +plt.colorbar() +plt.show() + +out1 = torch.flip(out.squeeze().detach().reshape(nxo, nyo).transpose(0, 1), dims=(-2,)) + +# %% +# .. raw:: html +# +#
+# +# Do the same but on an equidistant grid +conv_equi = EquidistantDiscreteContinuousConv2d( + 1, + 1, + (nx, ny), + (nxo, nyo), + kernel_shape=[2, 4], + radius_cutoff=5 / nyo, + domain_length=[2, 3], +) + +# initialize a kernel resembling an edge filter +w = torch.zeros_like(conv.weight) +w[0, 0, 1] = 1.0 +w[0, 0, 3] = -1.0 +conv_equi.weight = nn.Parameter(w) + +data = nn.functional.interpolate( + torch.from_numpy(img).unsqueeze(0).unsqueeze(0), size=(ny, nx) +).float() + +out_equi = conv_equi(data) + +print(out_equi.shape) + +plt.figure(figsize=(4,6)) +plt.imshow(out_equi.squeeze().detach(), cmap=cmap) +plt.colorbar() +plt.show() + +out2 = out_equi.squeeze().detach() + +print(out2.shape) + +# %% +# .. raw:: html +# +#
+# +# Visualize the local filter matrix + +plt.figure(figsize=(4,6)) +plt.imshow(conv_equi.get_local_filter_matrix()[0].detach(), cmap=cmap) +plt.colorbar() + +# %% +# .. raw:: html +# +#
+# +# Test the transpose convolution +convt = DiscreteContinuousConvTranspose2d( + 1, + 1, + grid_in=grid_out, + grid_out=grid_in, + quadrature_weights=q_out, + kernel_shape=[2, 4], + radius_cutoff=3 / nyo, + periodic=False, +).float() + +# initialize a flat +w = torch.zeros_like(conv.weight) +w[0, 0, 0] = 1.0 +w[0, 0, 1] = 1.0 +w[0, 0, 2] = 1.0 +w[0, 0, 3] = 1.0 +convt.weight = nn.Parameter(w) + +data = ( + nn.functional.interpolate( + torch.from_numpy(img).unsqueeze(0).unsqueeze(0), size=(ny, nx) + ) + .squeeze().float() + .permute(1, 0).flip(1).reshape(-1) +) +out = convt(data.reshape(1, 1, -1)) + +print(out.shape) + +plt.figure(figsize=(4,6)) +plt.imshow(torch.flip(out.squeeze().detach().reshape(nx, ny).transpose(0,1), dims=(-2, )), cmap=cmap) +plt.colorbar() +plt.show() + + +# %% +# .. raw:: html +# +#
+# +# Test the equidistant transpose convolution +convt_equi = EquidistantDiscreteContinuousConvTranspose2d( + 1, + 1, + (nxo, nyo), + (nx, ny), + kernel_shape=[2, 4], + radius_cutoff=3 / nyo, + domain_length=[2, 3], +) + +# initialize a flat +w = torch.zeros_like(convt_equi.weight) +w[0, 0, 0] = 1.0 +w[0, 0, 1] = 1.0 +w[0, 0, 2] = 1.0 +w[0, 0, 3] = 1.0 +convt_equi.weight = nn.Parameter(w) + +data = nn.functional.interpolate( + torch.from_numpy(img).unsqueeze(0).unsqueeze(0), size=(nyo, nxo) +).float() +out_equi = convt_equi(data) + +print(out_equi.shape) + +plt.figure(figsize=(4,6)) +plt.imshow(out_equi.squeeze().detach(), cmap=cmap) +plt.colorbar() +plt.show() diff --git a/sources/neuraloperator/examples/layers/plot_embeddings.py b/sources/neuraloperator/examples/layers/plot_embeddings.py new file mode 100644 index 0000000000000000000000000000000000000000..1da46d136cfd0d4e1c05d0b79169c06781317f41 --- /dev/null +++ b/sources/neuraloperator/examples/layers/plot_embeddings.py @@ -0,0 +1,235 @@ +""" +Grid Embeddings +=============== + +Grid embeddings encode spatial coordinates in neural operators, helping models understand geometric structure. This tutorial shows how to use: + +- 2D and N-dimensional grid embeddings +- Custom coordinate systems +- Different embedding types for various domains + +Grid embeddings are key for PDE solving, computer vision, and other spatially-structured problems. They add coordinate information and help neural operators learn spatial relationships. +""" + +# %% +# .. raw:: html +# +#
+# +# Import dependencies +# ------------------- +# We import the necessary modules for working with grid embeddings + +import random +import matplotlib.pyplot as plt +import torch + +device = "cpu" + +# %% +# .. raw:: html +# +#
+# +# Understanding grid embeddings +# ----------------------------- +# As we show in :ref:`small_darcy_vis`, we apply a 2D grid positional encoding to our data +# before passing it into the FNO. This embedding has been shown to improve model performance +# in a variety of applications by providing spatial context to the neural operator. +# +# Let's walk through its use. We start with a function that gives the coordinates of the +# bottom-left corners of each pixel in a grid: + +from neuralop.layers.embeddings import regular_grid_2d + +grid_2d = ( + torch.stack(regular_grid_2d(spatial_dims=(8, 8))).permute(1, 2, 0).view(-1, 2) +) # reshape into (64, 2) + +# Visualize the 2D grid coordinates +plt.scatter(grid_2d[:, 0], grid_2d[:, 1], color="orange", label="2D regular grid") +plt.legend() +plt.title("2D Grid Coordinates") +plt.xlabel("X coordinate") +plt.ylabel("Y coordinate") +plt.show() + +# %% +# .. raw:: html +# +#
+# +# Applying grid embeddings to data +# --------------------------------- +# In practice, we concatenate these two channels, representing the x- and y-coordinates +# of each pixel in an example, after the channels which encode physical variables +# in our PDE problems. This provides spatial context to the neural operator. + +from neuralop.data.datasets import load_darcy_flow_small +from neuralop.layers.embeddings import GridEmbedding2D + +# Load the Darcy-Flow dataset for demonstration +_, test_loaders, _ = load_darcy_flow_small( + n_train=10, + batch_size=1, + test_resolutions=[16, 32], + n_tests=[16, 16], + test_batch_sizes=[2, 2], + encode_output=False, +) + +# Get a sample from the dataset +loader_16 = test_loaders[16] +example = next(iter(loader_16)) +x = example["x"] +print(f"One batch of x is of shape: {x.shape}") + +# Note: our Darcy dataset is generated on the unit square, but our grid +# embedding's boundaries are configurable. +grid_embedding = GridEmbedding2D(in_channels=1, grid_boundaries=[[0, 1], [0, 1]]) +x = grid_embedding(x) +print(f"After embedding, x is of shape: {x.shape}") + +# %% +# .. raw:: html +# +#
+# +# Visualizing the embedded data +# ----------------------------- +# We can visualize how the grid embedding adds coordinate information to our data. +# The embedding adds two channels: one for x-coordinates and one for y-coordinates. + +# Grab the first element of the batch +x = x[0] +fig = plt.figure(figsize=(7, 7)) + +# Plot the original input data +ax = fig.add_subplot(2, 2, 1) +ax.imshow(x[0], cmap="gray") +ax.set_title("Input x") + +# Plot the x-coordinate embedding +ax = fig.add_subplot(2, 2, 3) +ax.imshow(x[1]) +ax.set_title("x-coordinate embedding") + +# Plot the y-coordinate embedding +ax = fig.add_subplot(2, 2, 4) +ax.imshow(x[2]) +ax.set_title("y-coordinate embedding") + +fig.suptitle("Visualizing one input sample with positional embeddings", y=0.98) +plt.tight_layout() +fig.show() + + +# %% +# .. raw:: html +# +#
+# +# Discretization invariance +# -------------------------- +# Our embeddings are also designed with discretization-invariance in mind. +# Without any changes, we can apply the same embedding to higher-resolution data. +# This is crucial for neural operators that need to work at different resolutions. + +loader_32 = test_loaders[32] +example = next(iter(loader_32)) +x = example["x"] +print(f"One batch of x is of shape: {x.shape}") + +# Apply the same grid embedding to higher-resolution data +x = grid_embedding(x) +print(f"After embedding, x is of shape: {x.shape}") + +# %% +# .. raw:: html +# +#
+# +# Visualizing higher-resolution embeddings +# ---------------------------------------- +# We can see how the grid embedding scales to different resolutions. +# The coordinate information is automatically adjusted to the new grid size. + +# Grab the first element of the batch +x = x[0] +fig = plt.figure(figsize=(7, 7)) + +# Plot the original input data +ax = fig.add_subplot(2, 2, 1) +ax.imshow(x[0], cmap="gray") +ax.set_title("Input x") + +# Plot the x-coordinate embedding +ax = fig.add_subplot(2, 2, 3) +ax.imshow(x[1]) +ax.set_title("x-coordinate embedding") + +# Plot the y-coordinate embedding +ax = fig.add_subplot(2, 2, 4) +ax.imshow(x[2]) +ax.set_title("y-coordinate embedding") + +fig.suptitle("Visualizing one input sample with positional embeddings", y=0.98) +plt.tight_layout() +fig.show() + +# %% +# .. raw:: html +# +#
+# +# Understanding discretization invariance +# --------------------------------------- +# The grid embeddings automatically adapt to different resolutions: +# 1. The coordinate values are normalized to the same range regardless of resolution +# 2. The spatial relationships are preserved across different grid sizes +# 3. This allows neural operators to work seamlessly at different resolutions +# 4. The same model can be applied to data of varying spatial discretization + +# %% +# .. raw:: html +# +#
+# +# Working with 3D grid embeddings +# -------------------------------- +# Let's also demonstrate how to embed a 3D tensor. +# This is useful for problems involving 3D spatial data, such as: +# - 3D fluid dynamics +# - Volumetric medical imaging +# - 3D material science problems + +from neuralop.layers.embeddings import GridEmbeddingND + +# Create a 3D tensor with one channel +cube_len = 5 +x = torch.randn(1, 1, cube_len, cube_len, cube_len) +embedding_3d = GridEmbeddingND(in_channels=1, dim=3, grid_boundaries=[[0, 1]] * 3) + +# Apply 3D grid embedding +x = embedding_3d(x) + +# %% +# .. raw:: html +# +#
+# +# Visualizing 3D grid embeddings +# ------------------------------ +# We can visualize the 3D embeddings by showing the coordinate information +# in 3D space. Each point represents a spatial location with its coordinates. + +# Grab only the appended positional embedding channels +x = x[0, 1:, ...].permute(1, 2, 3, 0).view(-1, 3) +fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) +plot = ax.scatter(x[:, 0], x[:, 1], x[:, 2], c=x[:, 2]) +fig.colorbar(plot, ax=ax, shrink=0.6) +ax.set_title("3D positional encoding, color=Z value") +ax.set_xlabel("X") +ax.set_ylabel("Y") +ax.set_zlabel("Z") +plt.show() diff --git a/sources/neuraloperator/examples/layers/plot_finite_diff.py b/sources/neuraloperator/examples/layers/plot_finite_diff.py new file mode 100644 index 0000000000000000000000000000000000000000..97d535a915c9c70f61afea35a27cc22b2e2e364d --- /dev/null +++ b/sources/neuraloperator/examples/layers/plot_finite_diff.py @@ -0,0 +1,613 @@ +""" +.. _finite_diff : + +Finite Differences +================== + +This tutorial demonstrates the use of finite difference methods for computing +derivatives of functions in neural operators. Finite differences are crucial for: + +- Computing gradients and higher-order derivatives +- Implementing physics-informed loss functions +- Enforcing differential equation constraints +- Computing divergence, curl, and Laplacian operators + +The `FiniteDiff` class provides efficient implementations of finite difference +schemes for computing derivatives in 1D, 2D, and 3D domains. +""" + +import torch +import matplotlib.pyplot as plt +import numpy as np +from neuralop.losses.differentiation import FiniteDiff + +# %% +# .. raw:: html +# +#
+# +# 1D Finite Difference Examples +# ============================= +# Here we demonstrate the FiniteDiff class for 1D functions + +# %% +# .. raw:: html +# +#
+# +# Creating an example of 1D function +# ----------------------------------------------- +# Here we consider f(x) = exp(-x) * sin(x) on [0, 2π] +L_x = 2 * torch.pi +nx = 256 +x = torch.linspace(0, L_x, nx, dtype=torch.float64) + +f_1d = torch.exp(-x) * torch.sin(x) + +# %% +# .. raw:: html +# +#
+# +# Differentiate the 1D signal +# ---------------------------------------------------------------- +# We use the FiniteDiff class with dim=1 +h = L_x / nx + +# Compute derivatives +fd1d = FiniteDiff(dim=1, h=h, periodic_in_x=False) +df_dx = fd1d.dx(f_1d) +d2f_dx2 = fd1d.dx(f_1d, order=2) + +# Expected analytical results for f(x) = exp(-x) * sin(x) +df_dx_expected = torch.exp(-x) * (torch.cos(x) - torch.sin(x)) # ∂f/∂x +d2f_dx2_expected = torch.exp(-x) * (-2 * torch.cos(x)) # ∂²f/∂x² + +# %% +# .. raw:: html +# +#
+# +# Plot the 1D results +# --------------------------------- +fig, axes = plt.subplots(3, 1, figsize=(10, 18)) +fig.suptitle("1D Finite Differences: f(x) = exp(-x) * sin(x)") + +# Original function +axes[0].plot(x.cpu().numpy(), f_1d.cpu().numpy(), "b-", linewidth=1.5) +axes[0].set_title("Original: exp(-x) * sin(x)") +axes[0].set_xlabel("x") +axes[0].set_ylabel("f(x)") + +# First derivative +axes[1].plot(x.cpu().numpy(), df_dx.cpu().numpy(), "r-", linewidth=1.5, label="Computed") +axes[1].plot(x.cpu().numpy(), df_dx_expected.cpu().numpy(), "r--", linewidth=2, label="Expected: exp(-x) * (cos(x) - sin(x))") +axes[1].set_title('∂f/∂x') +axes[1].set_xlabel('x') +axes[1].set_ylabel('∂f/∂x') +axes[1].legend() + +# Second derivative +axes[2].plot(x.cpu().numpy(), d2f_dx2.cpu().numpy(), "g-", linewidth=1.5, label="Computed") +axes[2].plot(x.cpu().numpy(), d2f_dx2_expected.cpu().numpy(), "g--", linewidth=2, label="Expected: exp(-x) * (-2cos(x))") +axes[2].set_title("∂²f/∂x²") +axes[2].set_xlabel("x") +axes[2].set_ylabel("∂²f/∂x²") +axes[2].legend() + +plt.tight_layout() +plt.show() + +# %% +# .. raw:: html +# +#
+# +# 2D Finite Difference Examples +# ============================= +# Here we demonstrate the FiniteDiff class for 2D functions + +# %% +# .. raw:: html +# +#
+# +# Creating an example of 2D function +# ----------------------------------------------- +# Here we consider f(x,y) = exp(-x) * sin(y), which is non-periodic on [0, 2π] × [0, 2π] +L_x, L_y = 2 * torch.pi, 2 * torch.pi +nx, ny = 256, 256 +x = torch.linspace(0, L_x, nx, dtype=torch.float64) +y = torch.linspace(0, L_y, ny, dtype=torch.float64) +X, Y = torch.meshgrid(x, y, indexing="ij") + +# Test function: f(x,y) = exp(-x) * sin(y) +f_2d = torch.exp(-X) * torch.sin(Y) + +# %% +# .. raw:: html +# +#
+# +# Differentiate the 2D signal +# ---------------------------------------------------------------- +# We use the FiniteDiff class with dim=2 to compute derivatives +fd2d = FiniteDiff( + dim=2, h=(L_x / nx, L_y / ny), periodic_in_x=False, periodic_in_y=False +) + +# Compute derivatives +df_dx = fd2d.dx(f_2d) +df_dy = fd2d.dy(f_2d) +d2f_dx2 = fd2d.dx(f_2d, order=2) +d2f_dy2 = fd2d.dy(f_2d, order=2) +laplacian = fd2d.laplacian(f_2d) + +# Expected analytical results for f(x,y) = exp(-x) * sin(y) +df_dx_expected = -torch.exp(-X) * torch.sin(Y) # ∂f/∂x +df_dy_expected = torch.exp(-X) * torch.cos(Y) # ∂f/∂y +d2f_dx2_expected = torch.exp(-X) * torch.sin(Y) # ∂²f/∂x² +d2f_dy2_expected = -torch.exp(-X) * torch.sin(Y) # ∂²f/∂y² +laplacian_expected = torch.zeros_like(X) # ∇²f + +# %% +# .. raw:: html +# +#
+# +# Plot the 2D results +# --------------------------------- +fig, axes = plt.subplots(2, 4, figsize=(20, 10)) +fig.suptitle("2D Finite Differences: f(x,y) = exp(-x) * sin(y)") + +# Compute consistent colorbar limits for each derivative pair +df_dx_min = min(df_dx.min().item(), df_dx_expected.min().item()) +df_dx_max = max(df_dx.max().item(), df_dx_expected.max().item()) +df_dy_min = min(df_dy.min().item(), df_dy_expected.min().item()) +df_dy_max = max(df_dy.max().item(), df_dy_expected.max().item()) + +# Compute consistent colorbar limits for second derivatives +d2f_dx2_min = min(d2f_dx2.min().item(), d2f_dx2_expected.min().item()) +d2f_dx2_max = max(d2f_dx2.max().item(), d2f_dx2_expected.max().item()) +d2f_dy2_min = min(d2f_dy2.min().item(), d2f_dy2_expected.min().item()) +d2f_dy2_max = max(d2f_dy2.max().item(), d2f_dy2_expected.max().item()) + +# Compute consistent colorbar limits for laplacian +laplacian_min = min(laplacian.min().item(), laplacian_expected.min().item()) +laplacian_max = max(laplacian.max().item(), laplacian_expected.max().item()) + +# Original function +im0 = axes[0, 0].imshow(f_2d.cpu().numpy()) +axes[0, 0].set_title("Original: exp(-x) * sin(y)") +plt.colorbar(im0, ax=axes[0, 0], shrink=0.62) + +# ∂f/∂x computed +im1 = axes[0, 1].imshow(df_dx.cpu().numpy(), vmin=df_dx_min, vmax=df_dx_max) +axes[0, 1].set_title("∂f/∂x (computed)") +plt.colorbar(im1, ax=axes[0, 1], shrink=0.62) + +# ∂f/∂x expected +im2 = axes[0, 2].imshow(df_dx_expected.cpu().numpy(), vmin=df_dx_min, vmax=df_dx_max) +axes[0, 2].set_title("∂f/∂x (expected: -exp(-x) * sin(y))") +plt.colorbar(im2, ax=axes[0, 2], shrink=0.62) + +# ∂f/∂y computed +im3 = axes[0, 3].imshow(df_dy.cpu().numpy(), vmin=df_dy_min, vmax=df_dy_max) +axes[0, 3].set_title("∂f/∂y (computed)") +plt.colorbar(im3, ax=axes[0, 3], shrink=0.62) + +# ∂f/∂y expected +im4 = axes[1, 0].imshow(df_dy_expected.cpu().numpy(), vmin=df_dy_min, vmax=df_dy_max) +axes[1, 0].set_title("∂f/∂y (expected: exp(-x) * cos(y))") +plt.colorbar(im4, ax=axes[1, 0], shrink=0.62) + +# Laplacian computed +im5 = axes[1, 1].imshow(laplacian.cpu().numpy(), vmin=laplacian_min, vmax=laplacian_max) +axes[1, 1].set_title("∇²f (computed)") +plt.colorbar(im5, ax=axes[1, 1], shrink=0.62) + +# Laplacian expected +im6 = axes[1, 2].imshow(laplacian_expected.cpu().numpy(), vmin=laplacian_min, vmax=laplacian_max) +axes[1, 2].set_title("∇²f (expected: 0)") +plt.colorbar(im6, ax=axes[1, 2], shrink=0.62) + +# Error in laplacian +error = torch.abs(laplacian - laplacian_expected) +im7 = axes[1, 3].imshow(error.cpu().numpy()) +axes[1, 3].set_title("Error in ∇²f") +plt.colorbar(im7, ax=axes[1, 3], shrink=0.62) + +plt.tight_layout() +plt.show() + +# %% +# .. raw:: html +# +#
+# +# Test gradient computation +# ------------------------- +# Compute gradient of the scalar field +gradient = fd2d.gradient(f_2d) # Returns [df_dx, df_dy] + +# Plot gradient components +fig, axes = plt.subplots(2, 2, figsize=(12, 10)) +fig.suptitle("Gradient Components: ∇f = [∂f/∂x, ∂f/∂y]") + +# ∂f/∂x from gradient +im0 = axes[0, 0].imshow(gradient[0].cpu().numpy(), vmin=df_dx_min, vmax=df_dx_max) +axes[0, 0].set_title("∂f/∂x from gradient") +plt.colorbar(im0, ax=axes[0, 0], shrink=0.62) + +# ∂f/∂y from gradient +im1 = axes[0, 1].imshow(gradient[1].cpu().numpy(), vmin=df_dy_min, vmax=df_dy_max) +axes[0, 1].set_title("∂f/∂y from gradient") +plt.colorbar(im1, ax=axes[0, 1], shrink=0.62) + +# Compare with direct computation +im2 = axes[1, 0].imshow((gradient[0] - df_dx).cpu().numpy()) +axes[1, 0].set_title("Difference: gradient[0] - df_dx") +plt.colorbar(im2, ax=axes[1, 0], shrink=0.62) + +im3 = axes[1, 1].imshow((gradient[1] - df_dy).cpu().numpy()) +axes[1, 1].set_title("Difference: gradient[1] - df_dy") +plt.colorbar(im3, ax=axes[1, 1], shrink=0.62) + +plt.tight_layout() +plt.show() + +# %% +# .. raw:: html +# +#
+# +# Test vector field operations +# ----------------------------- +# Create a vector field: u = [exp(-x), sin(y)] +u1 = torch.exp(-X) +u2 = torch.sin(Y) +u_vector = torch.stack([u1, u2], dim=0) + +# Compute divergence and curl +divergence = fd2d.divergence(u_vector) +curl = fd2d.curl(u_vector) + +# Expected analytical results +# ∇·u = ∂u₁/∂x + ∂u₂/∂y = -exp(-x) + cos(y) +divergence_expected = -torch.exp(-X) + torch.cos(Y) +# ∇×u = ∂u₂/∂x - ∂u₁/∂y = 0 - 0 = 0 (since u₁ doesn't depend on y, u₂ doesn't depend on x) +curl_expected = torch.zeros_like(X) + +# %% +# .. raw:: html +# +#
+# +# Plot vector field operations +# ----------------------------- +fig, axes = plt.subplots(2, 3, figsize=(18, 12)) +fig.suptitle("Vector Field Operations: u = [exp(-x), sin(y)]") + +# Compute consistent colorbar limits for vector field components +u1_min = min(u1.min().item(), u1.max().item()) +u1_max = max(u1.min().item(), u1.max().item()) +u2_min = min(u2.min().item(), u2.max().item()) +u2_max = max(u2.min().item(), u2.max().item()) + +# Compute consistent colorbar limits for divergence +div_min = min(divergence.min().item(), divergence_expected.min().item()) +div_max = max(divergence.max().item(), divergence_expected.max().item()) + +# Compute consistent colorbar limits for curl +curl_min = min(curl.min().item(), curl_expected.min().item()) +curl_max = max(curl.max().item(), curl_expected.max().item()) + +# Vector field components +im0 = axes[0, 0].imshow(u1.cpu().numpy(), vmin=u1_min, vmax=u1_max) +axes[0, 0].set_title("u₁ = exp(-x)") +plt.colorbar(im0, ax=axes[0, 0], shrink=0.62) + +im1 = axes[0, 1].imshow(u2.cpu().numpy(), vmin=u2_min, vmax=u2_max) +axes[0, 1].set_title("u₂ = sin(y)") +plt.colorbar(im1, ax=axes[0, 1], shrink=0.62) + +# Divergence +im2 = axes[0, 2].imshow(divergence.cpu().numpy(), vmin=div_min, vmax=div_max) +axes[0, 2].set_title("∇·u (computed)") +plt.colorbar(im2, ax=axes[0, 2], shrink=0.62) + +# Divergence expected +im3 = axes[1, 0].imshow(divergence_expected.cpu().numpy(), vmin=div_min, vmax=div_max) +axes[1, 0].set_title("∇·u (expected: -exp(-x) + cos(y))") +plt.colorbar(im3, ax=axes[1, 0], shrink=0.62) + +# Curl +im4 = axes[1, 1].imshow(curl.cpu().numpy(), vmin=curl_min, vmax=curl_max) +axes[1, 1].set_title("∇×u (computed)") +plt.colorbar(im4, ax=axes[1, 1], shrink=0.62) + +# Curl expected +im5 = axes[1, 2].imshow(curl_expected.cpu().numpy(), vmin=curl_min, vmax=curl_max) +axes[1, 2].set_title("∇×u (expected: 0)") +plt.colorbar(im5, ax=axes[1, 2], shrink=0.62) + +plt.tight_layout() +plt.show() + +# %% +# .. raw:: html +# +#
+# +# Additional verification plots +# ----------------------------- +# Show second derivatives with consistent colorbars +fig, axes = plt.subplots(2, 2, figsize=(12, 10)) +fig.suptitle("Second Derivatives: ∂²f/∂x² and ∂²f/∂y²") + +# ∂²f/∂x² computed +im0 = axes[0, 0].imshow(d2f_dx2.cpu().numpy(), vmin=d2f_dx2_min, vmax=d2f_dx2_max) +axes[0, 0].set_title("∂²f/∂x² (computed)") +plt.colorbar(im0, ax=axes[0, 0], shrink=0.62) + +# ∂²f/∂x² expected +im1 = axes[0, 1].imshow(d2f_dx2_expected.cpu().numpy(), vmin=d2f_dx2_min, vmax=d2f_dx2_max) +axes[0, 1].set_title("∂²f/∂x² (expected: exp(-x) * sin(y))") +plt.colorbar(im1, ax=axes[0, 1], shrink=0.62) + +# ∂²f/∂y² computed +im2 = axes[1, 0].imshow(d2f_dy2.cpu().numpy(), vmin=d2f_dy2_min, vmax=d2f_dy2_max) +axes[1, 0].set_title("∂²f/∂y² (computed)") +plt.colorbar(im2, ax=axes[1, 0], shrink=0.62) + +# ∂²f/∂y² expected +im3 = axes[1, 1].imshow(d2f_dy2_expected.cpu().numpy(), vmin=d2f_dy2_min, vmax=d2f_dy2_max) +axes[1, 1].set_title("∂²f/∂y² (expected: -exp(-x) * sin(y))") +plt.colorbar(im3, ax=axes[1, 1], shrink=0.62) + +plt.tight_layout() +plt.show() + +# %% +# .. raw:: html +# +#
+# +# 3D Finite Difference Examples +# ============================= +# Here we demonstrate the FiniteDiff class for 3D functions + +# %% +# .. raw:: html +# +#
+# +# Creating an example of 3D function +# ----------------------------------------------- +# Here we consider f(x,y,z) = exp(-x) * sin(y) * cos(z), which is on [0, 2π]³ +L_x, L_y, L_z = 2 * torch.pi, 2 * torch.pi, 2 * torch.pi +nx, ny, nz = 80, 84, 76 +x = torch.linspace(0, L_x, nx, dtype=torch.float64) +y = torch.linspace(0, L_y, ny, dtype=torch.float64) +z = torch.linspace(0, L_z, nz, dtype=torch.float64) +X, Y, Z = torch.meshgrid(x, y, z, indexing="ij") + +# Test function: f(x,y,z) = exp(-x) * sin(y) * cos(z) +f_3d = torch.exp(-X) * torch.sin(Y) * torch.cos(Z) + +# %% +# .. raw:: html +# +#
+# +# Differentiate the 3D signal +# ---------------------------------------------------------------- +# We use the FiniteDiff class with dim=3 to compute derivatives +fd3d = FiniteDiff( + dim=3, h=(L_x / nx, L_y / ny, L_z / nz), + periodic_in_x=False, periodic_in_y=True, periodic_in_z=True, +) + +# Compute derivatives +df_dx = fd3d.dx(f_3d) +df_dy = fd3d.dy(f_3d) +df_dz = fd3d.dz(f_3d) +d2f_dx2 = fd3d.dx(f_3d, order=2) +d2f_dy2 = fd3d.dy(f_3d, order=2) +d2f_dz2 = fd3d.dz(f_3d, order=2) +laplacian_3d = fd3d.laplacian(f_3d) + +# Expected analytical results for f(x,y,z) = exp(-x) * sin(y) * cos(z) +df_dx_expected = -torch.exp(-X) * torch.sin(Y) * torch.cos(Z) # ∂f/∂x +df_dy_expected = torch.exp(-X) * torch.cos(Y) * torch.cos(Z) # ∂f/∂y +df_dz_expected = -torch.exp(-X) * torch.sin(Y) * torch.sin(Z) # ∂f/∂z + +d2f_dx2_expected = torch.exp(-X) * torch.sin(Y) * torch.cos(Z) # ∂²f/∂x² +d2f_dy2_expected = -torch.exp(-X) * torch.sin(Y) * torch.cos(Z) # ∂²f/∂y² +d2f_dz2_expected = -torch.exp(-X) * torch.sin(Y) * torch.cos(Z) # ∂²f/∂z² + +# Laplacian: ∇²f = ∂²f/∂x² + ∂²f/∂y² + ∂²f/∂z² +laplacian_3d_expected = -torch.exp(-X) * torch.sin(Y) * torch.cos(Z) + +# %% +# .. raw:: html +# +#
+# +# Plot 3D results at a specific z-slice +# ------------------------------------- +z_slice_idx = nz // 2 # Middle z-slice +z_slice_val = z[z_slice_idx].item() + +fig, axes = plt.subplots(2, 3, figsize=(18, 12)) +fig.suptitle(f"3D Finite Differences: f(x,y,z) = exp(-x) * sin(y) * cos(z) at z = {z_slice_val:.2f}") + +# Compute consistent colorbar limits for each derivative pair at the z-slice +df_dx_3d_slice = df_dx[:, :, z_slice_idx] +df_dx_expected_3d_slice = df_dx_expected[:, :, z_slice_idx] +df_dy_3d_slice = df_dy[:, :, z_slice_idx] +df_dy_expected_3d_slice = df_dy_expected[:, :, z_slice_idx] +df_dz_3d_slice = df_dz[:, :, z_slice_idx] +df_dz_expected_3d_slice = df_dz_expected[:, :, z_slice_idx] + +df_dx_3d_min = min(df_dx_3d_slice.min().item(), df_dx_expected_3d_slice.min().item()) +df_dx_3d_max = max(df_dx_3d_slice.max().item(), df_dx_expected_3d_slice.max().item()) +df_dy_3d_min = min(df_dy_3d_slice.min().item(), df_dy_expected_3d_slice.min().item()) +df_dy_3d_max = max(df_dy_3d_slice.max().item(), df_dy_expected_3d_slice.max().item()) +df_dz_3d_min = min(df_dz_3d_slice.min().item(), df_dz_expected_3d_slice.min().item()) +df_dz_3d_max = max(df_dz_3d_slice.max().item(), df_dz_expected_3d_slice.max().item()) + +# Original function at z-slice +im0 = axes[0, 0].imshow(f_3d[:, :, z_slice_idx].cpu().numpy()) +axes[0, 0].set_title(f"Original: exp(-x) * sin(y) * cos(z) at z = {z_slice_val:.2f}") +plt.colorbar(im0, ax=axes[0, 0], shrink=0.62) + +# ∂f/∂x computed +im1 = axes[0, 1].imshow(df_dx_3d_slice.cpu().numpy(), vmin=df_dx_3d_min, vmax=df_dx_3d_max) +axes[0, 1].set_title("∂f/∂x (computed)") +plt.colorbar(im1, ax=axes[0, 1], shrink=0.62) + +# ∂f/∂x expected +im2 = axes[0, 2].imshow(df_dx_expected_3d_slice.cpu().numpy(), vmin=df_dx_3d_min, vmax=df_dx_3d_max) +axes[0, 2].set_title("∂f/∂x (expected: -exp(-x) * sin(y) * cos(z))") +plt.colorbar(im2, ax=axes[0, 2], shrink=0.62) + +# ∂f/∂y computed +im3 = axes[1, 0].imshow(df_dy_3d_slice.cpu().numpy(), vmin=df_dy_3d_min, vmax=df_dy_3d_max) +axes[1, 0].set_title("∂f/∂y (computed)") +plt.colorbar(im3, ax=axes[1, 0], shrink=0.62) + +# ∂f/∂y expected +im4 = axes[1, 1].imshow(df_dy_expected_3d_slice.cpu().numpy(), vmin=df_dy_3d_min, vmax=df_dy_3d_max) +axes[1, 1].set_title("∂f/∂y (expected: exp(-x) * cos(y) * cos(z))") +plt.colorbar(im4, ax=axes[1, 1], shrink=0.62) + +# ∂f/∂z expected +im5 = axes[1, 2].imshow(df_dz_expected_3d_slice.cpu().numpy(), vmin=df_dz_3d_min, vmax=df_dz_3d_max) +axes[1, 2].set_title("∂f/∂z (expected: -exp(-x) * sin(y) * sin(z))") +plt.colorbar(im5, ax=axes[1, 2], shrink=0.62) + +plt.tight_layout() +plt.show() + +# %% +# .. raw:: html +# +#
+# +# Test 3D gradient computation +# ----------------------------- +# Compute gradient of the 3D scalar field +gradient_3d = fd3d.gradient(f_3d) # Returns [df_dx, df_dy, df_dz] + +# Plot gradient components at z-slice +fig, axes = plt.subplots(2, 3, figsize=(18, 12)) +fig.suptitle(f"3D Gradient Components: ∇f = [∂f/∂x, ∂f/∂y, ∂f/∂z] at z = {z_slice_val:.2f}") + +# ∂f/∂x from gradient +im0 = axes[0, 0].imshow(gradient_3d[0][:, :, z_slice_idx].cpu().numpy(), vmin=df_dx_3d_min, vmax=df_dx_3d_max) +axes[0, 0].set_title("∂f/∂x from gradient") +plt.colorbar(im0, ax=axes[0, 0], shrink=0.62) + +# ∂f/∂y from gradient +im1 = axes[0, 1].imshow(gradient_3d[1][:, :, z_slice_idx].cpu().numpy(), vmin=df_dy_3d_min, vmax=df_dy_3d_max) +axes[0, 1].set_title("∂f/∂y from gradient") +plt.colorbar(im1, ax=axes[0, 1], shrink=0.62) + +# ∂f/∂z from gradient +im2 = axes[0, 2].imshow(gradient_3d[2][:, :, z_slice_idx].cpu().numpy(), vmin=df_dz_3d_min, vmax=df_dz_3d_max) +axes[0, 2].set_title("∂f/∂z from gradient") +plt.colorbar(im2, ax=axes[0, 2], shrink=0.62) + +# Reference gradient components (expected values) +im3 = axes[1, 0].imshow(df_dx_expected_3d_slice.cpu().numpy(), vmin=df_dx_3d_min, vmax=df_dx_3d_max) +axes[1, 0].set_title("∂f/∂x (expected)") +plt.colorbar(im3, ax=axes[1, 0], shrink=0.62) + +im4 = axes[1, 1].imshow(df_dy_expected_3d_slice.cpu().numpy(), vmin=df_dy_3d_min, vmax=df_dy_3d_max) +axes[1, 1].set_title("∂f/∂y (expected)") +plt.colorbar(im4, ax=axes[1, 1], shrink=0.62) + +im5 = axes[1, 2].imshow(df_dz_expected_3d_slice.cpu().numpy(), vmin=df_dz_3d_min, vmax=df_dz_3d_max) +axes[1, 2].set_title("∂f/∂z (expected)") +plt.colorbar(im5, ax=axes[1, 2], shrink=0.62) + +plt.tight_layout() +plt.show() + +# %% +# .. raw:: html +# +#
+# +# Test 3D vector field operations +# -------------------------------- +# Create a 3D vector field: u = [exp(-x), sin(y), cos(z)] +u1_3d = torch.exp(-X) +u2_3d = torch.sin(Y) +u3_3d = torch.cos(Z) +u_vector_3d = torch.stack([u1_3d, u2_3d, u3_3d], dim=0) + +# Compute divergence +divergence_3d = fd3d.divergence(u_vector_3d) + +# Expected analytical results +# ∇·u = ∂u₁/∂x + ∂u₂/∂y + ∂u₃/∂z +divergence_3d_expected = -torch.exp(-X) + torch.cos(Y) - torch.sin(Z) + +# %% +# .. raw:: html +# +#
+# +# Plot 3D vector field operations at z-slice +# ------------------------------------------- +fig, axes = plt.subplots(2, 3, figsize=(18, 12)) +fig.suptitle(f"3D Vector Field Operations: u = [exp(-x), sin(y), cos(z)] at z = {z_slice_val:.2f}") + +# Compute consistent colorbar limits for vector field components at z-slice +u1_3d_slice = u1_3d[:, :, z_slice_idx] +u2_3d_slice = u2_3d[:, :, z_slice_idx] +u3_3d_slice = u3_3d[:, :, z_slice_idx] + +u1_3d_min = min(u1_3d_slice.min().item(), u1_3d_slice.max().item()) +u1_3d_max = max(u1_3d_slice.min().item(), u1_3d_slice.max().item()) +u2_3d_min = min(u2_3d_slice.min().item(), u2_3d_slice.max().item()) +u2_3d_max = max(u2_3d_slice.min().item(), u2_3d_slice.max().item()) +u3_3d_min = min(u3_3d_slice.min().item(), u3_3d_slice.max().item()) +u3_3d_max = max(u3_3d_slice.min().item(), u3_3d_slice.max().item()) + +# Compute consistent colorbar limits for divergence at z-slice +div_3d_slice = divergence_3d[:, :, z_slice_idx] +div_3d_expected_slice = divergence_3d_expected[:, :, z_slice_idx] +div_3d_min = min(div_3d_slice.min().item(), div_3d_expected_slice.min().item()) +div_3d_max = max(div_3d_slice.max().item(), div_3d_expected_slice.max().item()) + +# Vector field components +im0 = axes[0, 0].imshow(u1_3d_slice.cpu().numpy(), vmin=u1_3d_min, vmax=u1_3d_max) +axes[0, 0].set_title("u₁ = exp(-x)") +plt.colorbar(im0, ax=axes[0, 0], shrink=0.62) + +im1 = axes[0, 1].imshow(u2_3d_slice.cpu().numpy(), vmin=u2_3d_min, vmax=u2_3d_max) +axes[0, 1].set_title("u₂ = sin(y)") +plt.colorbar(im1, ax=axes[0, 1], shrink=0.62) + +im2 = axes[0, 2].imshow(u3_3d_slice.cpu().numpy(), vmin=u3_3d_min, vmax=u3_3d_max) +axes[0, 2].set_title("u₃ = cos(z)") +plt.colorbar(im2, ax=axes[0, 2], shrink=0.62) + +# Divergence +im3 = axes[1, 0].imshow(div_3d_slice.cpu().numpy(), vmin=div_3d_min, vmax=div_3d_max) +axes[1, 0].set_title("∇·u (computed)") +plt.colorbar(im3, ax=axes[1, 0], shrink=0.62) + +# Divergence expected +im4 = axes[1, 1].imshow(div_3d_expected_slice.cpu().numpy(), vmin=div_3d_min, vmax=div_3d_max) +axes[1, 1].set_title("∇·u (expected: -exp(-x) + cos(y) - sin(z))") +plt.colorbar(im4, ax=axes[1, 1], shrink=0.62) + +# Empty plot for symmetry +axes[1, 2].set_visible(False) + +plt.tight_layout() +plt.show() diff --git a/sources/neuraloperator/examples/layers/plot_fourier_continuation.py b/sources/neuraloperator/examples/layers/plot_fourier_continuation.py new file mode 100644 index 0000000000000000000000000000000000000000..5a7e9befb38a27ac7b131d7cae5c97cbb1b3dfb7 --- /dev/null +++ b/sources/neuraloperator/examples/layers/plot_fourier_continuation.py @@ -0,0 +1,418 @@ +""" +.. _fourier_continuation : + +Fourier Continuation +==================== + +This tutorial demonstrates Fourier continuation methods for extending non-periodic +functions to periodic ones, enabling efficient spectral analysis and neural operator +applications. Fourier continuation is crucial for: + +- Converting non-periodic data to periodic form +- Enabling spectral methods on arbitrary domains +- Improving convergence of Fourier-based neural operators +- Handling boundary conditions in spectral computations + +The tutorial covers both FC-Legendre and FC-Gram methods for 1D, 2D, and 3D data. +""" + +# %% +# .. raw:: html +# +#
+# +# Import the library +# ------------------ +# We first import our `neuralop` library and required dependencies. +import torch +import matplotlib.pyplot as plt +from matplotlib.lines import Line2D +from neuralop.layers.fourier_continuation import FCLegendre, FCGram + + +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + +# %% +# .. raw:: html +# +#
+# +# Creating an example of 1D non-periodic function +# ---------------------------------------------- +# We consider f(x) = sin(16x) - cos(8x) on the interval [0,1]. +# This function is not periodic on [0,1], making it a good test case +# for Fourier continuation methods. + +length_signal = 101 # Length of the original 1D signal +add_pts = 50 # Number of additional points for continuation +batch_size = 3 # Batch size for processing multiple signals + +# Create the input signal +x = torch.linspace(0, 1, length_signal).repeat(batch_size, 1) +f = torch.sin(16 * x) - torch.cos(8 * x) + + +# %% +# .. raw:: html +# +#
+# +# Extending the signal +# ----------------------------------------- +# We use the FC-Legendre and FC-Gram Fourier continuation layers to extend the signal. + +# FC-Legendre: Uses Legendre polynomial basis for continuation +Extension_Legendre = FCLegendre(d=2, n_additional_pts=add_pts) +f_extend_Legendre = Extension_Legendre(f, dim=1) + +# FC-Gram: Uses Gram polynomial basis for continuation +Extension_Gram = FCGram(d=4, n_additional_pts=add_pts) +f_extend_Gram = Extension_Gram(f, dim=1) + + +# %% +# .. raw:: html +# +#
+# +# Visualizing the 1D Fourier continuation results +# ---------------------------------------------- +# We plot the original function and both continuation methods to compare +# their effectiveness in creating smooth periodic extensions. + +# Define the extended coordinates +x_extended = torch.linspace(-0.25, 1.25, 151) + +# Adjust the extended functions for visualization purposes +f_extend_Legendre_adjusted = f_extend_Legendre - 0.6 +f_extend_Gram_adjusted = f_extend_Gram + 0.6 + +plt.figure(figsize=(13, 6)) +plt.plot(x[0], f[0], "k", label="Original Function", lw=2.2) +plt.plot(x_extended, f_extend_Gram_adjusted[0], "b", label="FC-Gram Extension", lw=2.2) +plt.plot(x_extended, f_extend_Legendre_adjusted[0], "g", label="FC-Legendre Extension", lw=2.2) +plt.plot([0, 0], [-2.9, 1.9], "-", color="gray", lw=1.5) +plt.plot([1, 1], [-2.9, 1.1], "-", color="gray", lw=1.5) +plt.plot([-0.25, 1.25], [f_extend_Legendre_adjusted[0, 0], f_extend_Legendre_adjusted[0, 0]], "--", color="g", lw=1.6) +plt.plot([-0.25, 1.25], [f_extend_Gram_adjusted[0, 0], f_extend_Gram_adjusted[0, 0]], "--", color="b", lw=1.6) +legend_elements = [ + Line2D([0], [0], color="k", lw=2.2, label="Original Function"), + Line2D([0], [0], color="b", lw=2.2, label="FC-Gram Extension"), + Line2D([0], [0], color="g", lw=2.2, label="FC-Legendre Extension"), +] +legend = plt.legend(handles=legend_elements, fontsize=19) +plt.xlim([-0.28, 1.31]) +plt.ylim([-3.1, 2.6]) +ax = plt.gca() +ax.spines["top"].set_visible(False) +ax.spines["right"].set_visible(False) +ax.tick_params(axis="x", which="major", labelsize=19) +ax.tick_params(axis="y", which="major", labelsize=19) +plt.xticks([-0.25, 0, 1, 1.25], ["-0.25", "0", "1", "1.25"]) +plt.yticks([-2, 2]) +plt.tight_layout() +plt.show() + +# %% +# .. raw:: html +# +#
+# +# Creating an example of 2D non-periodic function +# ------------------------------------------------ +# We consider f(x,y) = sin(12x) - cos(14y) + 3xy on the domain [0,1]×[0,1]. +# This function is not periodic on the unit square, making it suitable +# for testing 2D Fourier continuation methods. + +length_signal = 101 # Length of the signal in each dimension +add_pts = 50 # Number of additional points for continuation in each dimension +batch_size = 3 # Batch size for processing multiple signals + +# Create the 2D coordinate grids +x = torch.linspace(0, 1, length_signal).view(1, length_signal, 1).repeat(batch_size, 1, length_signal) +y = torch.linspace(0, 1, length_signal).view(1, 1, length_signal).repeat(batch_size, length_signal, 1) + +# Define the 2D test function +f = torch.sin(12 * x) - torch.cos(14 * y) + 3 * x * y + + +# %% +# .. raw:: html +# +#
+# +# Extending the signal +# ----------------------------------------- +# We use the FC-Legendre and FC-Gram Fourier continuation layers to extend the signal. + +# FC-Legendre: Uses Legendre polynomial basis for 2D continuation +Extension_Legendre = FCLegendre(d=3, n_additional_pts=add_pts) +f_extend_Legendre = Extension_Legendre(f, dim=2) + +# FC-Gram: Uses Gram polynomial basis for 2D continuation +Extension_Gram = FCGram(d=3, n_additional_pts=add_pts) +f_extend_Gram = Extension_Gram(f, dim=2) + + +# %% +# .. raw:: html +# +#
+# +# Visualizing the 2D Fourier continuation results +# ---------------------------------------------- +# We plot the original function and both continuation methods to compare +# their effectiveness in creating smooth 2D periodic extensions. +# Black lines delineate the original domain boundaries. + +fig, axs = plt.subplots(figsize=(15, 5), nrows=1, ncols=3) + +# Plot the original function +axs[0].imshow(f[0]) +axs[0].set_title(r"Original Function", fontsize=15.5) +axs[1].imshow(f_extend_Legendre[0]) +axs[1].plot([add_pts//2, length_signal + add_pts//2], [add_pts//2, add_pts//2], "-", color="k", lw=3) +axs[1].plot([add_pts//2, add_pts//2], [add_pts//2, length_signal + add_pts//2], "-", color="k", lw=3) +axs[1].plot([add_pts//2, length_signal + add_pts//2], [length_signal + add_pts//2, length_signal + add_pts//2], "-", color="k", lw=3) +axs[1].plot([length_signal + add_pts//2, length_signal + add_pts//2], [add_pts//2, length_signal + add_pts//2], "-", color="k", lw=3) +axs[1].set_title(r"FC-Legendre Extension", fontsize=15.5) +axs[2].imshow(f_extend_Gram[0]) +axs[2].plot([add_pts//2, length_signal + add_pts//2], [add_pts//2, add_pts//2], "-", color="k", lw=3) +axs[2].plot([add_pts//2, add_pts//2], [add_pts//2, length_signal + add_pts//2], "-", color="k", lw=3) +axs[2].plot([add_pts//2, length_signal + add_pts//2], [length_signal + add_pts//2, length_signal + add_pts//2], "-", color="k", lw=3) +axs[2].plot([length_signal + add_pts//2, length_signal + add_pts//2], [add_pts//2, length_signal + add_pts//2], "-", color="k", lw=3) +axs[2].set_title(r"FC-Gram Extension", fontsize=15.5) +for ax in axs.flat: + ax.set_xticks([]) + ax.set_yticks([]) +plt.subplots_adjust(wspace=0.05) # Reduce white space between plots +plt.show() + + +# %% +# .. raw:: html +# +#
+# +# Creating an example of a 3D function +# -------------------- +# Here we consider f(x,y,z) = exp(-2z) + 2xz + sin(12xy) + y sin(10yz) +# which is not periodic on [0,1]x[0,1]x[0,1] + +batch_size = 2 +length_signal = 101 +add_pts = 50 + +# Create 3D grid +x = torch.linspace(0, 1, length_signal).view(1, length_signal, 1, 1).repeat(batch_size, 1, length_signal, length_signal) +y = torch.linspace(0, 1, length_signal).view(1, 1, length_signal, 1).repeat(batch_size, length_signal, 1, length_signal) +z = torch.linspace(0, 1, length_signal).view(1, 1, 1, length_signal).repeat(batch_size, length_signal, length_signal, 1) + +# Create 3D function +f = torch.exp(-2 * z) + 2 * z * x + torch.sin(12 * x * y) + y * torch.sin(10 * y * z) + + +# %% +# .. raw:: html +# +#
+# +# Extending the signal +# ----------------------------------------- +# We use the FC-Legendre and FC-Gram Fourier continuation layers to extend the signal. + +Extension_Legendre = FCLegendre(d=3, n_additional_pts=add_pts) +f_extend_Legendre = Extension_Legendre(f, dim=3) + +Extension_Gram = FCGram(d=3, n_additional_pts=add_pts) +f_extend_Gram = Extension_Gram(f, dim=3) + + +# %% +# .. raw:: html +# +#
+# +# Plot the FC-Legendre and FC-Gram results for 3D +# ---------------------- +# We also add white lines to deliminate the original signal + +f_min = f.min().item() +f_max = f.max().item() +f_ext_legendre_min = f_extend_Legendre.min().item() +f_ext_legendre_max = f_extend_Legendre.max().item() +f_ext_gram_min = f_extend_Gram.min().item() +f_ext_gram_max = f_extend_Gram.max().item() +global_min = min(f_min, f_ext_legendre_min, f_ext_gram_min) +global_max = max(f_max, f_ext_legendre_max, f_ext_gram_max) + + +# %% +# .. raw:: html +# +#
+# +# Figure for X slices +fig = plt.figure(figsize=(24, 20)) +slice_indices = [length_signal//4, length_signal//2, 3*length_signal//4] +slice_names = ["First Quarter", "Middle", "Third Quarter"] + +for i, (idx, name) in enumerate(zip(slice_indices, slice_names)): + # Original function - X-slice + ax = fig.add_subplot(3, 3, i + 1) + im = ax.imshow(f[0, idx, :, :].numpy(), cmap="viridis", aspect="auto", vmin=global_min, vmax=global_max) + ax.set_title(f"Original: X-slice {name}", fontsize=22, fontweight="bold") + ax.set_xlabel("Y", fontsize=20) + ax.set_ylabel("Z", fontsize=20) + ax.set_xticks([]) + ax.set_yticks([]) + cbar = plt.colorbar(im, ax=ax) + cbar.ax.tick_params(labelsize=18) + + # FC-Legendre extension - X-slice + ax = fig.add_subplot(3, 3, i + 4) + ext_idx = idx + add_pts//2 + im = ax.imshow(f_extend_Legendre[0, ext_idx, :, :].numpy(), cmap="viridis", aspect="auto", vmin=global_min, vmax=global_max) + ax.set_title(f"FC-Legendre: X-slice {name}", fontsize=22, fontweight="bold") + ax.set_xlabel("Y", fontsize=20) + ax.set_ylabel("Z", fontsize=20) + # Draw boundary lines + ax.axhline(y=add_pts//2, color="white", linewidth=2, linestyle="-") + ax.axhline(y=length_signal + add_pts//2, color="white", linewidth=2, linestyle="-") + ax.axvline(x=add_pts//2, color="white", linewidth=2, linestyle="-") + ax.axvline(x=length_signal + add_pts//2, color="white", linewidth=2, linestyle="-") + ax.set_xticks([]) + ax.set_yticks([]) + cbar = plt.colorbar(im, ax=ax) + cbar.ax.tick_params(labelsize=18) + + # FC-Gram extension - X-slice + ax = fig.add_subplot(3, 3, i + 7) + im = ax.imshow(f_extend_Gram[0, ext_idx, :, :].numpy(), cmap="viridis", aspect="auto", vmin=global_min, vmax=global_max) + ax.set_title(f"FC-Gram: X-slice {name}", fontsize=22, fontweight="bold") + ax.set_xlabel("Y", fontsize=20) + ax.set_ylabel("Z", fontsize=20) + # Draw boundary lines + ax.axhline(y=add_pts//2, color="white", linewidth=2, linestyle="-") + ax.axhline(y=length_signal + add_pts//2, color="white", linewidth=2, linestyle="-") + ax.axvline(x=add_pts//2, color="white", linewidth=2, linestyle="-") + ax.axvline(x=length_signal + add_pts//2, color="white", linewidth=2, linestyle="-") + ax.set_xticks([]) + ax.set_yticks([]) + cbar = plt.colorbar(im, ax=ax) + cbar.ax.tick_params(labelsize=18) + +plt.subplots_adjust(hspace=0.15, wspace=0.05, top=0.95) +plt.show() + +# %% +# .. raw:: html +# +#
+# +# Figure for Y-slices +fig2 = plt.figure(figsize=(24, 20)) + +for i, (idx, name) in enumerate(zip(slice_indices, slice_names)): + # Original function - Y-slice + ax = fig2.add_subplot(3, 3, i + 1) + im = ax.imshow(f[0, :, idx, :].numpy(), cmap="viridis", aspect="auto", vmin=global_min, vmax=global_max) + ax.set_title(f"Original: Y-slice {name}", fontsize=22, fontweight="bold") + ax.set_xlabel("X", fontsize=20) + ax.set_ylabel("Z", fontsize=20) + ax.set_xticks([]) + ax.set_yticks([]) + cbar = plt.colorbar(im, ax=ax) + cbar.ax.tick_params(labelsize=18) + + # FC-Legendre extension - Y-slice + ax = fig2.add_subplot(3, 3, i + 4) + ext_idx = idx + add_pts//2 + im = ax.imshow(f_extend_Legendre[0, :, ext_idx, :].numpy(), cmap="viridis", aspect="auto", vmin=global_min, vmax=global_max) + ax.set_title(f"FC-Legendre: Y-slice {name}", fontsize=22, fontweight="bold") + ax.set_xlabel("X", fontsize=20) + ax.set_ylabel("Z", fontsize=20) + # Draw boundary lines + ax.axhline(y=add_pts//2, color="white", linewidth=2, linestyle="-") + ax.axhline(y=length_signal + add_pts//2, color="white", linewidth=2, linestyle="-") + ax.axvline(x=add_pts//2, color="white", linewidth=2, linestyle="-") + ax.axvline(x=length_signal + add_pts//2, color="white", linewidth=2, linestyle="-") + ax.set_xticks([]) + ax.set_yticks([]) + cbar = plt.colorbar(im, ax=ax) + cbar.ax.tick_params(labelsize=18) + + # FC-Gram extension - Y-slice + ax = fig2.add_subplot(3, 3, i + 7) + im = ax.imshow(f_extend_Gram[0, :, ext_idx, :].numpy(), cmap="viridis", aspect="auto", vmin=global_min, vmax=global_max) + ax.set_title(f"FC-Gram: Y-slice {name}", fontsize=22, fontweight="bold") + ax.set_xlabel("X", fontsize=20) + ax.set_ylabel("Z", fontsize=20) + # Draw boundary lines + ax.axhline(y=add_pts//2, color="white", linewidth=2, linestyle="-") + ax.axhline(y=length_signal + add_pts//2, color="white", linewidth=2, linestyle="-") + ax.axvline(x=add_pts//2, color="white", linewidth=2, linestyle="-") + ax.axvline(x=length_signal + add_pts//2, color="white", linewidth=2, linestyle="-") + ax.set_xticks([]) + ax.set_yticks([]) + cbar = plt.colorbar(im, ax=ax) + cbar.ax.tick_params(labelsize=18) + +plt.subplots_adjust(hspace=0.15, wspace=0.05, top=0.95) +plt.show() + +# %% +# .. raw:: html +# +#
+# +# Figure for Z-slices +fig3 = plt.figure(figsize=(24, 20)) + +for i, (idx, name) in enumerate(zip(slice_indices, slice_names)): + # Original function - Z-slice + ax = fig3.add_subplot(3, 3, i + 1) + im = ax.imshow(f[0, :, :, idx].numpy(), cmap="viridis", aspect="auto", vmin=global_min, vmax=global_max) + ax.set_title(f"Original: Z-slice {name}", fontsize=22, fontweight="bold") + ax.set_xlabel("X", fontsize=20) + ax.set_ylabel("Y", fontsize=20) + ax.set_xticks([]) + ax.set_yticks([]) + cbar = plt.colorbar(im, ax=ax) + cbar.ax.tick_params(labelsize=18) + + # FC-Legendre extension - Z-slice + ax = fig3.add_subplot(3, 3, i + 4) + ext_idx = idx + add_pts//2 + im = ax.imshow(f_extend_Legendre[0, :, :, ext_idx].numpy(), cmap="viridis", aspect="auto", vmin=global_min, vmax=global_max) + ax.set_title(f"FC-Legendre: Z-slice {name}", fontsize=22, fontweight="bold") + ax.set_xlabel("X", fontsize=20) + ax.set_ylabel("Y", fontsize=20) + # Draw boundary lines + ax.axhline(y=add_pts//2, color="white", linewidth=2, linestyle="-") + ax.axhline(y=length_signal + add_pts//2, color="white", linewidth=2, linestyle="-") + ax.axvline(x=add_pts//2, color="white", linewidth=2, linestyle="-") + ax.axvline(x=length_signal + add_pts//2, color="white", linewidth=2, linestyle="-") + ax.set_xticks([]) + ax.set_yticks([]) + cbar = plt.colorbar(im, ax=ax) + cbar.ax.tick_params(labelsize=18) + + # FC-Gram extension - Z-slice + ax = fig3.add_subplot(3, 3, i + 7) + im = ax.imshow(f_extend_Gram[0, :, :, ext_idx].numpy(), cmap="viridis", aspect="auto", vmin=global_min, vmax=global_max) + ax.set_title(f"FC-Gram: Z-slice {name}", fontsize=22, fontweight="bold") + ax.set_xlabel("X", fontsize=20) + ax.set_ylabel("Y", fontsize=20) + # Draw boundary lines + ax.axhline(y=add_pts//2, color="white", linewidth=2, linestyle="-") + ax.axhline(y=length_signal + add_pts//2, color="white", linewidth=2, linestyle="-") + ax.axvline(x=add_pts//2, color="white", linewidth=2, linestyle="-") + ax.axvline(x=length_signal + add_pts//2, color="white", linewidth=2, linestyle="-") + ax.set_xticks([]) + ax.set_yticks([]) + cbar = plt.colorbar(im, ax=ax) + cbar.ax.tick_params(labelsize=18) + +plt.subplots_adjust(hspace=0.15, wspace=0.05, top=0.95) +plt.show() diff --git a/sources/neuraloperator/examples/layers/plot_fourier_diff.py b/sources/neuraloperator/examples/layers/plot_fourier_diff.py new file mode 100644 index 0000000000000000000000000000000000000000..984bca67e3ea90803af398cc132ea62d561af6e2 --- /dev/null +++ b/sources/neuraloperator/examples/layers/plot_fourier_diff.py @@ -0,0 +1,358 @@ +""" +.. _fourier_diff : + +Fourier Differentiation +====================== + +This tutorial demonstrates Fourier-based differentiation methods for computing +derivatives of periodic functions. Fourier differentiation is crucial for: + +- Computing derivatives of functions with spectral accuracy +- Implementing physics-informed loss functions + +The `FourierDiff` class provides efficient implementations of spectral +differentiation for periodic functions in 1D, 2D, and 3D domains. +""" + +# %% +# .. raw:: html +# +#
+# +# Import the library +# ------------------ +# We first import our `neuralop` library and required dependencies. +import torch +import numpy as np +import matplotlib.pyplot as plt +from neuralop.losses.differentiation import FourierDiff + +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + + +# %% +# .. raw:: html +# +#
+# +# Creating an example of periodic 1D curve +# ---------------------------------------- +# Here we consider sin(x) and cos(x), which are periodic on the interval [0, 2π] +L = 2 * torch.pi +x = torch.linspace(0, L, 101)[:-1] +f = torch.stack([torch.sin(x), torch.cos(x)], dim=0) +x_np = x.cpu().numpy() + +# %% +# .. raw:: html +# +#
+# +# Differentiate the signal +# ----------------------------------------- +# We use the FourierDiff class to differentiate the signal +fd1d = FourierDiff(dim=1, L=L, use_fc=False) +derivatives = fd1d.compute_multiple_derivatives(f, [1, 2, 3]) +dfdx, df2dx2, df3dx3 = derivatives + + +# %% +# .. raw:: html +# +#
+# +# Plot the results for sin(x) +# --------------------------- +plt.figure() +plt.plot(x_np, dfdx[0].squeeze().cpu().numpy(), label="Fourier dfdx") +plt.plot(x_np, np.cos(x_np), "--", label="dfdx") +plt.plot(x_np, df2dx2[0].squeeze().cpu().numpy(), label="Fourier df2dx2") +plt.plot(x_np, -np.sin(x_np), "--", label="df2dx2") +plt.plot(x_np, df3dx3[0].squeeze().cpu().numpy(), label="Fourier df3dx3") +plt.plot(x_np, -np.cos(x_np), "--", label="df3dx3") +plt.xlabel("x") +plt.legend() +plt.show() + +# %% +# .. raw:: html +# +#
+# +# Plot the results for cos(x) +# --------------------------- +plt.figure() +plt.plot(x_np, dfdx[1].squeeze().cpu().numpy(), label="Fourier dfdx") +plt.plot(x_np, -np.sin(x_np), "--", label="dfdx") +plt.plot(x_np, df2dx2[1].squeeze().cpu().numpy(), label="Fourier df2dx2") +plt.plot(x_np, -np.cos(x_np), "--", label="df2dx2") +plt.plot(x_np, df3dx3[1].squeeze().cpu().numpy(), label="Fourier df3dx3") +plt.plot(x_np, np.sin(x_np), "--", label="df3dx3") +plt.xlabel("x") +plt.legend() +plt.show() + + +# %% +# .. raw:: html +# +#
+# +# Creating an example of non-periodic 1D curve +# ------------------------------------------- +# Here we consider sin(3x)-cos(x) and exp(-0.8x)+sin(x) +L = 2 * torch.pi +x = torch.linspace(0, L, 101)[:-1] +f = torch.stack( + [torch.sin(3 * x) - torch.cos(x), torch.exp(-0.8 * x) + torch.sin(x)], dim=0 +) +x_np = x.cpu().numpy() + +# %% +# .. raw:: html +# +#
+# +# Differentiate the signal +# ----------------------------------------- +# We use the FourierDiff class with Fourier continuation to differentiate the signal +fd1d = FourierDiff(dim=1, L=L, use_fc="Legendre", fc_degree=4, fc_n_additional_pts=50) +derivatives = fd1d.compute_multiple_derivatives(f, [1, 2]) +dfdx, df2dx2 = derivatives + + +# %% +# .. raw:: html +# +#
+# +# Plot the results for sin(3x)-cos(x) +# -------------------------------------- +plt.figure() +plt.plot(x_np, dfdx[0].squeeze().cpu().numpy(), label="Fourier dfdx") +plt.plot(x_np, 3 * torch.cos(3 * x) + torch.sin(x), "--", label="dfdx") +plt.plot(x_np, df2dx2[0].squeeze().cpu().numpy(), label="Fourier df2dx2") +plt.plot(x_np, -9 * torch.sin(3 * x) + torch.cos(x), "--", label="df2dx2") +plt.xlabel("x") +plt.legend() +plt.show() + +# %% +# .. raw:: html +# +#
+# +# Plot the results for exp(-0.8x)+sin(x) +# --------------------------------------- +plt.figure() +plt.plot(x_np, dfdx[1].squeeze().cpu().numpy(), label="Fourier dfdx") +plt.plot(x_np, -0.8 * torch.exp(-0.8 * x) + torch.cos(x), "--", label="dfdx") +plt.plot(x_np, df2dx2[1].squeeze().cpu().numpy(), label="Fourier df2dx2") +plt.plot(x_np, 0.64 * torch.exp(-0.8 * x) - torch.sin(x), "--", label="df2dx2") +plt.xlabel("x") +plt.legend() +plt.show() + + +# %% +# .. raw:: html +# +#
+# +# 2D Fourier Differentiation Examples +# =================================== +# Here we demonstrate the FourierDiff class for 2D functions + +# %% +# .. raw:: html +# +#
+# +# Creating an example of periodic 2D function +# ----------------------------------------- +# Here we consider f(x,y) = sin(x) * cos(y), which is periodic on the interval [0, 2π] × [0, 2π] +L_x, L_y = 2 * torch.pi, 2 * torch.pi +nx, ny = 180, 186 +x = torch.linspace(0, L_x, nx, dtype=torch.float64) +y = torch.linspace(0, L_y, ny, dtype=torch.float64) +X, Y = torch.meshgrid(x, y, indexing="ij") + +# Test function: f(x,y) = sin(x) * cos(y) +f_2d = torch.sin(X) * torch.cos(Y) + +# %% +# .. raw:: html +# +#
+# +# Differentiate the 2D signal +# ----------------------------------------- +# We use the FourierDiff class to compute derivatives +fd2d = FourierDiff(dim=2, L=(L_x, L_y)) + +# Compute derivatives +df_dx = fd2d.dx(f_2d) +df_dy = fd2d.dy(f_2d) +laplacian = fd2d.laplacian(f_2d) + +# Expected analytical results for f(x,y) = sin(x) * cos(y) +df_dx_expected = torch.cos(X) * torch.cos(Y) +df_dy_expected = -torch.sin(X) * torch.sin(Y) +laplacian_expected = -2 * torch.sin(X) * torch.cos(Y) + +# %% +# .. raw:: html +# +#
+# +# Plot the 2D results +# ---------------------- +fig, axes = plt.subplots(2, 3, figsize=(15, 10)) +fig.suptitle("2D Fourier Differentiation Results: f(x,y) = sin(x) * cos(y)") + +# Compute consistent colorbar limits for each derivative pair +df_dx_min = min(df_dx.min().item(), df_dx_expected.min().item()) +df_dx_max = max(df_dx.max().item(), df_dx_expected.max().item()) +df_dy_min = min(df_dy.min().item(), df_dy_expected.min().item()) +df_dy_max = max(df_dy.max().item(), df_dy_expected.max().item()) + +# Original function +im0 = axes[0, 0].imshow(f_2d.cpu().numpy()) +axes[0, 0].set_title("Original: sin(x) * cos(y)") +plt.colorbar(im0, ax=axes[0, 0], shrink=0.57) + +# ∂f/∂x computed +im1 = axes[0, 1].imshow(df_dx.cpu().numpy(), vmin=df_dx_min, vmax=df_dx_max) +axes[0, 1].set_title("∂f/∂x (computed)") +plt.colorbar(im1, ax=axes[0, 1], shrink=0.57) + +# ∂f/∂x expected +im2 = axes[0, 2].imshow(df_dx_expected.cpu().numpy(), vmin=df_dx_min, vmax=df_dx_max) +axes[0, 2].set_title("∂f/∂x (expected: cos(x) * cos(y))") +plt.colorbar(im2, ax=axes[0, 2], shrink=0.57) + +# ∂f/∂y computed +im3 = axes[1, 0].imshow(df_dy.cpu().numpy(), vmin=df_dy_min, vmax=df_dy_max) +axes[1, 0].set_title("∂f/∂y (computed)") +plt.colorbar(im3, ax=axes[1, 0], shrink=0.57) + +# ∂f/∂y expected +im4 = axes[1, 1].imshow(df_dy_expected.cpu().numpy(), vmin=df_dy_min, vmax=df_dy_max) +axes[1, 1].set_title("∂f/∂y (expected: -sin(x) * sin(y))") +plt.colorbar(im4, ax=axes[1, 1], shrink=0.57) + +# Laplacian +im5 = axes[1, 2].imshow(laplacian.cpu().numpy()) +axes[1, 2].set_title("∇²f (computed)") +plt.colorbar(im5, ax=axes[1, 2], shrink=0.57) + +plt.tight_layout() +plt.show() + + +# %% +# .. raw:: html +# +#
+# +# 3D Fourier Differentiation Examples +# =================================== +# Here we demonstrate the FourierDiff class for 3D functions + +# %% +# .. raw:: html +# +#
+# +# Creating an example of periodic 3D function +# ----------------------------------------- +# Here we consider f(x,y,z) = sin(x) * cos(y) * sin(z), which is periodic on [0, 2π]³ +L_x, L_y, L_z = 2 * torch.pi, 2 * torch.pi, 2 * torch.pi +nx, ny, nz = 176, 180, 192 +x = torch.linspace(0, L_x, nx, dtype=torch.float64) +y = torch.linspace(0, L_y, ny, dtype=torch.float64) +z = torch.linspace(0, L_z, nz, dtype=torch.float64) +X, Y, Z = torch.meshgrid(x, y, z, indexing="ij") + +# Test function: f(x,y,z) = sin(x) * cos(y) * sin(z) +f_3d = torch.sin(X) * torch.cos(Y) * torch.sin(Z) + +# Alternative: create tensor directly like in the test +f_3d_alt = torch.randn(nx, ny, nz, dtype=torch.float64) + +# %% +# .. raw:: html +# +#
+# +# Differentiate the 3D signal +# ----------------------------------------- +# We use the FourierDiff class to compute derivatives +fd3d = FourierDiff(dim=3, L=(L_x, L_y, L_z)) + +# Compute derivatives +df_dx_3d = fd3d.dx(f_3d) +df_dy_3d = fd3d.dy(f_3d) +df_dz_3d = fd3d.dz(f_3d) +laplacian_3d = fd3d.laplacian(f_3d) + +# Expected analytical results for f(x,y,z) = sin(x) * cos(y) * sin(z) +df_dx_expected_3d = torch.cos(X) * torch.cos(Y) * torch.sin(Z) +df_dy_expected_3d = -torch.sin(X) * torch.sin(Y) * torch.sin(Z) +df_dz_expected_3d = torch.sin(X) * torch.cos(Y) * torch.cos(Z) +laplacian_expected_3d = -3 * torch.sin(X) * torch.cos(Y) * torch.sin(Z) + +# %% +# .. raw:: html +# +#
+# +# Plot a slice of the 3D results (z=0 plane) +# ------------------------------------------ +z_slice_idx = nz // 2 +fig, axes = plt.subplots(2, 3, figsize=(18, 12)) +fig.suptitle("3D Fourier Differentiation Results (z=0 slice): f(x,y,z) = sin(x) * cos(y) * sin(z)") + +# Compute consistent colorbar limits for each derivative pair at the z-slice +df_dx_3d_slice = df_dx_3d[:, :, z_slice_idx] +df_dx_expected_3d_slice = df_dx_expected_3d[:, :, z_slice_idx] +df_dy_3d_slice = df_dy_3d[:, :, z_slice_idx] +df_dy_expected_3d_slice = df_dy_expected_3d[:, :, z_slice_idx] + +df_dx_3d_min = min(df_dx_3d_slice.min().item(), df_dx_expected_3d_slice.min().item()) +df_dx_3d_max = max(df_dx_3d_slice.max().item(), df_dx_expected_3d_slice.max().item()) +df_dy_3d_min = min(df_dy_3d_slice.min().item(), df_dy_expected_3d_slice.min().item()) +df_dy_3d_max = max(df_dy_3d_slice.max().item(), df_dy_expected_3d_slice.max().item()) + +# Original function slice +im0 = axes[0, 0].imshow(f_3d[:, :, z_slice_idx].cpu().numpy()) +axes[0, 0].set_title("Original: sin(x) * cos(y) * sin(z)") +plt.colorbar(im0, ax=axes[0, 0], shrink=0.57) + +# ∂f/∂x slice +im1 = axes[0, 1].imshow(df_dx_3d_slice.cpu().numpy(), vmin=df_dx_3d_min, vmax=df_dx_3d_max) +axes[0, 1].set_title("∂f/∂x (computed)") +plt.colorbar(im1, ax=axes[0, 1], shrink=0.57) + +# ∂f/∂x expected slice +im2 = axes[0, 2].imshow(df_dx_expected_3d_slice.cpu().numpy(), vmin=df_dx_3d_min, vmax=df_dx_3d_max) +axes[0, 2].set_title("∂f/∂x (expected: cos(x) * cos(y) * sin(z))") +plt.colorbar(im2, ax=axes[0, 2], shrink=0.57) + +# ∂f/∂y slice +im3 = axes[1, 0].imshow(df_dy_3d_slice.cpu().numpy(), vmin=df_dy_3d_min, vmax=df_dy_3d_max) +axes[1, 0].set_title("∂f/∂y (computed)") +plt.colorbar(im3, ax=axes[1, 0], shrink=0.57) + +# ∂f/∂y expected slice +im4 = axes[1, 1].imshow(df_dy_expected_3d_slice.cpu().numpy(), vmin=df_dy_3d_min, vmax=df_dy_3d_max) +axes[1, 1].set_title("∂f/∂y (expected: -sin(x) * sin(y) * sin(z))") +plt.colorbar(im4, ax=axes[1, 1], shrink=0.57) + +# ∂f/∂z slice +im5 = axes[1, 2].imshow(df_dz_3d[:, :, z_slice_idx].cpu().numpy()) +axes[1, 2].set_title("∂f/∂z (computed)") +plt.colorbar(im5, ax=axes[1, 2], shrink=0.57) + +plt.tight_layout() +plt.show() diff --git a/sources/neuraloperator/examples/layers/plot_neighbor_search.py b/sources/neuraloperator/examples/layers/plot_neighbor_search.py new file mode 100644 index 0000000000000000000000000000000000000000..ab595692644a57f37b65a93c2e4964938d830569 --- /dev/null +++ b/sources/neuraloperator/examples/layers/plot_neighbor_search.py @@ -0,0 +1,137 @@ +""" +Neighbor Search for Graph Neural Operators +=========================================== + +This tutorial demonstrates neighbor search algorithms used in Graph Neural Operators (GNO). +Neighbor search is crucial for: + +- Finding spatial relationships in irregular point clouds +- Computing Nyström approximations of kernel integrals +- Enabling GNO to work with arbitrary point cloud data +- Implementing efficient spatial queries for neural operators + +The tutorial covers the `native_neighbor_search` function and its role in GNO architectures. + +""" + +# %% +# .. raw:: html +# +#
+# +# Import dependencies +# ------------------- +# We import the necessary modules for neighbor search and visualization + +import random +import matplotlib.pyplot as plt +import torch + +from neuralop.layers.gno_block import GNOBlock +from neuralop.layers.neighbor_search import native_neighbor_search +from neuralop.layers.embeddings import regular_grid_2d + +device = "cpu" + +# %% +# .. raw:: html +# +#
+# +# Understanding Graph Neural Operators and neighbor search +# -------------------------------------------------------- +# Many problems involve data collected over irregular point clouds. +# The Graph Neural Operator (GNO) is a neural operator architecture +# that learns mappings between functions evaluated on arbitrary point clouds. +# +# For input coordinates Y, input function f evaluated at all y ∈ Y, +# and output coordinates X, our goal is to map to function g evaluated at all x ∈ X. +# The GNO computes the Nyström approximation of a continuous kernel integral: +# ∫_{N_r(x)} f(y) k(x,y) dy +# +# The first step is neighbor search to find spatial relationships. + +# %% +# .. raw:: html +# +#
+# +# Setting up the point cloud data +# -------------------------------- +# We create a regular grid of input coordinates and random output query points +# to demonstrate the neighbor search functionality. + +# Create a regular 8x8 grid of input coordinates +input_coords = ( + torch.stack(regular_grid_2d(spatial_dims=(8, 8))).permute(1, 2, 0).view(-1, 2) +) + +# Generate random output query points +output_queries = torch.rand([50, 2]) + +# Visualize the input coordinates and query points +plt.scatter( + input_coords[:, 0], + input_coords[:, 1], + color="orange", + label="Input coordinates", + s=50, +) +plt.scatter( + output_queries[:, 0], + output_queries[:, 1], + color="blue", + label="Output queries", + s=30, +) +plt.legend() +plt.title("Input coordinates and output query points") +plt.xlabel("x") +plt.ylabel("y") +plt.show() + +# %% +# .. raw:: html +# +#
+# +# Performing neighbor search +# --------------------------- +# We select a query point and find all input coordinates within a specified radius. +# This demonstrates how the neighbor search algorithm identifies spatial relationships. + +query_index = 6 +query_point = output_queries[query_index] + +# Perform neighbor search with radius 0.25 +# Note: This radius is relatively large for our data density. +# In practice, we typically use values that find around 10 neighbors. +nbr_data = native_neighbor_search( + data=input_coords, queries=query_point.unsqueeze(0), radius=0.25 +) + +# %% +# .. raw:: html +# +#
+# +# Visualizing the neighbor search results +# -------------------------------------- +# We plot the query point, its neighbors, and the search radius to understand +# how the neighbor search algorithm works. + +fig, ax = plt.subplots() +neighbors = input_coords[nbr_data["neighbors_index"]] +ax.scatter( + input_coords[:, 0], input_coords[:, 1], color="blue", label="Input coordinates" +) +ax.scatter( + query_point[0], query_point[1], color="red", marker="*", s=200, label="Query point" +) +ax.scatter(neighbors[:, 0], neighbors[:, 1], color="green", label="Neighbors of query") +c = plt.Circle(query_point, radius=0.25, fill=False) +ax.add_patch(c) + +ax.legend() +ax.set_xlim(0, 1) +ax.set_ylim(0, 1) diff --git a/sources/neuraloperator/examples/layers/plot_normalization_layers.py b/sources/neuraloperator/examples/layers/plot_normalization_layers.py new file mode 100644 index 0000000000000000000000000000000000000000..674a671c98d3dc6cec64b123e65933abdbb00f95 --- /dev/null +++ b/sources/neuraloperator/examples/layers/plot_normalization_layers.py @@ -0,0 +1,229 @@ +""" +Normalization Layers +==================== + +This tutorial demonstrates normalization layers designed for neural operators. +Normalization is crucial for: + +- Stabilizing training dynamics +- Accelerating convergence +- Improving generalization +- Handling different data distributions + +The tutorial covers `InstanceNorm`, `BatchNorm`, and `AdaIN` layers, which are +dimension-agnostic and flexible for various neural operator architectures. + +""" + +# %% +# .. raw:: html +# +#
+# +# Import dependencies +# ------------------- +# We import the necessary modules for working with normalization layers + +import torch +import torch.nn as nn +import matplotlib.pyplot as plt +import numpy as np + +from neuralop.layers.normalization_layers import InstanceNorm, BatchNorm, AdaIN + +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + +# %% +# .. raw:: html +# +#
+# +# Understanding Normalization with 1D Functions +# --------------------------------------------- +# To clearly see how these layers work, we create a synthetic dataset of 1D functions. +# Our batch will consist of 10 functions. The first 5 will be sine waves with high amplitude and positive vertical shift, while the next 5 will be cosine waves with low amplitude and negative vertical shift. + +n_samples = 10 +n_points = 100 +x = torch.linspace(0, 2 * torch.pi, n_points) +data = torch.zeros((n_samples, 1, n_points)) + +# Generate two groups of functions with different characteristics +for i in range(n_samples): + if i < 5: + # Group 1: High amplitude sine waves with positive vertical shift + amplitude = np.random.uniform(2.0, 3.0) + shift = np.random.uniform(1.0, 2.0) + frequency = np.random.uniform(2.0, 3.0) + data[i, 0, :] = amplitude * torch.sin(frequency * x) + shift + else: + # Group 2: Low amplitude cosine waves with negative vertical shift + amplitude = np.random.uniform(0.5, 1.0) + shift = np.random.uniform(-2.0, -1.0) + frequency = np.random.uniform(1.0, 2.0) + data[i, 0, :] = amplitude * torch.cos(frequency * x) + shift + +# %% +# .. raw:: html +# +#
+# +# Visualizing the original data +# ------------------------------ +# We plot the synthetic functions to see their different statistical properties. +# The blue functions have high amplitude and positive shift, while the red functions +# have low amplitude and negative shift. + +plt.figure(figsize=(12, 6)) +plt.title("Original Data", fontsize=20) +for i in range(n_samples): + if i < 5: + plt.plot(x, data[i, 0, :], "b-", label="High Amplitude Functions with Positive Shift" if i == 0 else "") + else: + plt.plot(x, data[i, 0, :], "r-", label="Low Amplitude Functions with Negative Shift" if i == 5 else "") + +plt.legend(fontsize=20, loc="lower center", bbox_to_anchor=(0.5, -0.5), ncol=1) +plt.xlabel("$x$", fontsize=18) +plt.ylabel("$f(x)$", fontsize=18) +plt.xticks(fontsize=16) +plt.yticks(fontsize=16) +plt.locator_params(axis="y", nbins=5) +plt.grid(True, axis="y") +plt.subplots_adjust(bottom=0.2, top=0.9) +plt.tight_layout() +plt.show() + +# %% +# .. raw:: html +# +#
+# +# InstanceNorm +# ------------ +# `InstanceNorm` normalizes each sample in the batch **independently**. This means it rescales each of the 10 functions to have a mean of 0 and a standard deviation of 1, regardless of the other functions in the batch. This is useful when the statistical properties of each sample are distinct and should be treated separately. + +# Apply instance normalization +instance_norm = InstanceNorm() +data_in = instance_norm(data) + +plt.figure(figsize=(12, 6)) +plt.title("After InstanceNorm", fontsize=20) +for i in range(n_samples): + y_plot = data_in[i, 0, :].detach().numpy() + if i < 5: + plt.plot(x, y_plot, "b-", label="High Amplitude Functions with Positive Shift" if i == 0 else "") + else: + plt.plot(x, y_plot, "r-", label="Low Amplitude Functions with Negative Shift" if i == 5 else "") +plt.legend(fontsize=20, loc="lower center", bbox_to_anchor=(0.5, -0.5), ncol=1) +plt.xlabel("$x$", fontsize=18) +plt.ylabel("$f(x)$", fontsize=18) +plt.xticks(fontsize=16) +plt.yticks(fontsize=16) +plt.locator_params(axis="y", nbins=5) +plt.grid(True, axis="y") +plt.subplots_adjust(bottom=0.2, top=0.9) +plt.tight_layout() +plt.show() + +# %% +# .. raw:: html +# +#
+# +# Notice how all functions are now perfectly scaled to the same range, centered around zero. The original differences in amplitude and shift between the functions have been completely removed by instance-wise normalization. + +# %% +# .. raw:: html +# +#
+# +# BatchNorm +# --------- +# `BatchNorm` normalizes the data **across the entire batch**. It computes a single mean and standard deviation for all 10 functions combined and uses these values to normalize all the data. This is the most common form of normalization and is effective when batch statistics are a good approximation of the overall data distribution. + +# We need to specify the number of dimensions and features for BatchNorm +batch_norm = BatchNorm(n_dim=1, num_features=1) +data_bn = batch_norm(data) + +plt.figure(figsize=(12, 6)) +plt.title("After BatchNorm", fontsize=20) +for i in range(n_samples): + y_plot = data_bn[i, 0, :].detach().numpy() + if i < 5: + plt.plot(x, y_plot, "b-", label="High Amplitude Functions with Positive Shift" if i == 0 else "") + else: + plt.plot(x, y_plot, "r-", label="Low Amplitude Functions with Negative Shift" if i == 5 else "") +plt.legend(fontsize=20, loc="lower center", bbox_to_anchor=(0.5, -0.5), ncol=1) +plt.xlabel("$x$", fontsize=18) +plt.ylabel("$f(x)$", fontsize=18) +plt.xticks(fontsize=16) +plt.yticks(fontsize=16) +plt.locator_params(axis="y", nbins=5) +plt.grid(True, axis="y") +plt.subplots_adjust(bottom=0.2, top=0.9) +plt.tight_layout() +plt.show() + +# %% +# With `BatchNorm`, the relative differences between the two groups of functions are preserved. The high-amplitude functions are still visibly distinct from the low-amplitude ones, but the entire batch is now centered around a mean of zero with a standard deviation of one. +# + +# %% +# .. raw:: html +# +#
+# +# AdaIN (Adaptive Instance Normalization) +# --------------------------------------- +# `AdaIN` is a more advanced normalization that allows for "style transfer." It first normalizes an input (like `InstanceNorm`) and then applies a new style (a scaling `weight` and a shifting `bias`) derived from an external embedding vector. This is powerful for models where we want to control output characteristics based on a conditioning signal. +# +# To guarantee a clear and deterministic result for this tutorial, we define our own simple MLP. This MLP maps our chosen style embeddings directly to a desired `weight` and `bias`. + +content_function = torch.sin(2 * x).unsqueeze(0).unsqueeze(0) # (1, 1, 100) + + +# A simple, predictable MLP that maps an embedding directly to a (weight, bias) pair +class ToyMLP(nn.Module): + def forward(self, embedding): + return embedding + + +# Style 1: A simple change in amplitude and mean (weight=2.0, bias=1.0) +style_embedding_1 = torch.tensor([2.0, 1.0]) +# Style 2: A more complex change: inverting phase, shrinking, and shifting down (weight=-0.7, bias=-0.5) +style_embedding_2 = torch.tensor([-0.7, -0.5]) + +# The AdaIN layer needs to know the embedding dimension and number of input channels. +# We pass our toy MLP to have full control. +adain = AdaIN(embed_dim=2, in_channels=1, mlp=ToyMLP()) + +# Apply the first style +adain.set_embedding(style_embedding_1) +output_1 = adain(content_function) + +# Apply the second style +adain.set_embedding(style_embedding_2) +output_2 = adain(content_function) + +plt.figure(figsize=(12, 6)) +plt.title("AdaIN for Style Transfer", fontsize=20) +plt.plot(x, content_function.squeeze().numpy(), "k--", label="Content Function") +plt.plot(x, output_1.squeeze().detach().numpy(), "g-", label="Style 1: Increased Amplitude, Positive Shift") +plt.plot(x, output_2.squeeze().detach().numpy(), "m-", label="Style 2: Inverted, Shrunk, Negative Shift") +plt.legend(fontsize=20, loc="lower center", bbox_to_anchor=(0.5, -0.7), ncol=1) +plt.xlabel("$x$", fontsize=18) +plt.ylabel("$f(x)$", fontsize=18) +plt.xticks(fontsize=16) +plt.yticks(fontsize=16) +plt.locator_params(axis="y", nbins=5) +plt.grid(True, axis="y") +plt.subplots_adjust(bottom=0.35, top=0.9) +plt.tight_layout() +plt.show() + +# %% +# .. raw:: html +# +#
+# +# As you can see, the same content function is transformed into two very different outputs. **Style 1** produces a simple sinusoidal wave with larger amplitude and positive shift. **Style 2** produces a more complex transformation: the function is inverted (phase-shifted), its amplitude is reduced, and it's shifted downwards. This demonstrates how AdaIN can modulate network layer output in diverse ways based on the style embedding. diff --git a/sources/neuraloperator/examples/layers/plot_resample.py b/sources/neuraloperator/examples/layers/plot_resample.py new file mode 100644 index 0000000000000000000000000000000000000000..55fb014401ad1396729ced1d7ab25427471db611 --- /dev/null +++ b/sources/neuraloperator/examples/layers/plot_resample.py @@ -0,0 +1,152 @@ +""" +Resampling layers +================= + +When working with neural operators, we often need to change the resolution of our data. +For some architectures, like the FNO, this is handled automatically due to the +resolution-invariant nature of the Fourier domain. + +However, for other architectures, like the U-Net, we need to explicitly upsample and downsample +the data as it flows through the network. The ``neuralop.layers.resample`` function provides a +convenient way to do this. + +In this example, we'll demonstrate how to use the ``resample`` function to upsample and downsample +a sample from a Gaussian Random Field, which serves as a better visual tool than piecewise +constant data for observing the effects of interpolation. + +For 1D and 2D inputs, the ``resample`` function uses PyTorch’s built-in spatial interpolators +for efficiency, applying linear interpolation for 1D data and bicubic interpolation for 2D data directly +in the spatial domain. + +For 3D or higher-dimensional inputs, the ``resample`` function switches to a spectral interpolation method +based on the Fourier transform. The input is transformed into the frequency domain using a real n-dimensional FFT, +which decomposes the signal into its frequency components. By resizing this frequency representation and +then applying an inverse FFT, the function achieves smooth, alias-free interpolation +that preserves the signal’s overall structure. +""" +import torch +import matplotlib.pyplot as plt +from neuralop.layers.resample import resample + +# %% +# .. raw:: html +# +#
+# +# First, let's generate a data input. We create a high-resolution Gaussian Random Field (GRF), which +# is a smooth, continuous signal, making it ideal for visualizing the effects of resampling. +device = "cpu" + + +def generate_grf(shape, alpha=2.5, device="cpu"): + """Generates a 2D Gaussian Random Field. + + Parameters + ---------- + shape : tuple + The desired output shape (height, width). + alpha : float, optional + A parameter controlling the smoothness of the field. + Higher alpha leads to smoother fields, by default 2.5. + device : str, optional + The device to create the tensor on, by default 'cpu'. + + Returns + ------- + torch.Tensor + A 4D tensor of shape (1, 1, height, width) containing the GRF. + """ + n, m = shape + freq_x = torch.fft.fftfreq(n, d=1 / n, device=device).view(-1, 1) + freq_y = torch.fft.fftfreq(m, d=1 / m, device=device).view(1, -1) + + norm_sq = freq_x**2 + freq_y**2 + norm_sq[0, 0] = 1.0 # Avoid division by zero + + # Generate white noise in frequency domain + noise = torch.randn(n, m, dtype=torch.cfloat, device=device) + + # Apply a power-law filter + filtered_noise = noise * (norm_sq ** (-alpha / 2.0)) + + # Inverse FFT to get the spatial field + field = torch.fft.ifft2(filtered_noise).real + + # Normalize to [0, 1] for visualization + field = (field - field.min()) / (field.max() - field.min()) + + return field.unsqueeze(0).unsqueeze(0) # Add batch and channel dims + + +# Generate a 128x128 sample as our ground truth +high_res = 128 +high_res_data = generate_grf((high_res, high_res), device=device) + +# Define the low resolution we want to simulate (4x downsampling) +low_res = 32 + +# %% +# .. raw:: html +# +#
+# +# Now, let's use the ``resample`` function to simulate downsampling and upsampling operations. +# This could for instance be used in the encoder and decoder of a U-Net architecture. +# The function takes an input tensor, a `scale_factor`, and a list of +# `axis` dimensions to which the resampling is applied. + +# To downsample from 128x128 to 32x32, we need a scale factor of 32/128 = 0.25 +downsample_factor = low_res / high_res +downsampled_data = resample(high_res_data, downsample_factor, [2, 3]) + +# To upsample from 32x32 back to 128x128, we need a scale factor of 128/32 = 4 +upsample_factor = high_res / low_res +upsampled_data = resample(downsampled_data, upsample_factor, [2, 3]) + + +# %% +# .. raw:: html +# +#
+# +# Finally, let's visualize the results to see the effect of the ``resample`` function. + +fig, axs = plt.subplots(1, 3, figsize=(14, 6)) +plt.subplots_adjust(wspace=0.04) +fig.suptitle("Resampling a Gaussian Random Field", fontsize=24) + +# Plot the original high-resolution data +im1 = axs[0].imshow(high_res_data.squeeze().cpu().numpy(), cmap="viridis", vmin=0, vmax=1) +axs[0].set_title(f"High-Res Data ({high_res}x{high_res})", fontsize=16, fontweight="bold") +cbar1 = fig.colorbar(im1, ax=axs[0], fraction=0.046, pad=0.04, ticks=[0, 0.5, 1]) +cbar1.ax.tick_params(labelsize=14) + +# Plot the downsampled data +im2 = axs[1].imshow(downsampled_data.squeeze().cpu().numpy(), cmap="viridis", vmin=0, vmax=1) +axs[1].set_title(f"Downsampled (x{downsample_factor}) ({low_res}x{low_res})", fontsize=16, fontweight="bold") +cbar2 = fig.colorbar(im2, ax=axs[1], fraction=0.046, pad=0.04, ticks=[0, 0.5, 1]) +cbar2.ax.tick_params(labelsize=14) + +# Plot the upsampled data +im3 = axs[2].imshow(upsampled_data.squeeze().cpu().numpy(), cmap="viridis", vmin=0, vmax=1) +axs[2].set_title(f"Upsampled Back (x{upsample_factor:.0f}) ({high_res}x{high_res})", fontsize=16, fontweight="bold") +cbar3 = fig.colorbar(im3, ax=axs[2], fraction=0.046, pad=0.04, ticks=[0, 0.5, 1]) +cbar3.ax.tick_params(labelsize=14) + +# Hide axis ticks for a cleaner look +for ax in axs.flat: + ax.set_xticks([]) + ax.set_yticks([]) + +plt.tight_layout(rect=[0, 0.03, 1, 1.08]) +plt.show() + +# %% +# .. raw:: html +# +#
+# +# The ``resample`` function effectively changes the resolution of the data. +# Notice that the upsampled image on the right is a faithful, if slightly blurrier, +# reconstruction of the original. This is because the downsampling step is lossy; +# high-frequency details are lost and cannot be perfectly recovered. diff --git a/sources/neuraloperator/examples/layers/plot_sinusoidal_embeddings.py b/sources/neuraloperator/examples/layers/plot_sinusoidal_embeddings.py new file mode 100644 index 0000000000000000000000000000000000000000..7bd91e842a646c686653379369d645507b6b95c6 --- /dev/null +++ b/sources/neuraloperator/examples/layers/plot_sinusoidal_embeddings.py @@ -0,0 +1,634 @@ +""" +Sinusoidal Embeddings +==================== + +Inputs to deep learning models often represent positions on a spatial, temporal, or +spatio-temporal grid. To enrich these coordinates, positional embeddings can be introduced +to improve a model's capacity to generalize across the domain. In this tutorial, we focus +on sinusoidal positional embeddings. + +Sinusoidal embeddings encode inputs as periodic functions (sines and cosines), thereby +lifting low-dimensional coordinates into a richer spectral representation. This spectral +lifting enhances the model's ability to capture fine-scale variations and high-frequency +dynamics. +""" + +# %% +# .. raw:: html +# +#
+# +# Setup in 1D +# ---------------------- +# To build intuition, consider a simple 1D example. Let :math:`x \in \mathbb{R}` +# be a single input, and define the embedding function +# +# .. math:: +# g: \mathbb{R} \rightarrow \mathbb{R}^{2 L}, \quad g(x)=[\sin (x), \ \cos (x), \ \sin (2 x), \ \cos (2 x), \ldots, \ \sin (L x), \ \cos (L x)], +# +# where :math:`L` defines the number of frequencies we wish to use for the embedding. Each +# pair of sine and cosine terms introduces a higher frequency, enriching how positional +# information is represented. +# +# This idea naturally extends to an entire 1D input. Let :math:`\vec{x} \in \mathbb{R}^N` +# denote a discretized domain of :math:`N` points. Then the embedding function becomes +# +# .. math:: +# g: \mathbb{R}^N \rightarrow \mathbb{R}^{N \times 2 L}, \quad g(\vec{x})=\operatorname{concat}(\sin (\vec{x}), \cos (\vec{x}), \sin (2 \vec{x}), \cos (2 \vec{x}), \ldots, \sin (L \vec{x}), \cos (L \vec{x})), +# +# In practice, both the original coordinate and its embedding are passed to the model: +# +# .. math:: +# \operatorname{input}(\vec{x})=\operatorname{concat}(\vec{x}, \ g(\vec{x})) \in \mathbb{R}^{N \times 2 L + 1}, +# +# preserving the original input, while augmenting it with a hierarchy of frequency components. +# +# .. raw:: html +# +#
+# +# Domain Normalization +# ~~~~~~~~~~~~~~~~~~~~ +# When applying sinusoidal embeddings, it is often useful to normalize the input coordinates +# to a periodic interval that aligns with the natural period of the sine and cosine functions. +# For example, a 1D spatial domain :math:`\vec{x} \in[0,1]` of :math:`N` points can be rescaled to +# +# .. math:: +# \vec{x}^{\prime}=2 \pi \vec{x}, +# +# so that :math:`\vec{x}^{\prime} \in[0,2 \pi]`. +# +# This mapping preserves the number of sampling points :math:`N` and the overall shape of the domain +# while ensuring that the lowest-frequency sine and cosine components complete exactly one +# full oscillation over the interval. +# +# .. raw:: html +# +#
+# +# Choosing :math:`L` to Satisfy the Nyquist-Criterion +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# .. warning:: +# When choosing the number of frequency levels :math:`L`, it is important to ensure that the +# highest frequency component in the embedding does not exceed the Nyquist limit imposed by +# the discretisation of the input domain. +# +# For a domain of :math:`N` points, the Nyquist frequency is +# +# .. math:: +# f_{\text{Nyquist}} = \frac{N}{2}. +# +# For the sinusoidal embedding defined above, the Nyquist constraint becomes: +# +# .. math:: +# L < \frac{N}{2}. +# +# The Nyquist frequency represents the maximum frequency that can be correctly captured +# when sampling a signal, equal to half the sampling rate. If frequencies higher than this +# limit are used, they will not be represented as true high frequencies but will instead appear +# as lower ones, producing distortion known as aliasing. This is why we must ensure that +# the highest frequency in our embedding does not exceed the Nyquist limit. +# +# .. raw:: html +# +#
+# +# Visualizing the Sinusoidal Embeddings +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Below, we visualize the sinusoidal embeddings for a spatial input domain +# :math:`\vec{x} \in[0,1]` consisting of 1000 equally spaced points, using :math:`L = 3` frequency levels. + +# %% + +# Import required libraries +import torch +import matplotlib.pyplot as plt +import numpy as np +from neuralop.layers.embeddings import SinusoidalEmbedding + +# Set default font sizes for better readability +plt.rcParams.update( + { + "font.size": 14, + "axes.titlesize": 18, + "axes.labelsize": 16, + "xtick.labelsize": 14, + "ytick.labelsize": 14, + "legend.fontsize": 14, + } +) + +device = "cpu" + +# Define a spatial domain and number of frequencies +# Create 1000 equally spaced points in [0, 1] +# and normalize to [0, 2π] for proper sinusoidal embedding +x = torch.linspace(0, 1, 1000) +x_normalized = torch.linspace(0, 2 * torch.pi, len(x)) +# Number of frequency levels for the embedding +L = 3 + +# Check if the number of frequencies satisfies the Nyquist-Criterion +if L < len(x_normalized) / 2: + print(f"Nyquist-Shannon sampling theorem is satisfied for the given number of frequencies {L}.") +else: + print(f"Nyquist-Shannon sampling theorem is violated for the given number of frequencies {L}.") + +# Build embedding: [sin(x), cos(x), sin(2x), cos(2x), ...] +# Each frequency level contributes a sine and cosine pair +g = [] +for l in range(1, L + 1): + g.append(torch.sin(l * x_normalized)) + g.append(torch.cos(l * x_normalized)) + +# Construct input by concatenating the original input and the embedding +# This preserves the original coordinates while adding spectral information +input_arr = np.asarray([x, *g]) +input_tensor = torch.tensor(input_arr) + +# Plot the embedding components +colors = plt.cm.tab10.colors + +plt.figure(figsize=(10, 5)) +for freq_idx in range(L): + color = colors[freq_idx % len(colors)] + sin_idx = 2 * freq_idx + 1 + cos_idx = 2 * freq_idx + 2 + + plt.plot(x, input_tensor[sin_idx], color=color, label=f"Frequency {freq_idx + 1}") + plt.plot(x, input_tensor[cos_idx], color=color) + +plt.xlabel("x", fontsize=16) +plt.ylabel("Embedding value", fontsize=16) +plt.title("Sinusoidal Embedding Components (L = 3)", fontsize=18) +plt.legend(loc="lower left", framealpha=1.0, fontsize=14) +plt.locator_params(axis="y", nbins=5) +plt.tight_layout() +plt.show() + +# %% +# .. raw:: html +# +#
+# +# Encoding Constant Parameters +# ---------------------------- +# A particularly useful extension of sinusoidal embeddings is their ability to encode constant +# parameters. Consider a setting where you have a scalar parameter :math:`m` (such as a material +# property, boundary condition, or physical constant) that you wish to feed into a model. +# Instead of treating :math:`m` as a fixed scalar input, we can represent it using periodic +# functions, either by modulating the amplitude or the frequency of the sinusoidal components. +# +# .. raw:: html +# +#
+# +# **1. Amplitude Modulation:** To encode :math:`m` by scaling the amplitudes of the sinusoidal +# functions, we define the embedding as +# +# .. math:: +# m \rightarrow m g(\vec{x}), +# +# where each element of the embedding :math:`g(\vec{x})` is multiplied by :math:`m`. +# +# .. raw:: html +# +#
+# +# **2. Frequency Modulation:** Alternatively, to encode :math:`m` by scaling the frequencies, +# we define +# +# .. math:: +# m \rightarrow g(m\vec{x}) +# +# where :math:`m` multiplies the input argument of each sinusoidal component. +# +# When encoding constant parameters through frequency modulation, care must be taken to ensure +# that the Nyquist criterion is satisfied. In this case, where the modulation factor :math:`m` +# scales the frequencies, the Nyquist constraint becomes :math:`L < \frac{N}{2m}`. +# +# .. raw:: html +# +#
+# +# Below, we demonstrate an example of encoding the parameter :math:`m = 2.5` through both +# amplitude and frequency modulation. + +# %% + +# Define a spatial domain and number of frequencies +x = torch.linspace(0, 1, 1000) +x_normalized = torch.linspace(0, 2 * torch.pi, len(x)) +L = 3 + +# Define parameter to encode +m = 2.5 +m_tensor = torch.tensor([m]) + +# Check if the number of frequencies and parameter satisfies the Nyquist-Criterion +if L <= len(x_normalized) / (2 * m): + print(f"Nyquist-Shannon sampling theorem is satisfied for the given parameter {m} and number of frequencies {L}.") +else: + print(f"Nyquist-Shannon sampling theorem is violated for the given parameter {m} and number of frequencies {L}.") + +# Build amplitude-modulated embedding: m * g(x) +g_amplitude = [] +for l in range(1, L + 1): + g_amplitude.append(torch.sin(l * x_normalized) * m_tensor) + g_amplitude.append(torch.cos(l * x_normalized) * m_tensor) + +# Build frequency-modulated embedding: g(m * x) +g_frequency = [] +for l in range(1, L + 1): + g_frequency.append(torch.sin(l * x_normalized * m_tensor)) + g_frequency.append(torch.cos(l * x_normalized * m_tensor)) + +# Convert to arrays for visualization +input_amplitude = torch.tensor(np.asarray([x, *g_amplitude])) +input_frequency = torch.tensor(np.asarray([x, *g_frequency])) + +# Plot both embeddings +colors = plt.cm.tab10.colors +fig, axes = plt.subplots(2, 1, figsize=(10, 9), sharex=True) + +## Amplitude modulation +for freq_idx in range(L): + color = colors[freq_idx % len(colors)] + sin_idx, cos_idx = 2 * freq_idx + 1, 2 * freq_idx + 2 + axes[0].plot( + x, input_amplitude[sin_idx], color=color, label=f"Channel {freq_idx + 1}" + ) + axes[0].plot(x, input_amplitude[cos_idx], color=color) +axes[0].set_title("Amplitude Modulation", fontsize=18, pad=20) +axes[0].set_ylabel("Embedding value", fontsize=16) +axes[0].legend(loc="lower left", framealpha=1.0, fontsize=14) +axes[0].locator_params(axis="y", nbins=5) + +## Frequency modulation +for freq_idx in range(L): + color = colors[freq_idx % len(colors)] + sin_idx, cos_idx = 2 * freq_idx + 1, 2 * freq_idx + 2 + axes[1].plot(x, input_frequency[sin_idx], color=color, label=f"Channel {freq_idx + 1}") + axes[1].plot(x, input_frequency[cos_idx], color=color) +axes[1].set_title("Frequency Modulation", fontsize=18, pad=20) +axes[1].set_ylabel("Embedding value", fontsize=16) +axes[1].set_xlabel("x", fontsize=16) +axes[1].locator_params(axis="y", nbins=5) + +plt.suptitle(f"Sinusoidal Embeddings with Parameter m = {m}", y=0.98, fontsize=20) +plt.tight_layout() +plt.show() + +# %% +# .. raw:: html +# +#
+# +# Neural Operator SinusoidalEmbedding Class +# ----------------------------------------- +# The ``neuralop`` library provides a unified sinusoidal positional embedding class, +# ``neuralop.layers.embeddings.SinusoidalEmbedding``, with the following embedding techniques: +# +# - ``transformer`` - Vaswani, A. et al (2017), "Attention Is All You Need". +# - ``nerf`` - Mildenhall, B. et al (2020), "NeRF: Representing Scenes as Neural Radiance Fields for View Synthesis". +# +# The `SinusoidalEmbedding` class expects inputs to be of shape +# +# ``(batch_size, N, input_channels)`` or ``(N, input_channels)`` +# +# +# .. raw:: html +# +#
+# +# Embedding Variants +# ~~~~~~~~~~~~~~~~~~ +# Let :math:`\vec{x} \in \mathbb{R}^N` denote a 1D input domain consisting of +# :math:`N` discretized points. The embedding function +# :math:`g: \mathbb{R}^N \rightarrow \mathbb{R}^{N \times 2L}` maps each input value +# :math:`x_n` to a :math:`2L`-dimensional vector composed of sine and cosine terms evaluated +# at different frequencies. Each embedding type defines these frequencies differently, +# leading to distinct representations. +# +# .. raw:: html +# +#
+# +# **1. Transformer-style embedding:** For :math:`0 \leq k < L`: +# +# .. math:: +# g(\vec{x})_{:, 2 k}=\sin \left(\frac{\vec{x}}{\text { max_positions }^{k / L}}\right), \quad g(\vec{x})_{:, 2 k+1}=\cos \left(\frac{\vec{x}}{\text { max_positions }^{k / L}}\right) . +# +# Here, :math:`\text{max_positions}` controls the maximum position for the embedding. +# +# .. raw:: html +# +#
+# +# **2. NeRF-style embedding:** For :math:`0 \leq k < L`: +# +# .. math:: +# g(\vec{x})_{:, 2 k}=\sin \left(2^k \pi \vec{x}\right), \quad g(\vec{x})_{:, 2 k+1}=\cos \left(2^k \pi \vec{x}\right) . +# +# In order to ensure that the Nyquist-Criterion is satisfied, for the Transformer-style +# embedding, the embedding frequencies should satisfy: :math:`f_{\max} < f_{\text{Nyquist}}`. +# +# For the NeRF-style embedding: +# +# .. math:: +# 2^{L-1} < \frac{N}{2} \ \ \implies \ \ L < 1 + \log_2\left(\frac{N}{2}\right). +# +# .. raw:: html +# +#
+# +# Below, we include examples of using the `SinusoidalEmbedding` class with both the +# transformer- and NeRF-style embeddings. + +# %% + +# Define a spatial domain and the number of frequencies +x = torch.linspace(0, 1, 1000) +x_normalized = torch.linspace(0, 2 * torch.pi, len(x)).reshape(-1, 1) +L = 3 + +# Check if the number of frequencies satisfies the Nyquist-Criterion +if L <= 1 + torch.log2(torch.tensor(len(x_normalized) / 2)): + print(f"Nyquist-Shannon sampling theorem is satisfied for the given number of frequencies {L}.") +else: + print(f"Nyquist-Shannon sampling theorem is violated for the given number of frequencies {L}.") + +# Define the transformer embedding +# max_positions controls the frequency scaling in transformer-style embeddings +max_positions = 1000 +transformer_embedder = SinusoidalEmbedding( + in_channels=1, + num_frequencies=L, + embedding_type="transformer", + max_positions=max_positions, +).to(device) + +# Apply transformer-style embedding +transformer_embedding = transformer_embedder(x_normalized).permute(1, 0) + +# Define the NeRF embedding +nerf_embedder = SinusoidalEmbedding( + in_channels=1, num_frequencies=L, embedding_type="nerf" +).to(device) + +# Apply NeRF-style embedding, with the domain [0, 1] +nerf_embedding = nerf_embedder(x.reshape(-1, 1)).permute(1, 0) + +# Plot both embeddings +colors = plt.cm.tab10.colors +fig, axes = plt.subplots(2, 1, figsize=(10, 9), sharex=True) + +## Transformer embedding +for freq_idx in range(L): + color = colors[freq_idx % len(colors)] + sin_idx, cos_idx = 2 * freq_idx, 2 * freq_idx + 1 + + axes[0].plot(x, transformer_embedding[sin_idx], color=color, label=f"Channel {freq_idx + 1}") + axes[0].plot(x, transformer_embedding[cos_idx], color=color) + +axes[0].set_title("Transformer embedding", fontsize=18, pad=20) +axes[0].set_ylabel("Embedding value", fontsize=16) +axes[0].legend(loc="lower left", framealpha=1.0, fontsize=14) +axes[0].locator_params(axis="y", nbins=5) + +## NeRF embedding +for freq_idx in range(L): + color = colors[freq_idx % len(colors)] + sin_idx, cos_idx = 2 * freq_idx, 2 * freq_idx + 1 + + axes[1].plot(x, nerf_embedding[sin_idx], color=color, label=f"Channel {freq_idx + 1}") + axes[1].plot(x, nerf_embedding[cos_idx], color=color) + +axes[1].set_title("NeRF embedding", fontsize=18, pad=20) +axes[1].set_xlabel("x", fontsize=16) +axes[1].set_ylabel("Embedding value", fontsize=16) +axes[1].locator_params(axis="y", nbins=5) + +plt.suptitle("Sinusoidal Embeddings using transformer and NeRF embedding types", y=0.98, fontsize=20) +plt.tight_layout() +plt.show() + +# %% +# .. raw:: html +# +#
+# +# Encoding Constant Parameters with NeuralOp Class +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Similar to the earlier illustrative examples, we can also encode +# a scalar parameter :math:`m` before passing it to a model. Once again, care must be taken to +# ensure that the Nyquist criterion is satisfied. +# +# In the Transformer-style embedding, to avoid aliasing, the embedding frequencies should still +# satisfy +# +# .. math:: +# f_{\max} < f_{\text{Nyquist}}. +# +# For the NeRF-style embedding, the modified constraint becomes: +# +# .. math:: +# 2^{L-1}m < \frac{N}{2} \implies L < 1 + \log_2\left(\frac{N}{2m}\right). +# +# .. raw:: html +# +#
+# +# Below, we demonstrate an example of encoding the parameter :math:`m = 2.5` through frequency +# modulation of the NeRF-style embedding. + +# %% + +# Define a spatial domain and the number of frequencies +x = torch.linspace(0, 1, 1000) +L = 3 + +# Define the parameter to encode +m = 2.5 +m_tensor = torch.tensor([m]) + +# Check if the number of frequencies and parameter satisfies the Nyquist-Criterion +if L <= 1 + torch.log2(torch.tensor(len(x) / (2 * m))): + print(f"Nyquist-Shannon sampling theorem is satisfied for the given parameter {m} and number of frequencies {L}.") +else: + print(f"Nyquist-Shannon sampling theorem is violated for the given parameter {m} and number of frequencies {L}.") + +# Define the NeRF embedding +nerf_embedder = SinusoidalEmbedding( + in_channels=1, num_frequencies=L, embedding_type="nerf" +).to(device) + +# Apply frequency modulation: multiply input, with the domain [0, 1], by parameter before embedding +# This scales all frequencies by the parameter m +nerf_embedding = nerf_embedder(x.reshape(-1, 1) * m_tensor).permute(1, 0) + +# Plot the embedding +colors = plt.cm.tab10.colors + +plt.figure(figsize=(10, 5)) +for freq_idx in range(L): + color = colors[freq_idx % len(colors)] + sin_idx = 2 * freq_idx + cos_idx = 2 * freq_idx + 1 + + plt.plot(x, nerf_embedding[sin_idx], color=color, label=f"Channel {freq_idx}") + plt.plot(x, nerf_embedding[cos_idx], color=color) + +plt.xlabel("x", fontsize=16) +plt.ylabel("Embedding", fontsize=16) +plt.title("NeRF-style embedding with modulated frequency", fontsize=18, pad=20) +plt.legend(loc="lower left", framealpha=1.0, fontsize=14) +plt.locator_params(axis="y", nbins=5) +plt.tight_layout() +plt.show() + +# %% +# Similarly, we can encode the parameter :math:`m = 2.5` through amplitude modulation, where we show +# an example using the NeRF-style embedding below. + +# %% + +# Define a spatial domain and the number of frequencies +x = torch.linspace(0, 1, 1000) +L = 3 + +# Define the parameter to encode +m = 2.5 +m_tensor = torch.tensor([m]) + +# Check if the number of frequencies and parameter satisfies the Nyquist-Criterion +if L <= 1 + torch.log2(torch.tensor(len(x) / 2)): + print(f"Nyquist-Shannon sampling theorem is satisfied for the given number of frequencies {L}.") +else: + print(f"Nyquist-Shannon sampling theorem is violated for the given number of frequencies {L}.") + +# Define the embedding +nerf_embedder = SinusoidalEmbedding( + in_channels=1, num_frequencies=L, embedding_type="nerf" +).to(device) + +# Apply amplitude modulation: multiply embedding, with the domain [0, 1], by parameter after computation +# This scales all embedding components by the parameter m +nerf_embedding = nerf_embedder(x.reshape(-1, 1)).permute(1, 0) * m_tensor + +# Plot the embedding +colors = plt.cm.tab10.colors + +plt.figure(figsize=(10, 5)) +for freq_idx in range(L): + color = colors[freq_idx % len(colors)] + sin_idx = 2 * freq_idx + cos_idx = 2 * freq_idx + 1 + + plt.plot(x, nerf_embedding[sin_idx], color=color, label=f"Channel {freq_idx}") + plt.plot(x, nerf_embedding[cos_idx], color=color) + +plt.xlabel("x", fontsize=16) +plt.ylabel("Embedding", fontsize=16) +plt.title("NeRF-style embedding with amplitude modulation", fontsize=18, pad=20) +plt.legend(loc="lower left", framealpha=1.0, fontsize=14) +plt.locator_params(axis="y", nbins=5) +plt.tight_layout() +plt.show() + +# %% +# .. raw:: html +# +#
+# +# Application to Fourier Neural Operators (FNOs) +# ---------------------------------------------- +# Fourier Neural Operators (FNOs) learn mappings between functions by operating in the frequency domain. +# They use the Fourier transform to express data as combinations of sine and cosine components, +# enabling them to capture complex, multi-scale interactions across frequencies. +# Given that sinusoidal embeddings also lift low-dimensional data into a richer spectral +# representation, they complement FNOs naturally. +# This synergy makes sinusoidal embeddings particularly effective for neural operator architectures. +# +# In the general setting for neural operators, we strongly recommend choosing the number of frequencies +# :math:`L` such that the Nyquist-Criterion is not violated. This can be done by following the guidelines +# we provided earlier for selecting :math:`L` in both transformer-style and NeRF-style embeddings. +# +# When dealing with FNOs with a specified number of Fourier modes, :math:`\text{n_modes}`, the +# highest embedded frequency should ideally also remain below :math:`\text{n_modes}`, +# as higher frequencies will be zeroed out and not acted upon by the spectral convolution operation. +# +# For the NeRF-style embedding, this condition leads to an explicit upper bound on :math:`L`: +# +# .. math:: +# 2^{L-1} < \text{n_modes} \ \ \implies \ \ L < 1 + \log_2\left(\text{n_modes}\right). + +# %% +# .. raw:: html +# +#
+# +# Setup in Higher Dimensions +# -------------------------- +# Let :math:`X \in \mathbb{R}^{d \times N}` denote a :math:`d`-dimensional input domain consisting of +# :math:`N` discretised points, where each row :math:`\vec{x}_{i} \in \mathbb{R}^N` corresponds to +# the sampled coordinates along the :math:`i`-th spatial or temporal dimension. Thus, each column +# of :math:`X` represents a single point :math:`\vec{x}_{:,j} \in \mathbb{R}^d` in the +# :math:`d`-dimensional domain. +# +# Building on the 1D embedding function :math:`g` introduced earlier, we define the +# multi-dimensional embedding +# +# .. math:: +# h: \mathbb{R}^{d \times N} \ \ \rightarrow \ \ \mathbb{R}^{N \times 2 L d}, \quad h(X)=\operatorname{concat}\left(g\left(\vec{x}_1\right), g\left(\vec{x}_2\right), \ldots, g\left(\vec{x}_d\right)\right), +# +# where each :math:`\vec{x}_i` denotes the sampled domain along the :math:`i`-th input dimension. +# +# The multi-dimensional embedding function :math:`h` applies the 1D embedding function :math:`g` +# independently to each coordinate dimension and concatenates the resulting embeddings +# along the feature axis. This approach allows the model to capture +# frequency patterns along each dimension separately while maintaining the overall structure. +# +# .. raw:: html +# +#
+# +# Below, we include an example of using the `SinusoidalEmbedding` class to construct both +# transformer- and NeRF-style embeddings for a 3D input. + +# %% + +# Define a 1D spatial domain and construct 3D input by repeating the 1D domain +dim = 3 +x_1d = torch.linspace(0, 1, 1000) +# For transformer: normalize to [0, 2π] and repeat for 3D input, shape (N, 3) +x_normalized_1d = torch.linspace(0, 2 * torch.pi, x_1d.size(0), device=x_1d.device).unsqueeze(1) +x_normalized = x_normalized_1d.repeat(1, dim) +# For NeRF: coordinates in [0, 1] per dimension, shape (N, 3) +x_3d = x_1d.unsqueeze(1).repeat(1, dim) + +# Define the number of frequencies +L = 3 + +# Check if the number of frequencies satisfies the Nyquist-Criterion +# For multi-dimensional inputs, the constraint applies to each dimension independently +if L <= 1 + torch.log2(torch.tensor(len(x_3d) / 2)): + print(f"Nyquist-Shannon sampling theorem is satisfied for the given number of frequencies {L}.") +else: + print(f"Nyquist-Shannon sampling theorem is violated for the given number of frequencies {L}.") + +# Transformer-style 3D embedding: use normalized coordinates [0, 2π] +max_positions = 1000 +transformer_embedder = SinusoidalEmbedding( + in_channels=dim, + num_frequencies=L, + embedding_type="transformer", + max_positions=max_positions, +).to(device) +transformer_embedding = transformer_embedder(x_normalized).permute(1, 0) + +# NeRF-style 3D embedding: use coordinates in [0, 1] per dimension +nerf_embedder = SinusoidalEmbedding( + in_channels=dim, num_frequencies=L, embedding_type="nerf" +).to(device) +nerf_embedding = nerf_embedder(x_3d).permute(1, 0) diff --git a/sources/neuraloperator/examples/layers/plot_spectral_projection.py b/sources/neuraloperator/examples/layers/plot_spectral_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..4dad0f46d092ce6889f6abf4329f6e55bd029564 --- /dev/null +++ b/sources/neuraloperator/examples/layers/plot_spectral_projection.py @@ -0,0 +1,220 @@ +""" +.. _spectral_projection : + +Divergence-Free Spectral Projection +======================================================== +An example demonstrating spectral projection to enforce divergence-free constraints +in 2D velocity fields +""" + + +# %% +# .. raw:: html +# +#
+# +# Import the library +# ------------------ +# We first import our `neuralop` library and required dependencies. +import torch +import numpy as np +import matplotlib.pyplot as plt +from neuralop.layers.spectral_projection import spectral_projection_divergence_free +from neuralop.losses.differentiation import FourierDiff, FiniteDiff + +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") +print(f"Using device: {device}") + + +# %% +# .. raw:: html +# +#
+# +# Divergence error computation functions +# ------------------------------------- +# We define two functions to compute the divergence error +# using spectral differentiation and finite differences. + + +def div_error_fourier(u, L): + """Compute divergence error using spectral differentiation.""" + fourier_diff_2d = FourierDiff(dim=2, L=(L, L), use_fc=False) + div = fourier_diff_2d.divergence(u) + error_val = torch.linalg.norm(div, dim=(1, 2)) * (L**2 / (div.shape[-1] * div.shape[-2]))**(0.5) + return error_val.mean().item() + + +def div_error_finite_diff(u, L): + """Compute divergence error using FiniteDiff.""" + dx = L / u.shape[-1] + dy = L / u.shape[-2] + finite_diff_2d = FiniteDiff(dim=2, h=(dx, dy), periodic_in_x=True, periodic_in_y=True) + div = finite_diff_2d.divergence(u) + error_val = torch.linalg.norm(div, dim=(1, 2)) * (L**2 / (div.shape[-1] * div.shape[-2]))**(0.5) + return error_val.mean().item() + + +# %% +# .. raw:: html +# +#
+# +# Setting considered +# ------------------ +# We start from a divergence-free velocity field on [0, 2*pi] x [0, 2*pi] +# constructed from the stream function ψ(x,y) = sin(x) * cos(6*y) +# +# Velocity components: +# u_x = ∂ψ/∂y = -6 * sin(x) * sin(6*y) +# +# u_y = -∂ψ/∂x = - cos(x) * cos(6*y) +# +# ------------------------------------------------------- +# +# Mathematical verification of divergence-free property: +# +# ∇·u = ∂u_x/∂x + ∂u_y/∂y +# +# = ∂/∂x[-6*sin(x) * sin(6*y)] + ∂/∂y[-cos(x) * cos(6*y)] +# +# = -6*cos(x) * sin(6*y) + 6*cos(x) * sin(6*y) +# +# = 0 ✓ +# +# ------------------------------------------------------- +# +# +# We then add 10% noise to break the divergence-free property. +# +# We then apply the spectral projection to restore the divergence-free property. +# +# We then compute the divergence error for the original, noisy, and projected fields. +# +# We repeat this at various resolutions, [256, 512, 1024, 2048, 4096, 8192]. + +L = 2 * np.pi +noise_level = 0.1 +resolutions = [256, 512, 1024, 2048, 4096, 8192] + + +errors_original_spectral = [] +errors_original_finite = [] +errors_noisy_spectral = [] +errors_noisy_finite = [] +errors_prog_spectral = [] +errors_prog_finite = [] + +for target_resolution in resolutions: + # Create coordinate grids for this resolution + xs = torch.arange(target_resolution, device=device, dtype=torch.float64) * (L / target_resolution) + ys = torch.arange(target_resolution, device=device, dtype=torch.float64) * (L / target_resolution) + X, Y = torch.meshgrid(xs, ys, indexing="ij") + + # Create divergence-free field using the stream function defined earlier + u_x = -6.0 * torch.sin(X) * torch.sin(6.0 * Y) + u_y = -torch.cos(X) * torch.cos(6.0 * Y) + u = torch.stack([u_x, u_y], dim=0).unsqueeze(0).to(device=device, dtype=torch.float64) + + # Add noise to break divergence-free property + mean_magnitude = torch.mean(torch.sqrt(u[:, 0] ** 2 + u[:, 1] ** 2)) + noise = torch.randn_like(u, dtype=torch.float64) * noise_level * mean_magnitude + u_noisy = u + noise + + # Apply spectral projection to restore divergence-free property + u_proj = spectral_projection_divergence_free(u_noisy, L, constraint_modes=(64, 64)) + + # Compute divergence errors for all three fields + errors_original_spectral.append(div_error_fourier(u, L)) + errors_original_finite.append(div_error_finite_diff(u, L)) + errors_noisy_spectral.append(div_error_fourier(u_noisy, L)) + errors_noisy_finite.append(div_error_finite_diff(u_noisy, L)) + errors_prog_spectral.append(div_error_fourier(u_proj, L)) + errors_prog_finite.append(div_error_finite_diff(u_proj, L)) + + +# %% +# .. raw:: html +# +#
+# +# Divergence Errors using Spectral Differentiation +# ------------------------------------------------ +# The Fourier differentiation method computes derivatives in the spectral domain +# by transforming the field to Fourier space, applying the appropriate wavenumber +# operators, and transforming back. +# +# We display the divergence error for the original, noisy, and projected fields +# at the different resolutions. +# +# Note that at lower resolutions, finite differences are not accurate enough +# to properly compute the divergence error, which is why the errors appear higher +# initially but improve at higher resolutions. This is a limitation of +# finite differences for computing derivatives, not an issue with the +# spectral projection itself. Spectral differentiation provides more accurate +# derivative calculations at lower resolutions. + + +# Spectral Differentiation table +print("-" * 55) +print(f"{'Resolution':<12} {'Original':<15} {'Noisy':<15} {'Projected':<15}") +print("-" * 55) + +for i, res in enumerate(resolutions): + print( + f"{res:<12} {errors_original_spectral[i]:<15.2e} {errors_noisy_spectral[i]:<15.2e} {errors_prog_spectral[i]:<15.2e}" + ) + + +# Spectral Differentiation plot +plt.figure(figsize=(10, 6)) +plt.semilogy(resolutions, errors_original_spectral, "o-", label="Original", color="black", linewidth=2.5, markersize=6) +plt.semilogy(resolutions, errors_noisy_spectral, "o-", label="Noisy", color="green", linewidth=2.5, markersize=6) +plt.semilogy(resolutions, errors_prog_spectral, "o-", label="Projected", color="blue", linewidth=2.5, markersize=6) +plt.xlabel("Resolution", fontsize=16) +plt.ylabel("Divergence Error (L2 norm)", fontsize=16) +plt.title("Spectral Divergence Errors", fontsize=18) +plt.legend(fontsize=14) +plt.grid(True, alpha=0.3) +plt.xticks(fontsize=14) +plt.yticks(fontsize=14) +plt.tight_layout() +plt.show() + +# %% +# .. raw:: html +# +#
+# +# Divergence Errors using Finite Differences +# -------------------------- +# The finite difference method approximates derivatives using central differences. +# +# We display the divergence error for the original, noisy, and projected fields +# at the different resolutions. + +# Finite differences table +print("-" * 55) +print(f"{'Resolution':<12} {'Original':<15} {'Noisy':<15} {'Projected':<15}") +print("-" * 55) + +for i, res in enumerate(resolutions): + print( + f"{res:<12} {errors_original_finite[i]:<15.2e} {errors_noisy_finite[i]:<15.2e} {errors_prog_finite[i]:<15.2e}" + ) + + +# Finite differences plot +plt.figure(figsize=(10, 6)) +plt.semilogy(resolutions, errors_original_finite, "o-", label="Original", color="black", linewidth=2.5, markersize=6) +plt.semilogy(resolutions, errors_noisy_finite, "o-", label="Noisy", color="green", linewidth=2.5, markersize=6) +plt.semilogy(resolutions, errors_prog_finite, "o-", label="Projected", color="blue", linewidth=2.5, markersize=6) +plt.xlabel("Resolution", fontsize=16) +plt.ylabel("Divergence Error (L2 norm)", fontsize=16) +plt.title("Finite Difference Divergence Errors", fontsize=18) +plt.legend(fontsize=14) +plt.grid(True, alpha=0.3) +plt.xticks(fontsize=14) +plt.yticks(fontsize=14) +plt.tight_layout() +plt.show() diff --git a/sources/neuraloperator/examples/models/GALLERY_HEADER.rst b/sources/neuraloperator/examples/models/GALLERY_HEADER.rst new file mode 100644 index 0000000000000000000000000000000000000000..5fd51b91c500ae856fea0b7f00e0f3e20fc291fb --- /dev/null +++ b/sources/neuraloperator/examples/models/GALLERY_HEADER.rst @@ -0,0 +1,6 @@ +.. _model_examples : + +Models +------ + +Examples showcasing our end-to-end NO architectures. \ No newline at end of file diff --git a/sources/neuraloperator/examples/models/plot_FNO_darcy.py b/sources/neuraloperator/examples/models/plot_FNO_darcy.py new file mode 100644 index 0000000000000000000000000000000000000000..f02d0a665e58754415b4dfbad2c484b72ba75d0f --- /dev/null +++ b/sources/neuraloperator/examples/models/plot_FNO_darcy.py @@ -0,0 +1,303 @@ +""" +Training an FNO on Darcy-Flow +============================= + +We train a Fourier Neural Operator (FNO) on our small :ref:`Darcy-Flow example `. + +This tutorial demonstrates the complete workflow of training a neural operator: +1. Loading and preprocessing the Darcy-Flow dataset +2. Creating an FNO model architecture +3. Setting up training components (optimizer, scheduler, losses) +4. Training the model +5. Evaluating predictions and zero-shot super-resolution + +Note that this dataset is much smaller than one we would use in practice. The small Darcy-flow is an example built to +be trained on a CPU in a few seconds, whereas normally we would train on one or multiple GPUs. + +The FNO's key advantage is its resolution invariance - it can make predictions at different resolutions +without retraining, which we will demonstrate in the zero-shot super-resolution section. +""" + +# %% +# .. raw:: html +# +#
+# +# Import dependencies +# ------------------- +# We import the necessary modules from `neuralop` for training a Fourier Neural Operator + +import torch +import matplotlib.pyplot as plt +import sys +from neuralop.models import FNO +from neuralop import Trainer +from neuralop.training import AdamW +from neuralop.data.datasets import load_darcy_flow_small +from neuralop.utils import count_model_params +from neuralop import LpLoss, H1Loss + +device = "cpu" + +# %% +# .. raw:: html +# +#
+# +# Loading the Darcy-Flow dataset +# ------------------------------ +# We load the small Darcy-Flow dataset with multiple resolutions for training and testing. +# The dataset contains permeability fields (input) and pressure fields (output). + +train_loader, test_loaders, data_processor = load_darcy_flow_small( + n_train=1000, + batch_size=64, + n_tests=[100, 50], + test_resolutions=[16, 32], + test_batch_sizes=[32, 32], +) +data_processor = data_processor.to(device) + + +# %% +# .. raw:: html +# +#
+# +# Creating the FNO model +# ---------------------- + +model = FNO( + n_modes=(8, 8), + in_channels=1, + out_channels=1, + hidden_channels=24, + projection_channel_ratio=2, +) +model = model.to(device) + +# Count and display the number of parameters +n_params = count_model_params(model) +print(f"\nOur model has {n_params} parameters.") +sys.stdout.flush() + + +# %% +# .. raw:: html +# +#
+# +# Creating the optimizer and scheduler +# ------------------------------------ +# We use AdamW optimizer with weight decay for regularization +optimizer = AdamW(model.parameters(), lr=1e-2, weight_decay=1e-4) +scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=30) + +# %% +# .. raw:: html +# +#
+# +# Setting up loss functions +# ------------------------- +# We use H1 loss for training and L2 loss for evaluation +# H1 loss is particularly good for PDE problems as it penalizes both function values and gradients +l2loss = LpLoss(d=2, p=2) # L2 loss for function values +h1loss = H1Loss(d=2) # H1 loss includes gradient information + +train_loss = h1loss +eval_losses = {"h1": h1loss, "l2": l2loss} + + +# %% +# .. raw:: html +# +#
+# +# Training the model +# --------------------- +# We display the training configuration and then train the model + +print("\n### MODEL ###\n", model) +print("\n### OPTIMIZER ###\n", optimizer) +print("\n### SCHEDULER ###\n", scheduler) +print("\n### LOSSES ###") +print(f"\n * Train: {train_loss}") +print(f"\n * Test: {eval_losses}") +sys.stdout.flush() + +# %% +# .. raw:: html +# +#
+# +# Creating the trainer +# -------------------- +# We create a Trainer object that handles the training loop, evaluation, and logging +trainer = Trainer( + model=model, + n_epochs=15, + device=device, + data_processor=data_processor, + wandb_log=False, # Disable Weights & Biases logging for this tutorial + eval_interval=5, # Evaluate every 5 epochs + use_distributed=False, # Single GPU/CPU training + verbose=True, # Print training progress +) + +# %% +# .. raw:: html +# +#
+# +# Training the model +# ------------------ +# We train the model on our Darcy-Flow dataset. The trainer will: +# 1. Run the forward pass through the FNO +# 2. Compute the H1 loss +# 3. Backpropagate and update weights +# 4. Evaluate on test data every 3 epochs + +trainer.train( + train_loader=train_loader, + test_loaders=test_loaders, + optimizer=optimizer, + scheduler=scheduler, + regularizer=False, + training_loss=train_loss, + eval_losses=eval_losses, +) + +# %% +# .. raw:: html +# +#
+# +# .. _plot_preds : +# Visualizing predictions +# ------------------------ +# Let's take a look at what our model's predicted outputs look like. +# We wll compare the inputs, ground-truth outputs, and model predictions side by side. +# +# Note that in this example, we train on a very small resolution for +# a very small number of epochs. In practice, we would train at a larger +# resolution on many more samples. + +test_samples = test_loaders[16].dataset + +fig = plt.figure(figsize=(7, 7)) +for index in range(3): + data = test_samples[index] + data = data_processor.preprocess(data, batched=False) + + # Input + x = data["x"] + # Ground-truth output + y = data["y"] + # Model prediction + out = model(x.unsqueeze(0)) + + # Plot input + ax = fig.add_subplot(3, 3, index * 3 + 1) + ax.imshow(x[0], cmap="gray") + if index == 0: + ax.set_title("Input x") + plt.xticks([], []) + plt.yticks([], []) + + # Plot ground-truth output + ax = fig.add_subplot(3, 3, index * 3 + 2) + ax.imshow(y.squeeze()) + if index == 0: + ax.set_title("Ground-truth output") + plt.xticks([], []) + plt.yticks([], []) + + # Plot model prediction + ax = fig.add_subplot(3, 3, index * 3 + 3) + ax.imshow(out.squeeze().detach().numpy()) + if index == 0: + ax.set_title("Model prediction") + plt.xticks([], []) + plt.yticks([], []) + +fig.suptitle("FNO predictions on 16x16 Darcy-Flow data", y=0.98) +plt.tight_layout() +fig.show() + + +# %% +# .. raw:: html +# +#
+# +# .. zero_shot : +# Zero-shot super-resolution evaluation +# ------------------------------------- +# One of the key advantages of neural operators is their resolution invariance. +# The FNO's invariance to the discretization of input data means we can natively +# make predictions on higher-resolution inputs and get higher-resolution outputs +# without retraining the model! + +test_samples = test_loaders[32].dataset + +fig = plt.figure(figsize=(7, 7)) +for index in range(3): + data = test_samples[index] + data = data_processor.preprocess(data, batched=False) + + # Input at higher-resolution + x = data["x"] + # Ground-truth output at higher-resolution + y = data["y"] + # Model prediction at higher-resolution + out = model(x.unsqueeze(0)) + + # Plot input at higher-resolution + ax = fig.add_subplot(3, 3, index * 3 + 1) + ax.imshow(x[0], cmap="gray") + if index == 0: + ax.set_title("Input at 32x32") + plt.xticks([], []) + plt.yticks([], []) + + # Plot ground-truth output at higher-resolution + ax = fig.add_subplot(3, 3, index * 3 + 2) + ax.imshow(y.squeeze()) + if index == 0: + ax.set_title("Ground-truth at 32x32") + plt.xticks([], []) + plt.yticks([], []) + + # Plot model prediction at higher-resolution + ax = fig.add_subplot(3, 3, index * 3 + 3) + ax.imshow(out.squeeze().detach().numpy()) + if index == 0: + ax.set_title("FNO prediction at 32x32") + plt.xticks([], []) + plt.yticks([], []) + +fig.suptitle("Zero-shot super-resolution: 16x16 → 32x32", y=0.98) +plt.tight_layout() +fig.show() + +# %% +# .. raw:: html +# +#
+# +# Understanding zero-shot super-resolution +# ---------------------------------------- +# We only trained the model on data at a resolution of 16x16, and with no modifications +# or special prompting, we were able to perform inference on higher-resolution input data +# and get higher-resolution predictions! This is a powerful capability of neural operators. +# +# In practice, we often want to evaluate neural operators at multiple resolutions to track +# a model's zero-shot super-resolution performance throughout training. That's why many of +# our datasets, including the small Darcy-flow we showcased, are parameterized with a list +# of `test_resolutions` to choose from. +# +# Note: These predictions may be noisier than we would expect for a model evaluated +# at the same resolution at which it was trained. This is because the model hasn't seen +# the higher-frequency patterns present in the 32x32 data during training. However, this +# demonstrates the fundamental resolution invariance of neural operators. diff --git a/sources/neuraloperator/examples/models/plot_OTNO_car_cfd.py b/sources/neuraloperator/examples/models/plot_OTNO_car_cfd.py new file mode 100644 index 0000000000000000000000000000000000000000..34719565eee94a51310f0b44ccc1a1d34349f13b --- /dev/null +++ b/sources/neuraloperator/examples/models/plot_OTNO_car_cfd.py @@ -0,0 +1,387 @@ +""" +Training OTNO on a Car CFD Dataset +========================================== + +We load a pre-generated optimal transport (OT) dataset from car CFD data and train an OTNO model on it. + +This tutorial demonstrates how to: + +1. Load and preprocess optimal transport data for car CFD simulations +2. Create and configure an OTNO model for pressure field prediction +3. Train the model using the Trainer with proper normalization +4. Visualize the input OT maps, ground truth, and model predictions in 3D + +""" + +# %% +# .. raw:: html +# +#
+# +# Imports and setup +# ------------------------------ +from copy import deepcopy +import numpy as np +import torch +import matplotlib.pyplot as plt +import matplotlib.animation as animation +import sys +from neuralop.models import OTNO +from neuralop import Trainer +from neuralop.training import AdamW +from neuralop.data.datasets import load_saved_ot, CFDDataProcessor +from neuralop.utils import count_model_params +from neuralop import LpLoss + +# %% +# .. raw:: html +# +#
+# +# Loading the Car OT dataset +# ------------------------------ +# We load the small Car OT dataset. +# The dataset contains OT maps (input) and pressure fields (output). +data_module = load_saved_ot( + n_train=2, + n_test=1, + expand_factor=3.0, + reg=1e-06, +) + +train_loader = data_module.train_loader(batch_size=1, shuffle=True) +test_loader = data_module.test_loader(batch_size=1, shuffle=False) + +output_encoder = deepcopy(data_module.normalizers["press"]) +data_processor = CFDDataProcessor(normalizer=output_encoder) + +# %% +# .. raw:: html +# +#
+# +# Creating the OTNO model +# ---------------------- +model = OTNO( + n_modes=(16, 16), + hidden_channels=64, + in_channels=9, + out_channels=1, + lifting_channel_ratio=2, + projection_channel_ratio=2, + norm="group_norm", + use_channel_mlp=True, + channel_mlp_expansion=1.0, +) + +# Count and display the number of parameters +n_params = count_model_params(model) +print(f"\nOur model has {n_params} parameters.") +sys.stdout.flush() + +# %% +# .. raw:: html +# +#
+# +# Creating the optimizer and scheduler +# ------------------------------------ +# We use AdamW optimizer with weight decay for regularization +optimizer = AdamW(model.parameters(), lr=1e-3, weight_decay=1e-4) +scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=30) + +# %% +# .. raw:: html +# +#
+# +# Setting up loss functions +# ------------------------- +# We use L2 loss for training and evaluation +l2loss = LpLoss(d=2, p=2) +train_loss_fn = l2loss +test_loss_fn = l2loss + +# %% +# .. raw:: html +# +#
+# +# Training the model +# --------------------- +# We display the training configuration and then train the model + +print("\n### MODEL ###\n", model) +print("\n### OPTIMIZER ###\n", optimizer) +print("\n### SCHEDULER ###\n", scheduler) +print("\n### LOSSES ###") +print(f"\n * Train: {train_loss_fn}") +print(f"\n * Test: {test_loss_fn}") +sys.stdout.flush() + +# %% +# .. raw:: html +# +#
+# +# Creating the trainer +# -------------------- +# We create a Trainer object that handles the training loop, evaluation, and logging +trainer = Trainer( + model=model, + n_epochs=15, + data_processor=data_processor, + wandb_log=False, # Disable Weights & Biases logging for this tutorial + use_distributed=False, # Single GPU/CPU training + verbose=True, # Print training progress +) + +# %% +# .. raw:: html +# +#
+# +# Training the model +# ------------------ +# We train the model on our car cfd dataset. The trainer will: + +# 1. Run the forward pass through the OTNO +# 2. Compute the L2 loss +# 3. Backpropagate and update weights +# 4. Evaluate on test data + +trainer.train( + train_loader=train_loader, + test_loaders={"": test_loader}, + optimizer=optimizer, + scheduler=scheduler, + training_loss=train_loss_fn, + eval_losses={"l2": test_loss_fn}, + regularizer=None, +) + + +# %% +# .. raw:: html +# +#
+# +# .. _plot_preds : +# Visualizing predictions +# ------------------------ +# Let's take a look at what our model's predicted outputs look like. +# We will compare the inputs, ground-truth outputs, and model predictions side by side. +# +# Note that in this example, we train on 2 cars and test on 1 car. In practice, you would train on a larger +# number of cars for better generalization. + +test_sample = test_loader.dataset[0] + +# Preprocess the sample +model.eval() +with torch.no_grad(): + # Preprocess the data + processed_sample = data_processor.preprocess(test_sample.copy()) + + # Get model prediction + x = processed_sample["x"].unsqueeze(0) # Add batch dimension + ind_dec = processed_sample["ind_dec"] + + # Forward pass + prediction = model(x, ind_dec) + + # Inverse transform to get actual pressure values + prediction = output_encoder.inverse_transform(prediction.reshape(-1, 1)) + ground_truth = output_encoder.inverse_transform( + processed_sample["y"].reshape(-1, 1) + ) + +# Extract geometry data +vertices = test_sample["target"].numpy() # Target mesh vertices +source = test_sample["source"].numpy() # Source mesh vertices +ind_enc = test_sample["ind_enc"].numpy() # Encoder indices +trans = vertices[ind_enc, :] # Transport coordinates + +# Calculate axis limits for equal aspect ratio +x, y, z = vertices[:, 0], vertices[:, 1], vertices[:, 2] +max_range = np.array([x.max() - x.min(), y.max() - y.min(), z.max() - z.min()]).max() / 2.0 +mid_x, mid_y, mid_z = (x.max() + x.min()) * 0.5, (y.max() + y.min()) * 0.5, (z.max() + z.min()) * 0.5 + +# Set common color scale for pressure plots +vmin = min(ground_truth.min().item(), prediction.min().item()) +vmax = max(ground_truth.max().item(), prediction.max().item()) + +# Create RGB colors from transport coordinates +color_x = (trans[:, 0] - trans[:, 0].min()) / (trans[:, 0].max() - trans[:, 0].min()) +color_y = (trans[:, 1] - trans[:, 1].min()) / (trans[:, 1].max() - trans[:, 1].min()) +color_z = (trans[:, 2] - trans[:, 2].min()) / (trans[:, 2].max() - trans[:, 2].min()) +colors = np.stack([color_x, color_y, color_z], axis=1) + +# Create three-panel visualization +fig = plt.figure(figsize=(18, 6)) + +# Panel 1: Input OT with RGB-colored transport +ax1 = fig.add_subplot(1, 3, 1, projection="3d") +scatter1 = ax1.scatter(source[:, 0], source[:, 1], source[:, 2], c=colors, alpha=0.5, s=15) +ax1.set_xlim(mid_x - max_range, mid_x + max_range) +ax1.set_ylim(mid_y - max_range, mid_y + max_range) +ax1.set_zlim(mid_z - max_range, mid_z + max_range) +ax1.set_xlabel("x") +ax1.set_ylabel("y") +ax1.set_zlabel("z") +ax1.set_title("Input OT\n(RGB: Transport coordinates)", fontsize=10) +ax1.view_init(elev=20, azim=150, roll=0, vertical_axis="y") +ax1.text2D( + 0.05, + 0.95, + "Color = RGB(trans_x, trans_y, trans_z)", + transform=ax1.transAxes, + fontsize=8, + verticalalignment="top", + bbox=dict(boxstyle="round", facecolor="wheat", alpha=0.5), +) + +# Panel 2: Ground truth pressure +ax2 = fig.add_subplot(1, 3, 2, projection="3d") +scatter2 = ax2.scatter(x, y, z, s=2, c=ground_truth.cpu().numpy(), cmap="viridis", vmin=vmin, vmax=vmax) +ax2.set_xlim(mid_x - max_range, mid_x + max_range) +ax2.set_ylim(mid_y - max_range, mid_y + max_range) +ax2.set_zlim(mid_z - max_range, mid_z + max_range) +ax2.set_box_aspect([1, 1, 1]) +ax2.set_xlabel("x") +ax2.set_ylabel("y") +ax2.set_zlabel("z") +ax2.set_title("Ground Truth Pressure") +ax2.view_init(elev=20, azim=150, roll=0, vertical_axis="y") + +# Panel 3: Model prediction +ax3 = fig.add_subplot(1, 3, 3, projection="3d") +scatter3 = ax3.scatter(x, y, z, s=2, c=prediction.cpu().numpy(), cmap="viridis", vmin=vmin, vmax=vmax) +ax3.set_xlim(mid_x - max_range, mid_x + max_range) +ax3.set_ylim(mid_y - max_range, mid_y + max_range) +ax3.set_zlim(mid_z - max_range, mid_z + max_range) +ax3.set_box_aspect([1, 1, 1]) # Force equal box aspect +ax3.set_xlabel("x") +ax3.set_ylabel("y") +ax3.set_zlabel("z") +ax3.set_title("Model Prediction") +ax3.view_init(elev=20, azim=150, roll=0, vertical_axis="y") + +# Add a colorbar +fig.colorbar(scatter2, ax=[ax2, ax3], pad=0.1, label="Pressure", shrink=0.8) + +plt.show() + +# Print error statistics +print(f"\n### Prediction Statistics ###") +print( + f"Relative L2 Error: {(torch.norm(prediction - ground_truth) / torch.norm(ground_truth)).item():.6f}" +) + +# %% +# .. raw:: html +# +#
+# +# Visualizing OT encoding and decoding +# ------------------------------------- +# We display the optimal transport process as animations showing how the +# car surface is mapped to the latent torus grid and back. + +pressure_pullback = ground_truth[ind_enc].numpy() +n_s = source.shape[0] + +# OT encoding from the car surface to the latent torus grid +T = 60 +movement_enc = np.zeros((T, n_s, 3)) + +for j in range(n_s): + # Animate from CAR (trans) -> TORUS (source) for encoding + tx = np.linspace(trans[j, 0], source[j, 0], T).reshape((T, 1)) + ty = np.linspace(trans[j, 1], source[j, 1], T).reshape((T, 1)) + tz = np.linspace(trans[j, 2], source[j, 2], T).reshape((T, 1)) + movement_enc[:, j, :] = np.concatenate((tx, ty, tz), axis=1) + +# Create a Matplotlib 3D animation for the encoding (trans -> source) +print("Creating car to torus animation (matplotlib)...") +fig_enc = plt.figure(figsize=(5, 5)) +ax_enc = fig_enc.add_subplot(111, projection="3d") +sc_enc = ax_enc.scatter( + movement_enc[0, :, 0], + movement_enc[0, :, 1], + movement_enc[0, :, 2], + c="grey", + s=2, + alpha=0.95, + edgecolors="#7fb0b6", + linewidths=0.03, + depthshade=True, +) +ax_enc.set_xlim(mid_x - max_range, mid_x + max_range) +ax_enc.set_ylim(mid_y - max_range, mid_y + max_range) +ax_enc.set_zlim(mid_z - max_range, mid_z + max_range) +ax_enc.set_title("OT Encoding: Car → Torus") +ax_enc.view_init(elev=20, azim=150, roll=0, vertical_axis="y") + + +def update_enc(frame): + xs = movement_enc[frame, :, 0] + ys = movement_enc[frame, :, 1] + zs = movement_enc[frame, :, 2] + sc_enc._offsets3d = (xs, ys, zs) + ax_enc.set_title(f"OT Encoding: frame {frame}") + return (sc_enc,) + + +ani_enc = animation.FuncAnimation( + fig_enc, update_enc, frames=T, interval=50, blit=False +) + +# OT decoding process from the latent torus grid to the car surface +T = 60 +movement_dec = np.zeros((T, n_s, 3)) + +for j in range(n_s): + # Animate from TORUS (source) -> CAR (trans) for decoding + tx = np.linspace(source[j, 0], trans[j, 0], T).reshape((T, 1)) + ty = np.linspace(source[j, 1], trans[j, 1], T).reshape((T, 1)) + tz = np.linspace(source[j, 2], trans[j, 2], T).reshape((T, 1)) + movement_dec[:, j, :] = np.concatenate((tx, ty, tz), axis=1) + +print("Creating torus to car animation (matplotlib) with pressure...") +fig_dec = plt.figure(figsize=(8, 6)) +ax_dec = fig_dec.add_subplot(111, projection="3d") +# Initial positions: movement_dec[0] (source positions) +sc_dec = ax_dec.scatter( + movement_dec[0, :, 0], + movement_dec[0, :, 1], + movement_dec[0, :, 2], + c=pressure_pullback, + cmap="viridis", + s=2, + vmin=vmin, + vmax=vmax, + alpha=0.95, + edgecolors="none", + linewidths=0.03, + depthshade=True, +) +ax_dec.set_xlim(mid_x - max_range, mid_x + max_range) +ax_dec.set_ylim(mid_y - max_range, mid_y + max_range) +ax_dec.set_zlim(mid_z - max_range, mid_z + max_range) +ax_dec.set_title("OT Decoding: Torus → Car (pressure)") +ax_dec.view_init(elev=20, azim=150, roll=0, vertical_axis="y") + + +def update_dec(frame): + xs = movement_dec[frame, :, 0] + ys = movement_dec[frame, :, 1] + zs = movement_dec[frame, :, 2] + sc_dec._offsets3d = (xs, ys, zs) + ax_dec.set_title(f"OT Decoding: frame {frame}") + return (sc_dec,) + + +ani_dec = animation.FuncAnimation( + fig_dec, update_dec, frames=T, interval=50, blit=False +) diff --git a/sources/neuraloperator/examples/models/plot_SFNO_swe.py b/sources/neuraloperator/examples/models/plot_SFNO_swe.py new file mode 100644 index 0000000000000000000000000000000000000000..7105c04d7944be388f0efa962207910d90ae2aa2 --- /dev/null +++ b/sources/neuraloperator/examples/models/plot_SFNO_swe.py @@ -0,0 +1,219 @@ +""" +Training a SFNO on the spherical Shallow Water equations +========================================================== + +Using the small Spherical Shallow Water Equations example we ship with the package +to train a Spherical Fourier-Neural Operator (SFNO). + +This tutorial demonstrates how to train neural operators on spherical domains, which is +crucial for many geophysical applications like weather prediction, ocean modeling, and +climate science. The SFNO extends the FNO architecture to handle data on the sphere +using spherical harmonics instead of regular Fourier modes. + +The Shallow Water Equations describe the motion of a thin layer of fluid and are +fundamental in atmospheric and oceanic dynamics. +""" + +# %% +# .. raw:: html +# +#
+# +# Import dependencies +# ------------------- +# We import the necessary modules for training a Spherical Fourier Neural Operator + +import torch +import matplotlib.pyplot as plt +import sys +from neuralop.models import SFNO +from neuralop import Trainer +from neuralop.training import AdamW +from neuralop.data.datasets import load_spherical_swe +from neuralop.utils import count_model_params +from neuralop import LpLoss, H1Loss + +device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") + +# %% +# .. raw:: html +# +#
+# +# Loading the Spherical Shallow Water Equations dataset +# ----------------------------------------------------- +# We load the spherical shallow water equations dataset with multiple resolutions. +# The dataset contains velocity and height fields on the sphere, which are the +# fundamental variables in shallow water dynamics. + +train_loader, test_loaders = load_spherical_swe( + n_train=200, + batch_size=32, + train_resolution=(32, 64), + test_resolutions=[(32, 64), (64, 128)], + n_tests=[40, 40], + test_batch_sizes=[40, 40], +) + + +# %% +# .. raw:: html +# +#
+# +# Creating the Spherical FNO model +# --------------------------------- + + +model = SFNO( + n_modes=(16, 32), + in_channels=3, + out_channels=3, + hidden_channels=64, + domain_padding=[0.05, 0.05], + n_layers=2, +) +model = model.to(device) + +# Count and display the number of parameters +n_params = count_model_params(model) +print(f"\nOur model has {n_params} parameters.") +sys.stdout.flush() + + +# %% +# .. raw:: html +# +#
+# +# Creating the optimizer and scheduler +# ------------------------------------ +# We use AdamW optimizer with a lower learning rate for spherical data +optimizer = AdamW(model.parameters(), lr=5e-3, weight_decay=1e-4) +scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=30) + +# %% +# .. raw:: html +# +#
+# +# Setting up loss functions +# ------------------------- +# For spherical data, we use L2 loss with sum reduction to handle the varying +# grid sizes across different latitudes on the sphere +l2loss = LpLoss(d=2, p=2, reduction="sum") + +train_loss = l2loss +eval_losses = {"l2": l2loss} + + +# %% + + +print("\n### MODEL ###\n", model) +print("\n### OPTIMIZER ###\n", optimizer) +print("\n### SCHEDULER ###\n", scheduler) +print("\n### LOSSES ###") +print(f"\n * Train: {train_loss}") +print(f"\n * Test: {eval_losses}") +sys.stdout.flush() + + +# %% +# .. raw:: html +# +#
+# +# Creating the trainer +# --------------------- +# We create a Trainer object that handles the training loop for spherical data +trainer = Trainer( + model=model, + n_epochs=30, + device=device, + wandb_log=False, # Disable Weights & Biases logging + eval_interval=5, # Evaluate every 5 epochs + use_distributed=False, # Single GPU/CPU training + verbose=True, # Print training progress +) + +# %% +# .. raw:: html +# +#
+# +# Training the SFNO model +# ------------------------ +# We train the model on the spherical shallow water equations dataset. +# The trainer will handle the forward pass through the SFNO, compute the L2 loss, +# backpropagate, and evaluate on test data. + +trainer.train( + train_loader=train_loader, + test_loaders=test_loaders, + optimizer=optimizer, + scheduler=scheduler, + regularizer=False, + training_loss=train_loss, + eval_losses=eval_losses, +) + + +# %% +# .. raw:: html +# +#
+# +# Visualizing SFNO predictions on spherical data +# ------------------------------------------------ +# We visualize the model's predictions on spherical shallow water equations data. +# Note that we trained on a very small resolution for a very small number of epochs. +# In practice, we would train at larger resolution on many more samples. +# +# However, for practicality, we created a minimal example that: +# i) fits in just a few MB of memory +# ii) can be trained quickly on CPU +# +# In practice we would train a Neural Operator on one or multiple GPUs + +fig = plt.figure(figsize=(14, 7)) +for index, resolution in enumerate([(32, 64), (64, 128)]): + test_samples = test_loaders[resolution].dataset + data = test_samples[0] + # Input x + x = data["x"] + # Ground-truth + y = data["y"][0, ...].numpy() + # Model prediction: SFNO output + x_in = x.unsqueeze(0).to(device) + out = model(x_in).squeeze()[0, ...].detach().cpu().numpy() + x = x[0, ...].detach().numpy() + + # Plot input fields + ax = fig.add_subplot(2, 3, index * 3 + 1) + ax.imshow(x) + ax.set_title(f"Input x {resolution}") + plt.xticks([], []) + plt.yticks([], []) + + # Compute the min and max to use consistent color mapping + vmin = y.min() + vmax = y.max() + + # Plot ground-truth fields + ax = fig.add_subplot(2, 3, index * 3 + 2) + im_gt = ax.imshow(y, vmin=vmin, vmax=vmax) + ax.set_title("Ground-truth y") + plt.xticks([], []) + plt.yticks([], []) + + # Plot model prediction + ax = fig.add_subplot(2, 3, index * 3 + 3) + im_pred = ax.imshow(out, vmin=vmin, vmax=vmax) + ax.set_title("SFNO prediction") + plt.xticks([], []) + plt.yticks([], []) + +fig.suptitle("SFNO predictions on spherical shallow water equations", y=0.98, fontsize=24) +plt.tight_layout() +fig.show() diff --git a/sources/neuraloperator/examples/models/plot_UNO_darcy.py b/sources/neuraloperator/examples/models/plot_UNO_darcy.py new file mode 100644 index 0000000000000000000000000000000000000000..84c623a00095e27e351826497969cb6bce53f5a5 --- /dev/null +++ b/sources/neuraloperator/examples/models/plot_UNO_darcy.py @@ -0,0 +1,235 @@ +""" +U-NO on Darcy-Flow +================== + +Training a U-shaped Neural Operator (U-NO) on the small Darcy-Flow example we ship with the package. + +This tutorial demonstrates the U-NO architecture, which combines the resolution invariance +of neural operators with the multi-scale feature extraction of U-Net architectures. +The U-NO uses skip connections and multi-resolution processing to capture both local +and global features in the data, making it particularly effective for complex PDE problems. + +""" + +# %% +# .. raw:: html +# +#
+# +# Import dependencies +# ------------------- +# We import the necessary modules for working with the UNO model + +import torch +import matplotlib.pyplot as plt +import sys +from neuralop.models import UNO +from neuralop import Trainer +from neuralop.training import AdamW +from neuralop.data.datasets import load_darcy_flow_small +from neuralop.utils import count_model_params +from neuralop import LpLoss, H1Loss + +device = "cpu" + + +# %% +# .. raw:: html +# +#
+# +# Loading the Darcy-Flow dataset +# ------------------------------ +# We load the Darcy-Flow dataset for training and testing. + +train_loader, test_loaders, data_processor = load_darcy_flow_small( + n_train=1000, + batch_size=32, + n_tests=[100, 50], + test_resolutions=[16, 32], + test_batch_sizes=[32, 32], +) + +# %% +# .. raw:: html +# +#
+# +# Creating the U-NO model +# ------------------------ +# We create a U-shaped Neural Operator with the following architecture: +# +# - in_channels: Number of input channels +# - out_channels: Number of output channels +# - hidden_channels: Width of the hidden layers +# - uno_out_channels: Channel dimensions for each layer in the U-Net structure +# - uno_n_modes: Fourier modes for each layer (decreasing then increasing) +# - uno_scalings: Scaling factors for each layer + +model = UNO( + in_channels=1, + out_channels=1, + hidden_channels=64, + projection_channels=64, + uno_out_channels=[32, 64, 64, 64, 32], + uno_n_modes=[[8, 8], [8, 8], [4, 4], [8, 8], [8, 8]], + uno_scalings=[[1.0, 1.0], [0.5, 0.5], [1, 1], [2, 2], [1, 1]], + horizontal_skips_map=None, + channel_mlp_skip="linear", + n_layers=5, +) + +model = model.to(device) + +# Count and display the number of parameters +n_params = count_model_params(model) +print(f"\nOur model has {n_params} parameters.") +sys.stdout.flush() + + +# %% +# .. raw:: html +# +#
+# +# Creating the optimizer and scheduler +# ------------------------------------ +# We use AdamW optimizer with weight decay for regularization +optimizer = AdamW(model.parameters(), lr=8e-3, weight_decay=1e-4) +scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=30) + +# %% +# .. raw:: html +# +#
+# +# Setting up loss functions +# ------------------------- +# We use H1 loss for training and L2 loss for evaluation +l2loss = LpLoss(d=2, p=2) +h1loss = H1Loss(d=2) + +train_loss = h1loss +eval_losses = {"h1": h1loss, "l2": l2loss} + + +# %% +# .. raw:: html +# +#
+# +# Displaying configuration +# ------------------------ +# We print the model architecture, optimizer, scheduler, and loss functions + +print("\n### MODEL ###\n", model) +print("\n### OPTIMIZER ###\n", optimizer) +print("\n### SCHEDULER ###\n", scheduler) +print("\n### LOSSES ###") +print(f"\n * Train: {train_loss}") +print(f"\n * Test: {eval_losses}") +sys.stdout.flush() + + +# %% +# .. raw:: html +# +#
+# +# Creating the trainer +# --------------------- +# We create a Trainer object that handles the training loop for the U-NO +trainer = Trainer( + model=model, + n_epochs=30, + device=device, + data_processor=data_processor, + wandb_log=False, # Disable Weights & Biases logging + eval_interval=5, # Evaluate every 5 epochs + use_distributed=False, # Single GPU/CPU training + verbose=True, +) # Print training progress + +# %% +# .. raw:: html +# +#
+# +# Training the U-NO model +# ------------------------ +# We train the model on our Darcy-Flow dataset. The trainer will: +# +# 1. Run the forward pass through the U-NO +# 2. Compute the H1 loss +# 3. Backpropagate and update weights +# 4. Evaluate on test data every 5 epochs + + +trainer.train( + train_loader=train_loader, + test_loaders=test_loaders, + optimizer=optimizer, + scheduler=scheduler, + regularizer=False, + training_loss=train_loss, + eval_losses=eval_losses, +) + + +# %% +# .. raw:: html +# +#
+# +# Visualizing U-NO predictions +# ----------------------------- +# We visualize the model's predictions on the Darcy-Flow dataset. +# Note that we trained on a very small resolution for a very small number of epochs. +# In practice, we would train at larger resolution on many more samples. +# +# However, for practicality, we created a minimal example that: +# i) fits in just a few MB of memory +# ii) can be trained quickly on CPU +# +# In practice we would train a Neural Operator on one or multiple GPUs + +test_samples = test_loaders[32].dataset + +fig = plt.figure(figsize=(7, 7)) +for index in range(3): + data = test_samples[index] + data = data_processor.preprocess(data, batched=False) + # Input x + x = data["x"] + # Ground-truth + y = data["y"] + # Model prediction: U-NO output + out = model(x.unsqueeze(0).to(device)).cpu() + + # Plot input x + ax = fig.add_subplot(3, 3, index * 3 + 1) + ax.imshow(x[0], cmap="gray") + if index == 0: + ax.set_title("Input x") + plt.xticks([], []) + plt.yticks([], []) + + # Plot ground-truth y + ax = fig.add_subplot(3, 3, index * 3 + 2) + ax.imshow(y.squeeze()) + if index == 0: + ax.set_title("Ground-truth y") + plt.xticks([], []) + plt.yticks([], []) + + # Plot model prediction + ax = fig.add_subplot(3, 3, index * 3 + 3) + ax.imshow(out.squeeze().detach().numpy()) + if index == 0: + ax.set_title("U-NO prediction") + plt.xticks([], []) + plt.yticks([], []) + +fig.suptitle("U-NO predictions on 32x32 Darcy-Flow data", y=0.98) +plt.tight_layout() +fig.show() diff --git a/sources/neuraloperator/examples/training/GALLERY_HEADER.rst b/sources/neuraloperator/examples/training/GALLERY_HEADER.rst new file mode 100644 index 0000000000000000000000000000000000000000..37f8bf785875b4b3442ab90c9ded22a1e69528d2 --- /dev/null +++ b/sources/neuraloperator/examples/training/GALLERY_HEADER.rst @@ -0,0 +1,6 @@ +.. _training_examples : + +Training and Meta-Learning Algorithms +------------------------------------- + +Examples to highlight our flexible ``Trainer`` module and the meta-algorithms built on top of it. diff --git a/sources/neuraloperator/examples/training/checkpoint_FNO_darcy.py b/sources/neuraloperator/examples/training/checkpoint_FNO_darcy.py new file mode 100644 index 0000000000000000000000000000000000000000..2e30509f001b1f71c2536fe65a85c8089a692520 --- /dev/null +++ b/sources/neuraloperator/examples/training/checkpoint_FNO_darcy.py @@ -0,0 +1,176 @@ +""" +Checkpointing and loading training states +========================================= + +Demonstrating the ``Trainer``'s saving and loading functionality, +which makes it easy to checkpoint and resume training states. + +""" + +# %% +# .. raw:: html +# +#
+# +# Import dependencies +# ------------------- + +import torch +import matplotlib.pyplot as plt +import sys +from neuralop.models import FNO +from neuralop import Trainer +from neuralop.training import AdamW +from neuralop.data.datasets import load_darcy_flow_small +from neuralop.utils import count_model_params +from neuralop import LpLoss, H1Loss + +device = "cpu" + + +# %% +# .. raw:: html +# +#
+# +# Loading the Darcy-Flow dataset +# ------------------------------ +train_loader, test_loaders, data_processor = load_darcy_flow_small( + n_train=1000, + batch_size=32, + test_resolutions=[16, 32], + n_tests=[100, 50], + test_batch_sizes=[32, 32], +) + + +# %% +# .. raw:: html +# +#
+# +# Creating the FNO model +# ---------------------- + +model = FNO( + n_modes=(16, 16), + in_channels=1, + out_channels=1, + hidden_channels=32, + projection_channel_ratio=2, + factorization="tucker", + rank=0.42, +) + +model = model.to(device) + +n_params = count_model_params(model) +print(f"\nOur model has {n_params} parameters.") +sys.stdout.flush() + + +# %% +# .. raw:: html +# +#
+# +# Creating the optimizer and scheduler +# ------------------------------------ +optimizer = AdamW(model.parameters(), lr=8e-3, weight_decay=1e-4) +scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=30) + + +# %% +# .. raw:: html +# +#
+# +# Creating the losses +# ------------------ +l2loss = LpLoss(d=2, p=2) +h1loss = H1Loss(d=2) + +train_loss = h1loss +eval_losses = {"h1": h1loss, "l2": l2loss} + + +# %% +# .. raw:: html +# +#
+# +# Displaying configuration +# ------------------------ + +print("\n### MODEL ###\n", model) +print("\n### OPTIMIZER ###\n", optimizer) +print("\n### SCHEDULER ###\n", scheduler) +print("\n### LOSSES ###") +print(f"\n * Train: {train_loss}") +print(f"\n * Test: {eval_losses}") +sys.stdout.flush() + + +# %% +# .. raw:: html +# +#
+# +# Creating the trainer +# -------------------- +trainer = Trainer( + model=model, + n_epochs=20, + device=device, + data_processor=data_processor, + wandb_log=False, + eval_interval=3, + use_distributed=False, + verbose=True, +) + + +# %% +# .. raw:: html +# +#
+# +# Training the model +# ------------------ +# We train and save checkpoints + +trainer.train( + train_loader=train_loader, + test_loaders={}, + optimizer=optimizer, + scheduler=scheduler, + regularizer=False, + training_loss=train_loss, + save_every=1, + save_dir="./checkpoints", +) + + +# .. resume_from_dir: +# resume training from saved checkpoint at epoch 10 + +trainer = Trainer( + model=model, + n_epochs=20, + device=device, + data_processor=data_processor, + wandb_log=False, + eval_interval=3, + use_distributed=False, + verbose=True, +) + +trainer.train( + train_loader=train_loader, + test_loaders={}, + optimizer=optimizer, + scheduler=scheduler, + regularizer=False, + training_loss=train_loss, + resume_from_dir="./checkpoints", +) diff --git a/sources/neuraloperator/examples/training/plot_count_flops.py b/sources/neuraloperator/examples/training/plot_count_flops.py new file mode 100644 index 0000000000000000000000000000000000000000..81ca54ade2afffd116158243a8ae0dab29a5d0ab --- /dev/null +++ b/sources/neuraloperator/examples/training/plot_count_flops.py @@ -0,0 +1,117 @@ +""" +Using `torchtnt` to count FLOPS +================================ + +A demo using ``torchtnt`` to estimate the number of floating-point +operations per second (FLOPS) required for a model's forward and backward pass. + +This tutorial demonstrates how to profile neural operator models to understand +their computational requirements. FLOPS counting is crucial for: +- Comparing different model architectures +- Understanding computational bottlenecks +- Optimizing model efficiency +- Making informed decisions about model deployment + +We will use the FLOP computation to analyze the computational resources +used by a FNO model. + +""" + +# %% +# .. raw:: html +# +#
+# +# Import dependencies +# ------------------- +# We import the necessary modules for FLOPS counting and model creation + +from copy import deepcopy +import torch +from torchtnt.utils.flops import FlopTensorDispatchMode + +from neuralop.models import FNO + +device = "cpu" + +# %% +# .. raw:: html +# +#
+# +# Creating the FNO model for analysis +# ------------------------------------ +# We create a moderately-sized FNO model to demonstrate FLOPS counting +fno = FNO( + n_modes=(64, 64), + in_channels=1, + out_channels=1, + hidden_channels=64, + projection_channel_ratio=1, +) + +# Create a sample input tensor for FLOPS counting +batch_size = 4 +model_input = torch.randn(batch_size, 1, 128, 128) + + +# %% +# .. raw:: html +# +#
+# +# Counting FLOPS for forward and backward passes +# ---------------------------------------------- +# We use the FlopTensorDispatchMode to count FLOPS during both forward and backward passes +with FlopTensorDispatchMode(fno) as ftdm: + # Count forward pass FLOPS + res = fno(model_input).mean() + fno_forward_flops = deepcopy(ftdm.flop_counts) + + # Reset the counter and count backward pass FLOPS + ftdm.reset() + res.backward() + fno_backward_flops = deepcopy(ftdm.flop_counts) + +# %% +# .. raw:: html +# +#
+# +# Analyzing FLOPS breakdown +# -------------------------- +# The output is organized as a defaultdict object that counts the FLOPS used in each submodule. +# This gives us detailed insight into which parts of the model are computationally expensive. +print("Forward pass FLOPS breakdown:") +print(fno_forward_flops) + +# %% +# .. raw:: html +# +#
+# +# Finding maximum FLOPS usage +# ---------------------------- +# To check the maximum FLOPS used during the forward pass, let's create a recursive function +# to search the nested dictionary structure: +from collections import defaultdict + + +def get_max_flops(flop_count_dict, max_value=0): + for _, value in flop_count_dict.items(): + # If not nested, compare leaf value to max + if isinstance(value, int): + max_value = max(max_value, value) + + # Otherwise compute recursive max value below node + elif isinstance(value, defaultdict): + new_val = get_max_flops(value, max_value) + max_value = max(max_value, new_val) + return max_value + + +print(f"Max FLOPS required for FNO.forward: {get_max_flops(fno_forward_flops)}") +print(f"Max FLOPS required for FNO.backward: {get_max_flops(fno_backward_flops)}") + +# %% +# diff --git a/sources/neuraloperator/examples/training/plot_incremental_FNO_darcy.py b/sources/neuraloperator/examples/training/plot_incremental_FNO_darcy.py new file mode 100644 index 0000000000000000000000000000000000000000..5d3c2cdbf716457558fe8e0f62a6835a4cf307ac --- /dev/null +++ b/sources/neuraloperator/examples/training/plot_incremental_FNO_darcy.py @@ -0,0 +1,286 @@ +""" +Training an FNO with incremental meta-learning +=============================================== +A demo of the Incremental FNO meta-learning algorithm on our small Darcy-Flow dataset. + +This tutorial demonstrates incremental meta-learning for neural operators, which allows +the model to gradually increase its complexity during training. This approach can lead to: + +- Better convergence properties +- More stable training dynamics +- Improved generalization +- Reduced computational requirements during early training + +The incremental approach starts with a small number of Fourier modes and gradually +increases the model capacity as training progresses. +""" + +# %% +# .. raw:: html +# +#
+# +# Import dependencies +# ------------------- +# We import the necessary modules for incremental FNO training + +import torch +import matplotlib.pyplot as plt +import sys +from neuralop.models import FNO +from neuralop.data.datasets import load_darcy_flow_small +from neuralop.utils import count_model_params +from neuralop.training import AdamW +from neuralop.training.incremental import IncrementalFNOTrainer +from neuralop.data.transforms.data_processors import IncrementalDataProcessor +from neuralop import LpLoss, H1Loss + +# %% +# .. raw:: html +# +#
+# +# Loading the Darcy-Flow dataset +# ------------------------------ +# We load the Darcy-Flow dataset with multiple resolutions for incremental training. + +train_loader, test_loaders, output_encoder = load_darcy_flow_small( + n_train=100, + batch_size=16, + test_resolutions=[16, 32], + n_tests=[100, 50], + test_batch_sizes=[32, 32], +) + +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + +# %% +# .. raw:: html +# +#
+# +# Configuring incremental training +# -------------------------------- +# We set up the incremental FNO model with a small starting number of modes. +# The model will gradually increase its capacity during training. +# We choose to update the modes using the incremental gradient explained algorithm +incremental = True +if incremental: + starting_modes = (2, 2) # Start with very few modes +else: + starting_modes = (8, 8) # Standard number of modes + +# %% +# .. raw:: html +# +#
+# +# Creating the incremental FNO model +# ---------------------------------- +# We create an FNO model with a maximum number of modes that can be reached +# during incremental training. The model starts with fewer modes and grows. +model = FNO( + max_n_modes=(8, 8), # Maximum modes the model can reach + n_modes=starting_modes, # Starting number of modes + hidden_channels=32, + in_channels=1, + out_channels=1, +) +model = model.to(device) +n_params = count_model_params(model) + +# %% +# .. raw:: html +# +#
+# +# Setting up the optimizer and scheduler +# ------------------------------------- +# We use AdamW optimizer with weight decay for regularization +optimizer = AdamW(model.parameters(), lr=8e-3, weight_decay=1e-4) +scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=30) + +# %% +# .. raw:: html +# +#
+# +# Configuring incremental data processing +# --------------------------------------- +# If one wants to use Incremental Resolution, one should use the IncrementalDataProcessor. +# When passed to the trainer, the trainer will automatically update the resolution. +# +# Key parameters for incremental resolution: +# +# - incremental_resolution: bool, default is False. If True, increase the resolution of the input incrementally +# - incremental_res_gap: parameter for resolution updates +# - subsampling_rates: a list of resolutions to use +# - dataset_indices: a list of indices of the dataset to slice to regularize the input resolution +# - dataset_resolution: the resolution of the input +# - epoch_gap: the number of epochs to wait before increasing the resolution +# - verbose: if True, print the resolution and the number of modes + +data_transform = IncrementalDataProcessor( + in_normalizer=None, + out_normalizer=None, + device=device, + subsampling_rates=[2, 1], # Resolution scaling factors + dataset_resolution=16, # Base resolution + dataset_indices=[2, 3], # Dataset indices for regularization + epoch_gap=10, # Epochs between resolution updates + verbose=True, # Print progress information +) + +data_transform = data_transform.to(device) +# %% +# .. raw:: html +# +#
+# +# Setting up loss functions +# ------------------------- +# We use H1 loss for training and L2 loss for evaluation +l2loss = LpLoss(d=2, p=2) +h1loss = H1Loss(d=2) +train_loss = h1loss +eval_losses = {"h1": h1loss, "l2": l2loss} + +# %% +# .. raw:: html +# +#
+# +# Displaying training configuration +# --------------------------------- +# We display the model parameters, optimizer, scheduler, and loss functions +# to verify our incremental training setup +print("\n### N PARAMS ###\n", n_params) +print("\n### OPTIMIZER ###\n", optimizer) +print("\n### SCHEDULER ###\n", scheduler) +print("\n### LOSSES ###") +print("\n### INCREMENTAL RESOLUTION + GRADIENT EXPLAINED ###") +print(f"\n * Train: {train_loss}") +print(f"\n * Test: {eval_losses}") +sys.stdout.flush() + +# %% +# .. raw:: html +# +#
+# +# Configuring the IncrementalFNOTrainer +# -------------------------------------- +# We set up the IncrementalFNOTrainer with various incremental learning options. +# Other options include setting incremental_loss_gap = True. +# If one wants to use incremental resolution, set it to True. +# In this example we only update the modes and not the resolution. +# When using incremental resolution, keep in mind that the number of modes +# initially set should be strictly less than the resolution. +# +# Key parameters for incremental training: +# +# - incremental_grad: bool, default is False. If True, use the base incremental algorithm based on gradient variance +# - incremental_grad_eps: threshold for gradient variance +# - incremental_buffer: number of buffer modes to calculate gradient variance +# - incremental_max_iter: initial number of iterations +# - incremental_grad_max_iter: maximum iterations to accumulate gradients +# - incremental_loss_gap: bool, default is False. If True, use the incremental algorithm based on loss gap +# - incremental_loss_eps: threshold for loss gap + +# Create the IncrementalFNOTrainer with our configuration +trainer = IncrementalFNOTrainer( + model=model, + n_epochs=20, + data_processor=data_transform, + device=device, + verbose=True, + incremental_loss_gap=False, # Use gradient-based incremental learning + incremental_grad=True, # Enable gradient-based mode updates + incremental_grad_eps=0.9999, # Gradient variance threshold + incremental_loss_eps=0.001, # Loss gap threshold + incremental_buffer=5, # Buffer modes for gradient calculation + incremental_max_iter=1, # Initial iterations + incremental_grad_max_iter=2, # Maximum gradient accumulation iterations +) + +# %% +# .. raw:: html +# +#
+# +# Training the incremental FNO model +# ---------------------------------- +# We train the model using incremental meta-learning. The trainer will: +# 1. Start with a small number of Fourier modes +# 2. Gradually increase the model capacity based on gradient variance +# 3. Monitor the incremental learning progress +# 4. Evaluate on test data throughout training + +trainer.train( + train_loader, + test_loaders, + optimizer, + scheduler, + regularizer=False, + training_loss=train_loss, + eval_losses=eval_losses, +) + +# %% +# .. raw:: html +# +#
+# +# Visualizing incremental FNO predictions +# ---------------------------------------- +# We visualize the model's predictions after incremental training. +# Note that we trained on a very small resolution for a very small number of epochs. +# In practice, we would train at larger resolution on many more samples. +# +# However, for practicality, we created a minimal example that: +# i) fits in just a few MB of memory +# ii) can be trained quickly on CPU +# +# In practice we would train a Neural Operator on one or multiple GPUs + +test_samples = test_loaders[32].dataset + +fig = plt.figure(figsize=(7, 7)) +for index in range(3): + data = test_samples[index] + # Input x + x = data["x"].to(device) + # Ground-truth + y = data["y"].to(device) + # Model prediction: incremental FNO output + out = model(x.unsqueeze(0)) + + # Plot input x + ax = fig.add_subplot(3, 3, index * 3 + 1) + x = x.cpu().squeeze().detach().numpy() + y = y.cpu().squeeze().detach().numpy() + ax.imshow(x, cmap="gray") + if index == 0: + ax.set_title("Input x") + plt.xticks([], []) + plt.yticks([], []) + + # Plot ground-truth y + ax = fig.add_subplot(3, 3, index * 3 + 2) + ax.imshow(y.squeeze()) + if index == 0: + ax.set_title("Ground-truth y") + plt.xticks([], []) + plt.yticks([], []) + + # Plot model prediction + ax = fig.add_subplot(3, 3, index * 3 + 3) + ax.imshow(out.cpu().squeeze().detach().numpy()) + if index == 0: + ax.set_title("Incremental FNO prediction") + plt.xticks([], []) + plt.yticks([], []) + +fig.suptitle("Incremental FNO predictions on Darcy-Flow data", y=0.98) +plt.tight_layout() +fig.show() diff --git a/sources/neuraloperator/examples/training/plot_tensorgrad_fno_darcy.py b/sources/neuraloperator/examples/training/plot_tensorgrad_fno_darcy.py new file mode 100644 index 0000000000000000000000000000000000000000..3326df3608f4c1ffd7ba5f88a9955f08a663ea64 --- /dev/null +++ b/sources/neuraloperator/examples/training/plot_tensorgrad_fno_darcy.py @@ -0,0 +1,467 @@ +""" +Training an FNO with TensorGRaD +============================== + +This example compares three optimizers on Darcy-Flow: + +- AdamW baseline +- TensorGRaD low-rank gradients with a 25% budget +- TensorGRaD low-rank + sparse residual gradients with a matched 20% + 5% + budget + +The example follows the standard FNO Darcy workflow while using +``DarcyDataset(download=True)`` so it does not rely on repository-local data. +It records train H1, validation H1, and validation L2 losses for all three +methods and visualizes their predictions side by side. +""" + +# sphinx_gallery_thumbnail_number = 2 + +# %% +# .. raw:: html +# +#
+# +# Import dependencies +# ------------------- + +from pathlib import Path +import sys + +for path in [Path.cwd(), *Path.cwd().parents]: + if (path / "neuralop" / "__init__.py").exists(): + repo_root = path + break +else: + repo_root = None + +if repo_root is not None and str(repo_root) not in sys.path: + sys.path.insert(0, str(repo_root)) + +import matplotlib.pyplot as plt +import numpy as np +import torch +from torch.utils.data import DataLoader + +from neuralop import H1Loss, LpLoss, Trainer +from neuralop.data.datasets.darcy import DarcyDataset +from neuralop.models import FNO +from neuralop.training import ( + AdamW as BaselineAdamW, + TensorGRaD, + fno_tensorgrad_param_groups, +) +from neuralop.utils import count_model_params + +plt.rcParams["figure.dpi"] = 110 + + +# %% +# .. raw:: html +# +#
+# +# Configuration +# ------------- +# TensorGRaD is applied to the spectral convolution weights. Other FNO +# parameters, such as lifting/projection layers and skip connections, remain in +# a regular AdamW parameter group. + +N_TRAIN = 1000 +N_TEST = 100 +BATCH_SIZE = 128 +N_EPOCHS = 15 +LEARNING_RATE = 1e-2 +WEIGHT_DECAY = 1e-4 +HIDDEN_CHANNELS = 24 +N_MODES = (8, 8) +UPDATE_PROJ_GAP = 4 +LOW_RANK_SCALE = 10.0 +SPARSE_SCALE = 1.0 +LAMBDA_SPARSE = 1.0 +SPARSE_TYPE = "randk" + +LOW_RANK_BUDGET = 0.25 +LOW_RANK_SPARSE_LOW_RANK_BUDGET = 0.20 +LOW_RANK_SPARSE_SPARSE_BUDGET = 0.05 +assert abs( + LOW_RANK_BUDGET + - (LOW_RANK_SPARSE_LOW_RANK_BUDGET + LOW_RANK_SPARSE_SPARSE_BUDGET) +) < 1e-12 + +DATA_ROOT = Path.home() / ".cache" / "neuraloperator" / "darcy" +TEST_RESOLUTIONS = [16, 32] +TEST_BATCH_SIZES = [BATCH_SIZE, BATCH_SIZE] + +torch.manual_seed(0) +np.random.seed(0) +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") +print(f"Using device: {device}") + + +# %% +# .. raw:: html +# +#
+# +# Loading the Darcy-Flow dataset +# ------------------------------ +# ``DarcyDataset(download=True)`` downloads the public Darcy files from Zenodo +# if they are not already present in ``DATA_ROOT``. + +darcy_dataset = DarcyDataset( + root_dir=DATA_ROOT, + n_train=N_TRAIN, + n_tests=[N_TEST, N_TEST], + batch_size=BATCH_SIZE, + test_batch_sizes=TEST_BATCH_SIZES, + train_resolution=16, + test_resolutions=TEST_RESOLUTIONS, + encode_input=False, + encode_output=True, + download=True, +) + +train_loader = DataLoader( + darcy_dataset.train_db, + batch_size=BATCH_SIZE, + shuffle=True, + num_workers=0, + pin_memory=torch.cuda.is_available(), +) +test_loaders = { + resolution: DataLoader( + darcy_dataset.test_dbs[resolution], + batch_size=batch_size, + shuffle=False, + num_workers=0, + pin_memory=torch.cuda.is_available(), + ) + for resolution, batch_size in zip(TEST_RESOLUTIONS, TEST_BATCH_SIZES) +} +data_processor = darcy_dataset.data_processor.to(device) +print(f"Loaded Darcy-Flow test resolutions: {list(test_loaders)}") + + +# %% +# .. raw:: html +# +#
+# +# Creating the FNO model +# ---------------------- + + +def make_model(): + torch.manual_seed(0) + return FNO( + n_modes=N_MODES, + in_channels=1, + out_channels=1, + hidden_channels=HIDDEN_CHANNELS, + projection_channel_ratio=2, + ).to(device) + + +preview_model = make_model() +print(f"FNO parameters: {count_model_params(preview_model):,}") +del preview_model + + +# %% +# .. raw:: html +# +#
+# +# Creating the optimizers +# ----------------------- +# The compressed-gradient budgets are matched: low-rank uses a 25% budget, and +# low-rank+sparse uses a 20% low-rank budget plus a 5% sparse residual budget. + + +def adamw_optimizer(model): + return BaselineAdamW( + model.parameters(), + lr=LEARNING_RATE, + weight_decay=WEIGHT_DECAY, + ) + + +def tensorgrad_low_rank_optimizer(model): + param_groups = fno_tensorgrad_param_groups( + model, + rank=LOW_RANK_BUDGET, + min_params=1000, + update_proj_gap=UPDATE_PROJ_GAP, + scale=LOW_RANK_SCALE, + ) + return TensorGRaD(param_groups, lr=LEARNING_RATE, weight_decay=WEIGHT_DECAY) + + +def tensorgrad_low_rank_sparse_optimizer(model): + param_groups = fno_tensorgrad_param_groups( + model, + rank=LOW_RANK_SPARSE_LOW_RANK_BUDGET, + sparse_ratio=LOW_RANK_SPARSE_SPARSE_BUDGET, + min_params=1000, + update_proj_gap=UPDATE_PROJ_GAP, + scale=LOW_RANK_SCALE, + sparse_scale=SPARSE_SCALE, + sparse_type=SPARSE_TYPE, + lambda_sparse=LAMBDA_SPARSE, + ) + return TensorGRaD(param_groups, lr=LEARNING_RATE, weight_decay=WEIGHT_DECAY) + + +print(f"Low-rank budget: {LOW_RANK_BUDGET:.0%}") +print( + "Low-rank + sparse budget: " + f"{LOW_RANK_SPARSE_LOW_RANK_BUDGET:.0%} + " + f"{LOW_RANK_SPARSE_SPARSE_BUDGET:.0%} = " + f"{LOW_RANK_BUDGET:.0%}" +) + + +# %% +# .. raw:: html +# +#
+# +# Setting up losses +# ----------------- + +l2loss = LpLoss(d=2, p=2) +h1loss = H1Loss(d=2) + +train_loss = h1loss +eval_losses = {"h1": h1loss, "l2": l2loss} + + +# %% +# .. raw:: html +# +#
+# +# Training all three models +# ------------------------- +# We subclass ``Trainer`` only to store epoch-wise train and validation metrics +# so we can plot all three methods on the same axes. + + +def to_float(value): + if torch.is_tensor(value): + return float(value.detach().cpu()) + if value is None: + return None + return float(value) + + +class HistoryTrainer(Trainer): + def train_one_epoch(self, epoch, train_loader, training_loss): + train_err, avg_loss, avg_lasso_loss, epoch_train_time = super().train_one_epoch( + epoch, + train_loader, + training_loss, + ) + self._latest_history_row = { + "epoch": epoch, + "step": (epoch + 1) * len(train_loader), + "train_err": to_float(train_err), + "avg_loss": to_float(avg_loss), + "epoch_train_time": to_float(epoch_train_time), + } + return train_err, avg_loss, avg_lasso_loss, epoch_train_time + + def evaluate_all( + self, + epoch, + eval_losses, + test_loaders, + eval_modes, + max_autoregressive_steps=None, + ): + eval_metrics = super().evaluate_all( + epoch=epoch, + eval_losses=eval_losses, + test_loaders=test_loaders, + eval_modes=eval_modes, + max_autoregressive_steps=max_autoregressive_steps, + ) + row = dict(getattr(self, "_latest_history_row", {"epoch": epoch})) + row.update({key: to_float(value) for key, value in eval_metrics.items()}) + self.history.append(row) + return eval_metrics + + +def train_with_optimizer(name, optimizer_builder): + torch.manual_seed(0) + np.random.seed(0) + model = make_model() + optimizer = optimizer_builder(model) + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=N_EPOCHS) + + print(f"\n### {name} ###") + print(f"Optimizer: {optimizer.__class__.__name__}") + + trainer = HistoryTrainer( + model=model, + n_epochs=N_EPOCHS, + device=device, + data_processor=data_processor, + wandb_log=False, + eval_interval=1, + use_distributed=False, + verbose=True, + ) + trainer.history = [] + trainer.train( + train_loader=train_loader, + test_loaders=test_loaders, + optimizer=optimizer, + scheduler=scheduler, + regularizer=False, + training_loss=train_loss, + eval_losses=eval_losses, + ) + return model, trainer.history + + +optimizer_builders = { + "AdamW": adamw_optimizer, + "Low-rank 25%": tensorgrad_low_rank_optimizer, + "Low-rank 20% + sparse 5%": tensorgrad_low_rank_sparse_optimizer, +} + +models = {} +histories = {} +for name, optimizer_builder in optimizer_builders.items(): + models[name], histories[name] = train_with_optimizer(name, optimizer_builder) + + +# %% +# .. raw:: html +# +#
+# +# Reporting best validation losses +# -------------------------------- + +plot_resolution = max(test_loaders) +eval_h1_key = f"{plot_resolution}_h1" +eval_l2_key = f"{plot_resolution}_l2" + + +def best_metric(history, key): + best_row = min(history, key=lambda row: row[key]) + return best_row[key], best_row["step"] + + +summary_rows = [] +for name, history in histories.items(): + best_h1, best_h1_step = best_metric(history, eval_h1_key) + best_l2, best_l2_step = best_metric(history, eval_l2_key) + summary_rows.append( + { + "method": name, + "best_val_h1": best_h1, + "best_val_h1_step": best_h1_step, + "best_val_l2": best_l2, + "best_val_l2_step": best_l2_step, + } + ) + +header = ( + f"{'method':<28} {'best_h1':>12} {'h1_step':>8} " + f"{'best_l2':>12} {'l2_step':>8}" +) +summary_lines = [header, "-" * len(header)] +for row in summary_rows: + summary_lines.append( + f"{row['method']:<28} " + f"{row['best_val_h1']:>12.5g} " + f"{row['best_val_h1_step']:>8} " + f"{row['best_val_l2']:>12.5g} " + f"{row['best_val_l2_step']:>8}" + ) + +summary_text = "\n".join(summary_lines) +print(summary_text) + + +# %% +# .. raw:: html +# +#
+# +# Loss curves +# ----------- +# All panels use optimizer steps on the x-axis. Validation H1 and L2 are shown +# at the highest test resolution. + +fig, axes = plt.subplots(1, 3, figsize=(15, 4)) +for name, history in histories.items(): + steps = [row["step"] for row in history] + axes[0].plot(steps, [row["avg_loss"] for row in history], marker="o", label=name) + axes[1].plot(steps, [row[eval_h1_key] for row in history], marker="o", label=name) + axes[2].plot(steps, [row[eval_l2_key] for row in history], marker="o", label=name) + +axes[0].set_title("Train H1 loss") +axes[1].set_title(f"Validation H1 loss ({plot_resolution} x {plot_resolution})") +axes[2].set_title(f"Validation L2 loss ({plot_resolution} x {plot_resolution})") + +for ax in axes: + ax.set_xlabel("Optimizer step") + ax.set_ylabel("Loss") + ax.grid(True, alpha=0.3) + ax.legend() + +plt.tight_layout() +fig.show() + + +# %% +# .. raw:: html +# +#
+# +# Visualizing predictions +# ----------------------- +# The columns compare the input, ground truth, AdamW prediction, low-rank +# prediction, and low-rank+sparse prediction. + +test_samples = test_loaders[plot_resolution].dataset +prediction_labels = ["AdamW", "Low-rank 25%", "Low-rank 20% + sparse 5%"] + +fig = plt.figure(figsize=(12, 7)) +for index in range(3): + data = test_samples[index] + data = data_processor.preprocess(data, batched=False) + + x = data["x"].to(device) + y = data["y"].to(device) + + with torch.no_grad(): + predictions = { + label: models[label](x.unsqueeze(0)).squeeze().detach().cpu() + for label in prediction_labels + } + + panels = [ + ("Input x", x[0].detach().cpu(), "gray"), + ("Ground truth y", y.squeeze().detach().cpu(), None), + *[(label, predictions[label], None) for label in prediction_labels], + ] + for column, (title, image, cmap) in enumerate(panels): + ax = fig.add_subplot(3, 5, index * 5 + column + 1) + ax.imshow(image, cmap=cmap) + if index == 0: + ax.set_title(title) + ax.set_xticks([]) + ax.set_yticks([]) + +fig.suptitle( + f"Darcy-Flow FNO predictions at {plot_resolution} x {plot_resolution}", + y=0.98, +) +plt.tight_layout() +fig.show() diff --git a/sources/neuraloperator/examples/training/tensorgrad_fno.ipynb b/sources/neuraloperator/examples/training/tensorgrad_fno.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9a63b688c18d13e1099cf9f2be9f57c8dea718ef --- /dev/null +++ b/sources/neuraloperator/examples/training/tensorgrad_fno.ipynb @@ -0,0 +1,648 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Training FNOs on Darcy-Flow with TensorGRaD\n", + "\n", + "This notebook follows the same basic workflow as the NeuralOperator Darcy FNO example: load Darcy-Flow data, build an FNO, set up losses and optimizers, train, and visualize results.\n", + "\n", + "We compare three optimizers:\n", + "\n", + "- AdamW baseline;\n", + "- TensorGRaD low-rank gradients with a 25% budget;\n", + "- TensorGRaD low-rank + sparse gradients with a matched 20% + 5% budget." + ] + }, + { + "cell_type": "markdown", + "id": "9b091cfa", + "metadata": {}, + "source": [ + "## Import dependencies\n", + "\n", + "The path setup below makes sure this notebook uses the local NeuralOperator checkout when run from the repository.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "99c8fd8b", + "metadata": {}, + "outputs": [], + "source": [ + "from pathlib import Path\n", + "import sys\n", + "\n", + "\n", + "for path in [Path.cwd(), *Path.cwd().parents]:\n", + " if (path / \"neuralop\" / \"__init__.py\").exists():\n", + " repo_root = path\n", + " break\n", + "else:\n", + " repo_root = None\n", + "\n", + "if repo_root is not None and str(repo_root) not in sys.path:\n", + " sys.path.insert(0, str(repo_root))\n", + "\n", + "print(f\"NeuralOperator root: {repo_root if repo_root is not None else 'installed package'}\")\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "077ff79b", + "metadata": {}, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "import torch\n", + "from torch.utils.data import DataLoader\n", + "\n", + "from neuralop import H1Loss, LpLoss, Trainer\n", + "from neuralop.data.datasets.darcy import DarcyDataset\n", + "from neuralop.models import FNO\n", + "from neuralop.training import AdamW as BaselineAdamW, TensorGRaD, fno_tensorgrad_param_groups\n", + "from neuralop.utils import count_model_params\n", + "\n", + "\n", + "plt.rcParams[\"figure.dpi\"] = 110" + ] + }, + { + "cell_type": "markdown", + "id": "5534322b", + "metadata": {}, + "source": [ + "## Configuration" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9ed22ed6", + "metadata": {}, + "outputs": [], + "source": [ + "N_TRAIN = 1000\n", + "N_TEST = 100\n", + "BATCH_SIZE = 128\n", + "N_EPOCHS = 15\n", + "LEARNING_RATE = 1e-2\n", + "WEIGHT_DECAY = 1e-4\n", + "HIDDEN_CHANNELS = 24\n", + "N_MODES = (8, 8)\n", + "UPDATE_PROJ_GAP = 4\n", + "LOW_RANK_SCALE = 10.0\n", + "SPARSE_SCALE = 1\n", + "LAMBDA_SPARSE = 1\n", + "SPARSE_TYPE = \"randk\"\n", + "\n", + "LOW_RANK_BUDGET = 0.25\n", + "LOW_RANK_SPARSE_LOW_RANK_BUDGET = 0.20\n", + "LOW_RANK_SPARSE_SPARSE_BUDGET = 0.05\n", + "assert abs(LOW_RANK_BUDGET - (LOW_RANK_SPARSE_LOW_RANK_BUDGET + LOW_RANK_SPARSE_SPARSE_BUDGET)) < 1e-12\n", + "\n", + "DATA_ROOT = Path.home() / \".cache\" / \"neuraloperator\" / \"darcy\"\n", + "TEST_RESOLUTIONS = [16, 32]\n", + "TEST_BATCH_SIZES = [BATCH_SIZE, BATCH_SIZE]\n", + "\n", + "torch.manual_seed(0)\n", + "np.random.seed(0)\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "device" + ] + }, + { + "cell_type": "markdown", + "id": "1c5d817d", + "metadata": {}, + "source": [ + "## Loading the Darcy-Flow dataset\n", + "\n", + "`DarcyDataset(download=True)` downloads the public Darcy files from Zenodo if they are not already present in `DATA_ROOT`. This keeps the example independent of any local repository data.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e4376360", + "metadata": {}, + "outputs": [], + "source": [ + "darcy_dataset = DarcyDataset(\n", + " root_dir=DATA_ROOT,\n", + " n_train=N_TRAIN,\n", + " n_tests=[N_TEST, N_TEST],\n", + " batch_size=BATCH_SIZE,\n", + " test_batch_sizes=TEST_BATCH_SIZES,\n", + " train_resolution=16,\n", + " test_resolutions=TEST_RESOLUTIONS,\n", + " encode_input=False,\n", + " encode_output=True,\n", + " download=True,\n", + ")\n", + "\n", + "train_loader = DataLoader(\n", + " darcy_dataset.train_db,\n", + " batch_size=BATCH_SIZE,\n", + " shuffle=True,\n", + " num_workers=0,\n", + " pin_memory=torch.cuda.is_available(),\n", + ")\n", + "test_loaders = {\n", + " resolution: DataLoader(\n", + " darcy_dataset.test_dbs[resolution],\n", + " batch_size=batch_size,\n", + " shuffle=False,\n", + " num_workers=0,\n", + " pin_memory=torch.cuda.is_available(),\n", + " )\n", + " for resolution, batch_size in zip(TEST_RESOLUTIONS, TEST_BATCH_SIZES)\n", + "}\n", + "data_processor = darcy_dataset.data_processor.to(device)\n", + "print(f\"Loaded Darcy-Flow test resolutions: {list(test_loaders)}\")\n" + ] + }, + { + "cell_type": "markdown", + "id": "f15c6713", + "metadata": {}, + "source": [ + "## Creating the FNO model" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "db1d082c", + "metadata": {}, + "outputs": [], + "source": [ + "def make_model():\n", + " torch.manual_seed(0)\n", + " return FNO(\n", + " n_modes=N_MODES,\n", + " in_channels=1,\n", + " out_channels=1,\n", + " hidden_channels=HIDDEN_CHANNELS,\n", + " projection_channel_ratio=2,\n", + " ).to(device)\n", + "\n", + "\n", + "preview_model = make_model()\n", + "print(f\"FNO parameters: {count_model_params(preview_model):,}\")\n", + "del preview_model" + ] + }, + { + "cell_type": "markdown", + "id": "8a4b06dd", + "metadata": {}, + "source": [ + "## Creating the optimizers\n", + "\n", + "TensorGRaD is applied to the FNO spectral convolution weights. Other parameters, such as lifting/projection layers and skip connections, stay in a normal AdamW group.\n", + "\n", + "The compressed-gradient budgets are matched:\n", + "\n", + "- low-rank only: 25%;\n", + "- low-rank + sparse residual: 20% low-rank + 5% sparse.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a35aa540", + "metadata": {}, + "outputs": [], + "source": [ + "def adamw_optimizer(model):\n", + " return BaselineAdamW(\n", + " model.parameters(),\n", + " lr=LEARNING_RATE,\n", + " weight_decay=WEIGHT_DECAY,\n", + " )\n", + "\n", + "\n", + "def tensorgrad_low_rank_optimizer(model):\n", + " param_groups = fno_tensorgrad_param_groups(\n", + " model,\n", + " rank=LOW_RANK_BUDGET,\n", + " min_params=1000,\n", + " update_proj_gap=UPDATE_PROJ_GAP,\n", + " scale=LOW_RANK_SCALE,\n", + " )\n", + " return TensorGRaD(param_groups, lr=LEARNING_RATE, weight_decay=WEIGHT_DECAY)\n", + "\n", + "\n", + "def tensorgrad_low_rank_sparse_optimizer(model):\n", + " param_groups = fno_tensorgrad_param_groups(\n", + " model,\n", + " rank=LOW_RANK_SPARSE_LOW_RANK_BUDGET,\n", + " sparse_ratio=LOW_RANK_SPARSE_SPARSE_BUDGET,\n", + " min_params=1000,\n", + " update_proj_gap=UPDATE_PROJ_GAP,\n", + " scale=LOW_RANK_SCALE,\n", + " sparse_scale=SPARSE_SCALE,\n", + " sparse_type=SPARSE_TYPE,\n", + " lambda_sparse=LAMBDA_SPARSE,\n", + " )\n", + " return TensorGRaD(param_groups, lr=LEARNING_RATE, weight_decay=WEIGHT_DECAY)\n", + "\n", + "\n", + "print(f\"Low-rank budget: {LOW_RANK_BUDGET:.0%}\")\n", + "print(\n", + " \"Low-rank + sparse budget: \"\n", + " f\"{LOW_RANK_SPARSE_LOW_RANK_BUDGET:.0%} + \"\n", + " f\"{LOW_RANK_SPARSE_SPARSE_BUDGET:.0%} = \"\n", + " f\"{LOW_RANK_BUDGET:.0%}\"\n", + ")\n" + ] + }, + { + "cell_type": "markdown", + "id": "a450953d", + "metadata": {}, + "source": [ + "## Setting up losses" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "35842b76", + "metadata": {}, + "outputs": [], + "source": [ + "l2loss = LpLoss(d=2, p=2)\n", + "h1loss = H1Loss(d=2)\n", + "\n", + "train_loss = h1loss\n", + "eval_losses = {\"h1\": h1loss, \"l2\": l2loss}" + ] + }, + { + "cell_type": "markdown", + "id": "373074ad", + "metadata": {}, + "source": [ + "## Training all three models" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b4f40e55", + "metadata": {}, + "outputs": [], + "source": [ + "def to_float(value):\n", + " if torch.is_tensor(value):\n", + " return float(value.detach().cpu())\n", + " if value is None:\n", + " return None\n", + " return float(value)\n", + "\n", + "\n", + "class HistoryTrainer(Trainer):\n", + " def train_one_epoch(self, epoch, train_loader, training_loss):\n", + " train_err, avg_loss, avg_lasso_loss, epoch_train_time = super().train_one_epoch(\n", + " epoch,\n", + " train_loader,\n", + " training_loss,\n", + " )\n", + " self._latest_history_row = {\n", + " \"epoch\": epoch,\n", + " \"step\": (epoch + 1) * len(train_loader),\n", + " \"train_err\": to_float(train_err),\n", + " \"avg_loss\": to_float(avg_loss),\n", + " \"epoch_train_time\": to_float(epoch_train_time),\n", + " }\n", + " return train_err, avg_loss, avg_lasso_loss, epoch_train_time\n", + "\n", + " def evaluate_all(\n", + " self,\n", + " epoch,\n", + " eval_losses,\n", + " test_loaders,\n", + " eval_modes,\n", + " max_autoregressive_steps=None,\n", + " ):\n", + " eval_metrics = super().evaluate_all(\n", + " epoch=epoch,\n", + " eval_losses=eval_losses,\n", + " test_loaders=test_loaders,\n", + " eval_modes=eval_modes,\n", + " max_autoregressive_steps=max_autoregressive_steps,\n", + " )\n", + " row = dict(getattr(self, \"_latest_history_row\", {\"epoch\": epoch}))\n", + " row.update({key: to_float(value) for key, value in eval_metrics.items()})\n", + " self.history.append(row)\n", + " return eval_metrics\n", + "\n", + "\n", + "def train_with_optimizer(name, optimizer_builder):\n", + " torch.manual_seed(0)\n", + " np.random.seed(0)\n", + " model = make_model()\n", + " optimizer = optimizer_builder(model)\n", + " scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=N_EPOCHS)\n", + "\n", + " print(f\"\\n### {name} ###\")\n", + " print(f\"Optimizer: {optimizer.__class__.__name__}\")\n", + "\n", + " trainer = HistoryTrainer(\n", + " model=model,\n", + " n_epochs=N_EPOCHS,\n", + " device=device,\n", + " data_processor=data_processor,\n", + " wandb_log=False,\n", + " eval_interval=1,\n", + " use_distributed=False,\n", + " verbose=True,\n", + " )\n", + " trainer.history = []\n", + " trainer.train(\n", + " train_loader=train_loader,\n", + " test_loaders=test_loaders,\n", + " optimizer=optimizer,\n", + " scheduler=scheduler,\n", + " regularizer=False,\n", + " training_loss=train_loss,\n", + " eval_losses=eval_losses,\n", + " )\n", + " return model, trainer.history\n", + "\n", + "\n", + "optimizer_builders = {\n", + " \"AdamW\": adamw_optimizer,\n", + " \"Low-rank 25%\": tensorgrad_low_rank_optimizer,\n", + " \"Low-rank 20% + sparse 5%\": tensorgrad_low_rank_sparse_optimizer,\n", + "}\n", + "\n", + "models = {}\n", + "histories = {}\n", + "for name, optimizer_builder in optimizer_builders.items():\n", + " models[name], histories[name] = train_with_optimizer(name, optimizer_builder)\n" + ] + }, + { + "cell_type": "markdown", + "id": "c928f2e1", + "metadata": {}, + "source": [ + "## Loss curves\n", + "\n", + "All panels use optimizer steps on the x-axis. Validation H1 and L2 are shown at the 32 x 32 test resolution." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7fec4a3f", + "metadata": {}, + "outputs": [], + "source": [ + "plot_resolution = max(test_loaders)\n", + "eval_h1_key = f\"{plot_resolution}_h1\"\n", + "eval_l2_key = f\"{plot_resolution}_l2\"\n", + "\n", + "fig, axes = plt.subplots(1, 3, figsize=(15, 4))\n", + "for name, history in histories.items():\n", + " steps = [row[\"step\"] for row in history]\n", + " axes[0].plot(steps, [row[\"avg_loss\"] for row in history], marker=\"o\", label=name)\n", + " axes[1].plot(steps, [row[eval_h1_key] for row in history], marker=\"o\", label=name)\n", + " axes[2].plot(steps, [row[eval_l2_key] for row in history], marker=\"o\", label=name)\n", + "\n", + "axes[0].set_title(\"Train H1 loss\")\n", + "axes[1].set_title(f\"Validation H1 loss ({plot_resolution} x {plot_resolution})\")\n", + "axes[2].set_title(f\"Validation L2 loss ({plot_resolution} x {plot_resolution})\")\n", + "\n", + "for ax in axes:\n", + " ax.set_xlabel(\"Optimizer step\")\n", + " ax.set_ylabel(\"Loss\")\n", + " ax.grid(True, alpha=0.3)\n", + " ax.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "d6032898", + "metadata": {}, + "source": [ + "## Visualizing predictions\n", + "\n", + "The columns compare the input, ground truth, AdamW prediction, low-rank prediction, and low-rank + sparse prediction at the 32 x 32 test resolution." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3013fe1b", + "metadata": {}, + "outputs": [], + "source": [ + "plot_resolution = max(test_loaders)\n", + "test_samples = test_loaders[plot_resolution].dataset\n", + "prediction_labels = [\"AdamW\", \"Low-rank 25%\", \"Low-rank 20% + sparse 5%\"]\n", + "\n", + "fig = plt.figure(figsize=(12, 7))\n", + "for index in range(3):\n", + " data = test_samples[index]\n", + " data = data_processor.preprocess(data, batched=False)\n", + "\n", + " x = data[\"x\"].to(device)\n", + " y = data[\"y\"].to(device)\n", + "\n", + " with torch.no_grad():\n", + " predictions = {\n", + " label: models[label](x.unsqueeze(0)).squeeze().detach().cpu()\n", + " for label in prediction_labels\n", + " }\n", + "\n", + " panels = [\n", + " (\"Input x\", x[0].detach().cpu(), \"gray\"),\n", + " (\"Ground truth y\", y.squeeze().detach().cpu(), None),\n", + " *[(label, predictions[label], None) for label in prediction_labels],\n", + " ]\n", + " for column, (title, image, cmap) in enumerate(panels):\n", + " ax = fig.add_subplot(3, 5, index * 5 + column + 1)\n", + " ax.imshow(image, cmap=cmap)\n", + " if index == 0:\n", + " ax.set_title(title)\n", + " ax.set_xticks([])\n", + " ax.set_yticks([])\n", + "\n", + "fig.suptitle(f\"Darcy-Flow FNO predictions at {plot_resolution} x {plot_resolution}\", y=0.98)\n", + "plt.tight_layout()\n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e55ab8df", + "metadata": {}, + "outputs": [], + "source": [ + "# Optional hyperparameter sweep.\n", + "# AdamW has no projector gap, so it is run once per learning rate.\n", + "# TensorGRaD variants are run for every (learning rate, projector gap, scale) tuple.\n", + "\n", + "SWEEP_LEARNING_RATES = [1e-2, 3e-2]\n", + "SWEEP_PROJECTOR_GAPS = [8]\n", + "SWEEP_SCALES = [10, 5, 1]\n", + "\n", + "plot_resolution = max(test_loaders)\n", + "eval_h1_key = f\"{plot_resolution}_h1\"\n", + "eval_l2_key = f\"{plot_resolution}_l2\"\n", + "\n", + "\n", + "def best_metric(history, key):\n", + " best_row = min(history, key=lambda row: row[key])\n", + " return best_row[key], best_row[\"step\"]\n", + "\n", + "\n", + "def set_projector_gap(projector_gap):\n", + " global UPDATE_PROJ_GAP\n", + " UPDATE_PROJ_GAP = projector_gap\n", + "\n", + "\n", + "def set_projector_scale(scale):\n", + " global LOW_RANK_SCALE\n", + " LOW_RANK_SCALE = scale\n", + "\n", + "\n", + "def run_sweep_case(method_name, optimizer_builder, learning_rate, projector_gap=None, scale=None):\n", + " global LEARNING_RATE\n", + "\n", + " LEARNING_RATE = learning_rate\n", + " if projector_gap is not None:\n", + " set_projector_gap(projector_gap)\n", + " if scale is not None:\n", + " set_projector_scale(scale)\n", + "\n", + " run_name = f\"{method_name} | lr={learning_rate:g}\"\n", + " if projector_gap is not None:\n", + " run_name += f\" | gap={projector_gap}\"\n", + " if scale is not None:\n", + " run_name += f\" | scale={scale:g}\"\n", + "\n", + " model, history = train_with_optimizer(run_name, optimizer_builder)\n", + " best_h1, best_h1_step = best_metric(history, eval_h1_key)\n", + " best_l2, best_l2_step = best_metric(history, eval_l2_key)\n", + "\n", + " del model\n", + " if torch.cuda.is_available():\n", + " torch.cuda.empty_cache()\n", + "\n", + " return {\n", + " \"method\": method_name,\n", + " \"learning_rate\": learning_rate,\n", + " \"projector_gap\": projector_gap,\n", + " \"scale\": scale,\n", + " \"best_val_h1\": best_h1,\n", + " \"best_val_h1_step\": best_h1_step,\n", + " \"best_val_l2\": best_l2,\n", + " \"best_val_l2_step\": best_l2_step,\n", + " }\n", + "\n", + "\n", + "def print_sweep_results(results):\n", + " header = (\n", + " f\"{'method':<28} {'lr':>10} {'gap':>6} {'scale':>8} \"\n", + " f\"{'best_h1':>12} {'h1_step':>8} {'best_l2':>12} {'l2_step':>8}\"\n", + " )\n", + " print(header)\n", + " print(\"-\" * len(header))\n", + " for row in results:\n", + " gap = \"-\" if row[\"projector_gap\"] is None else str(row[\"projector_gap\"])\n", + " scale = \"-\" if row[\"scale\"] is None else f\"{row['scale']:g}\"\n", + " print(\n", + " f\"{row['method']:<28} \"\n", + " f\"{row['learning_rate']:>10.2e} \"\n", + " f\"{gap:>6} \"\n", + " f\"{scale:>8} \"\n", + " f\"{row['best_val_h1']:>12.5g} \"\n", + " f\"{row['best_val_h1_step']:>8} \"\n", + " f\"{row['best_val_l2']:>12.5g} \"\n", + " f\"{row['best_val_l2_step']:>8}\"\n", + " )\n", + "\n", + "\n", + "base_learning_rate = LEARNING_RATE\n", + "base_projector_gap = UPDATE_PROJ_GAP\n", + "base_projector_scale = LOW_RANK_SCALE\n", + "sweep_results = []\n", + "try:\n", + " for learning_rate in SWEEP_LEARNING_RATES:\n", + " sweep_results.append(\n", + " run_sweep_case(\"AdamW\", adamw_optimizer, learning_rate)\n", + " )\n", + "\n", + " for projector_gap in SWEEP_PROJECTOR_GAPS:\n", + " for scale in SWEEP_SCALES:\n", + " sweep_results.append(\n", + " run_sweep_case(\n", + " \"Low-rank 25%\",\n", + " tensorgrad_low_rank_optimizer,\n", + " learning_rate,\n", + " projector_gap,\n", + " scale,\n", + " )\n", + " )\n", + " sweep_results.append(\n", + " run_sweep_case(\n", + " \"Low-rank 20% + sparse 5%\",\n", + " tensorgrad_low_rank_sparse_optimizer,\n", + " learning_rate,\n", + " projector_gap,\n", + " scale,\n", + " )\n", + " )\n", + "finally:\n", + " LEARNING_RATE = base_learning_rate\n", + " set_projector_gap(base_projector_gap)\n", + " set_projector_scale(base_projector_scale)\n", + "\n", + "sweep_results = sorted(\n", + " sweep_results,\n", + " key=lambda row: (\n", + " row[\"method\"],\n", + " row[\"learning_rate\"],\n", + " -1 if row[\"projector_gap\"] is None else row[\"projector_gap\"],\n", + " -1 if row[\"scale\"] is None else row[\"scale\"],\n", + " ),\n", + ")\n", + "print_sweep_results(sweep_results)\n" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "tensorgrad", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.14" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/sources/neuraloperator/neuralop/__init__.py b/sources/neuraloperator/neuralop/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..131b9b028b9511f056ba4613d0aef59039182c97 --- /dev/null +++ b/sources/neuraloperator/neuralop/__init__.py @@ -0,0 +1,19 @@ +__version__ = "2.0.0" + +from .models import TFNO, FNO, RNO, get_model +from .data import datasets, transforms +from . import mpu +from .training import Trainer +from .losses import ( + LpLoss, + H1Loss, + BurgersEqnLoss, + ICLoss, + WeightedSumLoss, + Aggregator, + Relobralo, + SoftAdapt, + FourierDiff, + non_uniform_fd, + FiniteDiff, +) diff --git a/sources/neuraloperator/neuralop/__pycache__/__init__.cpython-313.pyc b/sources/neuraloperator/neuralop/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9be89c465a4fc09746c4a1d9b498b8ac955bfb2a Binary files /dev/null and b/sources/neuraloperator/neuralop/__pycache__/__init__.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/__pycache__/utils.cpython-313.pyc b/sources/neuraloperator/neuralop/__pycache__/utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43417a27d1cb6b1d82d7994f461dbd7d3ec54746 Binary files /dev/null and b/sources/neuraloperator/neuralop/__pycache__/utils.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/data/__init__.py b/sources/neuraloperator/neuralop/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a439d1b1222cfa9dc9f9b4b5526004790fe9517b --- /dev/null +++ b/sources/neuraloperator/neuralop/data/__init__.py @@ -0,0 +1,7 @@ +""" +neuralop.data contains APIs for PDE datasets (.datasets) +and APIs to transform raw data inputs into forms more suited +to training machine learning models (.transforms) +""" +from . import datasets +from . import transforms diff --git a/sources/neuraloperator/neuralop/data/__pycache__/__init__.cpython-313.pyc b/sources/neuraloperator/neuralop/data/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a22ff53d93ad65bc631975d85a5df95faebd7a7 Binary files /dev/null and b/sources/neuraloperator/neuralop/data/__pycache__/__init__.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/data/datasets/__init__.py b/sources/neuraloperator/neuralop/data/datasets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..31ee4351e20a467afbbf5860e36cc69eb6b85700 --- /dev/null +++ b/sources/neuraloperator/neuralop/data/datasets/__init__.py @@ -0,0 +1,21 @@ +from .darcy import DarcyDataset, load_darcy_flow_small +from .navier_stokes import NavierStokesDataset, load_navier_stokes_pt +from .pt_dataset import PTDataset +from .burgers import Burgers1dTimeDataset, load_mini_burgers_1dtime +from .dict_dataset import DictDataset +from .mesh_datamodule import MeshDataModule +from .car_cfd_dataset import CarCFDDataset, load_mini_car +from .ot_datamodule import OTDataModule +from .car_ot_dataset import CarOTDataset, load_saved_ot, CFDDataProcessor + +# only import SphericalSWEDataset if torch_harmonics is built locally +try: + from .spherical_swe import load_spherical_swe +except ModuleNotFoundError: + pass + +# only import TheWell if the_well is built +try: + from .the_well_dataset import TheWellDataset, ActiveMatterDataset, MHD64Dataset +except ModuleNotFoundError: + pass diff --git a/sources/neuraloperator/neuralop/data/datasets/__pycache__/__init__.cpython-313.pyc b/sources/neuraloperator/neuralop/data/datasets/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2031a1bdc03af88fb86b9a175ddac7fd58d38136 Binary files /dev/null and b/sources/neuraloperator/neuralop/data/datasets/__pycache__/__init__.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/data/datasets/__pycache__/burgers.cpython-313.pyc b/sources/neuraloperator/neuralop/data/datasets/__pycache__/burgers.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae3665280b00977809aef6d6d240bdd10bb883bc Binary files /dev/null and b/sources/neuraloperator/neuralop/data/datasets/__pycache__/burgers.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/data/datasets/__pycache__/car_cfd_dataset.cpython-313.pyc b/sources/neuraloperator/neuralop/data/datasets/__pycache__/car_cfd_dataset.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6fb82e4b32a93395fd9acd2cee6603cdc71ba79 Binary files /dev/null and b/sources/neuraloperator/neuralop/data/datasets/__pycache__/car_cfd_dataset.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/data/datasets/__pycache__/car_ot_dataset.cpython-313.pyc b/sources/neuraloperator/neuralop/data/datasets/__pycache__/car_ot_dataset.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91470208207c98b8730a7606d0f44a72d56f7d00 Binary files /dev/null and b/sources/neuraloperator/neuralop/data/datasets/__pycache__/car_ot_dataset.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/data/datasets/__pycache__/darcy.cpython-313.pyc b/sources/neuraloperator/neuralop/data/datasets/__pycache__/darcy.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07d8947bce4e7bd82aeb2d684d89a2e61691f304 Binary files /dev/null and b/sources/neuraloperator/neuralop/data/datasets/__pycache__/darcy.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/data/datasets/__pycache__/dict_dataset.cpython-313.pyc b/sources/neuraloperator/neuralop/data/datasets/__pycache__/dict_dataset.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f8e1ef352b3f27ac5b98b83196aca19c77bff00 Binary files /dev/null and b/sources/neuraloperator/neuralop/data/datasets/__pycache__/dict_dataset.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/data/datasets/__pycache__/mesh_datamodule.cpython-313.pyc b/sources/neuraloperator/neuralop/data/datasets/__pycache__/mesh_datamodule.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e5b6b7ddddfa62b066bfc928fc63a1f37e52eeb Binary files /dev/null and b/sources/neuraloperator/neuralop/data/datasets/__pycache__/mesh_datamodule.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/data/datasets/__pycache__/navier_stokes.cpython-313.pyc b/sources/neuraloperator/neuralop/data/datasets/__pycache__/navier_stokes.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1352d07f3fefb108adde4916bf3b3819a424c9a0 Binary files /dev/null and b/sources/neuraloperator/neuralop/data/datasets/__pycache__/navier_stokes.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/data/datasets/__pycache__/ot_datamodule.cpython-313.pyc b/sources/neuraloperator/neuralop/data/datasets/__pycache__/ot_datamodule.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c29a7880f8be75d8e1df69e5ce2d559f94116ef Binary files /dev/null and b/sources/neuraloperator/neuralop/data/datasets/__pycache__/ot_datamodule.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/data/datasets/__pycache__/pt_dataset.cpython-313.pyc b/sources/neuraloperator/neuralop/data/datasets/__pycache__/pt_dataset.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55142f7eaf3dd6a2d894ad7bd16f01eb75610e42 Binary files /dev/null and b/sources/neuraloperator/neuralop/data/datasets/__pycache__/pt_dataset.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/data/datasets/__pycache__/spherical_swe.cpython-313.pyc b/sources/neuraloperator/neuralop/data/datasets/__pycache__/spherical_swe.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8825960f2b8fda92b93b6ca7e5b98aacf2659b86 Binary files /dev/null and b/sources/neuraloperator/neuralop/data/datasets/__pycache__/spherical_swe.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/data/datasets/__pycache__/tensor_dataset.cpython-313.pyc b/sources/neuraloperator/neuralop/data/datasets/__pycache__/tensor_dataset.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb19632e5a2c6fe7a14f51f29859f2a27d6a8977 Binary files /dev/null and b/sources/neuraloperator/neuralop/data/datasets/__pycache__/tensor_dataset.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/data/datasets/__pycache__/the_well_dataset.cpython-313.pyc b/sources/neuraloperator/neuralop/data/datasets/__pycache__/the_well_dataset.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2fa62955e4504308be2e6b37916e37f3de91ceb2 Binary files /dev/null and b/sources/neuraloperator/neuralop/data/datasets/__pycache__/the_well_dataset.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/data/datasets/__pycache__/web_utils.cpython-313.pyc b/sources/neuraloperator/neuralop/data/datasets/__pycache__/web_utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3705420eff8b27eb5cc6afbb78f50bbe376f801a Binary files /dev/null and b/sources/neuraloperator/neuralop/data/datasets/__pycache__/web_utils.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/data/datasets/burgers.py b/sources/neuraloperator/neuralop/data/datasets/burgers.py new file mode 100644 index 0000000000000000000000000000000000000000..3ea1f841bb45054417d8fd64d8e2a00a23727bc9 --- /dev/null +++ b/sources/neuraloperator/neuralop/data/datasets/burgers.py @@ -0,0 +1,174 @@ +from pathlib import Path +from typing import Optional, List, Union +from torch.utils.data import DataLoader + +from .pt_dataset import PTDataset +from ..transforms.data_processors import DefaultDataProcessor + + +class Burgers1dTimeDataProcessor(DefaultDataProcessor): + """Burgers1dTimeDataProcessor wraps the DefaultDataProcessor + but adds one line to ``.preprocess`` to repeat the input ``x`` along + the temporal dimension. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + def preprocess(self, data_dict, batched=True): + """preprocess does the same thing as ``DefaultDataProcessor.preprocess()``, + with the addition of unsqueezing ``x`` along the temporal dimension and repeating + to match ``y``'s shape. + + Parameters + ---------- + data_dict : dict + one batch of input + batched : bool, optional + Whether inputs are batched, by default True + """ + _, _, temporal_len, _ = data_dict["y"].shape + # x starts as shape b, 1, spatial_len + x = data_dict["x"] + x = x.unsqueeze(-2).repeat([1, 1, temporal_len, 1]) + data_dict["x"] = x + return super().preprocess(data_dict, batched) + + +class Burgers1dTimeDataset(PTDataset): + """ + Burgers1dTimeDataset wraps data from the viscous + Burger's equation in 1 spatial dimension. + This dataset is not available for download online, but we + provide a low-res version on 16 spatial points + + Parameters + ---------- + root_dir : Union[Path, str] + root at which to download data files + n_train : int + number of train instances + n_tests : List[int] + number of test instances per test dataset + batch_size : int + batch size of training set + test_batch_sizes : List[int] + batch size of test sets + train_resolution : int + resolution of data for training set + test_resolutions : List[int], optional + resolution of data for testing sets, by default [16] + temporal_subsample : int, optional + rate at which to subsample the temporal dimension, by default None + spatial_subsample : int, optional + rate at which to subsample along the spatial dimension, by default None + + Attributes + ---------- + train_db: torch.utils.data.Dataset of training examples + test_db: "" of test examples + data_processor: neuralop.data.transforms.DataProcessor to process data examples + optional, default is None + """ + + def __init__( + self, + root_dir: Union[Path, str], + n_train: int, + n_tests: list[int], + train_resolution: int = 16, + test_resolutions: List[int] = [16], + batch_size: int = 32, + test_batch_sizes: List[int] = 32, + temporal_subsample: Optional[int] = None, + spatial_subsample: Optional[int] = None, + pad: int = 0, + ): + # convert root dir to path + if isinstance(root_dir, str): + root_dir = Path(root_dir) + if not root_dir.exists(): + root_dir.mkdir(parents=True) + + available_resolutions = [16, 128] + assert ( + train_resolution in available_resolutions + ), f"Resolutions available: {available_resolutions}, got {train_resolution}" + for res in test_resolutions: + assert ( + res in available_resolutions + ), f"Resolutions available: {available_resolutions}, got {res}" + + super().__init__( + root_dir=root_dir, + n_train=n_train, + n_tests=n_tests, + batch_size=batch_size, + test_batch_sizes=test_batch_sizes, + train_resolution=train_resolution, + test_resolutions=test_resolutions, + input_subsampling_rate=spatial_subsample, + output_subsampling_rate=[temporal_subsample, spatial_subsample], + encode_input=True, + encode_output=True, + encoding="channel-wise", + channel_dim=1, + dataset_name="burgers", + ) + self._data_processor = Burgers1dTimeDataProcessor( + self._data_processor.in_normalizer, self.data_processor.out_normalizer + ) + + +def load_mini_burgers_1dtime( + data_path: Union[Path, str], + n_train: int, + n_test: int, + batch_size: int, + test_batch_size: int, + temporal_subsample: int = 1, + spatial_subsample: int = 1, +): + """ + Legacy function to load mini Burger's equation dataset + + Parameters + ---------- + root_dir : Union[Path, str] + root at which to download data files + n_train : int + number of train instances + n_test : int + number of test instances per test dataset + batch_size : int + batch size of training set + test_batch_size : int + batch size of test set + temporal_subsample : int, optional + rate at which to subsample the temporal dimension, by default None + spatial_subsample : int, optional + rate at which to subsample along the spatial dimension, by default None + """ + burgers_dataset = Burgers1dTimeDataset( + root_dir=data_path, + n_train=n_train, + n_tests=[n_test], + batch_size=batch_size, + test_batch_sizes=[test_batch_size], + train_resolution=16, + test_resolutions=[16], + temporal_subsample=temporal_subsample, + spatial_subsample=spatial_subsample, + ) + + train_loader = DataLoader( + burgers_dataset.train_db, batch_size=batch_size, shuffle=True + ) + + test_loaders = { + 16: DataLoader( + burgers_dataset.test_dbs[16], batch_size=test_batch_size, shuffle=False + ) + } + + return train_loader, test_loaders, burgers_dataset.data_processor diff --git a/sources/neuraloperator/neuralop/data/datasets/car_cfd_dataset.py b/sources/neuraloperator/neuralop/data/datasets/car_cfd_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..8ed829ec08e034c2619c4e7f1e2f6ccae486c390 --- /dev/null +++ b/sources/neuraloperator/neuralop/data/datasets/car_cfd_dataset.py @@ -0,0 +1,107 @@ +from typing import List, Union +from pathlib import Path + +import torch + +from .mesh_datamodule import MeshDataModule +from .web_utils import download_from_zenodo_record +from neuralop.utils import get_project_root + + +class CarCFDDataset(MeshDataModule): + """Processed version of the Car-CFD dataset. + + CarCFDDataset is a processed version of the dataset introduced in + [1]_, which encodes a triangular mesh over the surface of a 3D model car + and provides the air pressure at each centroid and vertex of the mesh when + the car is placed in a simulated wind tunnel with a recorded inlet velocity. + In our case, inputs are a signed distance function evaluated over a regular + 3D grid of query points, as well as the inlet velocity. Outputs are pressure + values at each centroid of the triangle mesh. + + .. warning:: + ``CarCFDDataset`` inherits from ``MeshDataModule``, which requires the optional ``open3d`` dependency. + See :ref:`open3d_dependency` for more information. + + We also add additional manifest files to split the provided examples + into training and testing sets, as well as remove instances that are corrupted. + + Data is also stored on Zenodo: https://zenodo.org/records/13936501 + + Parameters + ---------- + root_dir : Union[str, Path] + root directory at which data is stored. + n_train : int, optional + Number of training instances to load, by default 1 + n_test : int, optional + Number of testing instances to load, by default 1 + query_res : List[int], optional + Dimension-wise resolution of signed distance function + (SDF) query cube, by default [32,32,32] + download : bool, optional + Whether to download data from Zenodo, by default True + + + Attributes + ---------- + train_loader: torch.utils.data.DataLoader + dataloader of training examples + test_loader: torch.utils.data.DataLoader + dataloader of testing examples + + References + ---------- + .. [1] : Umetani, N. and Bickel, B. (2018). "Learning three-dimensional flow for interactive + aerodynamic design". ACM Transactions on Graphics, 2018. + https://dl.acm.org/doi/10.1145/3197517.3201325. + """ + + def __init__( + self, + root_dir: Union[str, Path], + n_train: int = 1, + n_test: int = 1, + query_res: List[int] = [32, 32, 32], + download: bool = True, + ): + """Initialize the CarCFDDataset.""" + self.zenodo_record_id = "13936501" + + if isinstance(root_dir, str): + root_dir = Path(root_dir) + + if not root_dir.exists(): + root_dir.mkdir(parents=True) + + if download: + download_from_zenodo_record(record_id=self.zenodo_record_id, root=root_dir) + super().__init__( + root_dir=root_dir, + item_dir_name="data/", + n_train=n_train, + n_test=n_test, + query_res=query_res, + attributes=["press"], + ) + + # process data list to remove specific vertices from pressure to match number of vertices + for i, data in enumerate(self.train_data.data_list): + press = data["press"] + self.train_data.data_list[i]["press"] = torch.cat( + (press[:, 0:16], press[:, 112:]), axis=1 + ) + for i, data in enumerate(self.test_data.data_list): + press = data["press"] + self.test_data.data_list[i]["press"] = torch.cat( + (press[:, 0:16], press[:, 112:]), axis=1 + ) + + +def load_mini_car(): + """ + Load the 3-example mini Car-CFD dataset we package along with our module. + + See `neuralop.data.datasets.CarCFDDataset` for more detailed references + """ + return torch.load(get_project_root() / "neuralop/data/datasets/data/mini_car.pt") diff --git a/sources/neuraloperator/neuralop/data/datasets/car_ot_dataset.py b/sources/neuraloperator/neuralop/data/datasets/car_ot_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..679aeed64aeea915fb67ab18978122c65ce6bae9 --- /dev/null +++ b/sources/neuraloperator/neuralop/data/datasets/car_ot_dataset.py @@ -0,0 +1,232 @@ +from typing import List, Union +from pathlib import Path + +import numpy as np +import torch +from torch.utils.data import DataLoader +from neuralop.data.transforms.data_processors import DataProcessor + +from .dict_dataset import DictDataset +from ..transforms.normalizers import UnitGaussianNormalizer + +from .ot_datamodule import OTDataModule +from .web_utils import download_from_zenodo_record +from neuralop.utils import get_project_root + + +class CarOTDataset(OTDataModule): + """ + Parameters + ---------- + root_dir : Union[str, Path] + root directory at which data is stored. + n_train : int, optional + Number of training instances to load, by default 1. + n_test : int, optional + Number of testing instances to load, by default 1. + expand_factor : float, optional + Scale factor to map physical mesh size to latent mesh size (e.g., torus/sphere). + Affects OT plan surjectivity: smaller values may lead to incomplete mappings, while larger values increase computational cost but improve surjectivity. + Choose a value balancing accuracy and efficiency, by default 3. + reg : float, optional + Regularization coefficient for the Sinkhorn algorithm. + Affects OT plan surjectivity: smaller values increase precision (where fewer non-surjective plans indicate higher precision) but incur higher computational cost. + Choose a value balancing accuracy and efficiency, by default 1e-06. + device : Union[str, torch.device], optional + Device for OT computation. + + Attributes + ---------- + train_loader: torch.utils.data.DataLoader + dataloader of training examples + test_loader: torch.utils.data.DataLoader + dataloader of testing examples + + """ + + def __init__( + self, + root_dir: Union[str, Path], + n_train: int = 1, + n_test: int = 1, + expand_factor: float = 3.0, + reg: float = 1e-06, + device: Union[str, torch.device] = "cuda", + ): + if isinstance(root_dir, str): + root_dir = Path(root_dir) + + if not root_dir.exists(): + root_dir.mkdir(parents=True) + + super().__init__( + root_dir=root_dir, + item_dir_name="data/", + n_train=n_train, + n_test=n_test, + attributes=["press"], + expand_factor=expand_factor, + reg=reg, + device=device, + ) + + # encode transport and pressure + normalizer_keys = ["trans", "press"] + self.normalizers = UnitGaussianNormalizer.from_dataset( + self.data[0:n_train], dim=[1], keys=normalizer_keys + ) + + for attr in normalizer_keys: + for j in range(len(self.data)): + data_elem = self.data[j][attr] + self.data[j][attr] = self.normalizers[attr].transform(data_elem) + + for j in range(len(self.data)): + batch_data = self.data[j] + # prepare the complete features presenting transport map/plan on latent mesh + n_s = batch_data["trans"].shape[1] + n_s_sqrt = int(np.sqrt(n_s)) + normal = batch_data["nor_t"] + ind_enc = batch_data["ind_enc"] + normal = normal[ind_enc] + normal_features = torch.cross( + normal, batch_data["nor_s"].reshape(-1, 3), dim=1 + ) + trans = ( + torch.cat( + (batch_data["trans"][0], batch_data["source"], normal_features), + dim=1, + ) + .T.reshape(9, n_s_sqrt, n_s_sqrt) + .unsqueeze(0) + ) + self.data[j]["trans"] = trans + # process data list to remove specific vertices from pressure to match number of vertices + press = batch_data["press"] + self.data[j]["press"] = torch.cat((press[:, 0:16], press[:, 112:]), axis=1) + + # Datasets + self.train_data = DictDataset(self.data[0:n_train]) + self.test_data = DictDataset(self.data[n_train:]) + + def train_loader(self, **kwargs): + return DataLoader(self.train_data, **kwargs) + + def test_loader(self, **kwargs): + return DataLoader(self.test_data, **kwargs) + + +class load_saved_ot: + def __init__( + self, + n_train: int = 2, + n_test: int = 1, + expand_factor: float = 3.0, + reg: float = 1e-06, + ): + """ + Load the saved Car-OT dataset we package along with our module. + + See `neuralop.data.datasets.ot_datamodule` for more detailed references + """ + data = torch.load( + get_project_root() + / "neuralop/data/datasets/data" + / f"ot_expand{expand_factor}_reg{reg}_train{n_train}_test{n_test}.pt" + ) + + # encode transport and pressure + normalizer_keys = ["trans", "press"] + self.normalizers = UnitGaussianNormalizer.from_dataset( + data[0:n_train], dim=[1], keys=normalizer_keys + ) + + for attr in normalizer_keys: + for j in range(len(data)): + data_elem = data[j][attr] + data[j][attr] = self.normalizers[attr].transform(data_elem) + + for j in range(len(data)): + batch_data = data[j] + # prepare the complete features presenting transport map/plan on latent mesh + n_s = batch_data["trans"].shape[1] + n_s_sqrt = int(np.sqrt(n_s)) + normal = batch_data["nor_t"] + ind_enc = batch_data["ind_enc"] + normal = normal[ind_enc] + normal_features = torch.cross( + normal, batch_data["nor_s"].reshape(-1, 3), dim=1 + ) + trans = ( + torch.cat( + (batch_data["trans"][0], batch_data["source"], normal_features), + dim=1, + ) + .T.reshape(9, n_s_sqrt, n_s_sqrt) + .unsqueeze(0) + ) + data[j]["trans"] = trans + # process data list to remove specific vertices from pressure to match number of vertices + press = batch_data["press"] + data[j]["press"] = torch.cat((press[:, 0:16], press[:, 112:]), axis=1) + + # Datasets + self.train_data = DictDataset(data[0:n_train]) + self.test_data = DictDataset(data[n_train : n_test + n_train]) + + def train_loader(self, **kwargs): + return DataLoader(self.train_data, **kwargs) + + def test_loader(self, **kwargs): + return DataLoader(self.test_data, **kwargs) + + +# Handle data preprocessing to OTNO +class CFDDataProcessor(DataProcessor): + """ + Implements logic to preprocess data/handle model outputs + to train an OTNO on the CFD car-pressure dataset + """ + + def __init__(self, normalizer, device="cuda"): + super().__init__() + self.normalizer = normalizer + self.device = device + self.model = None + + def preprocess(self, sample): + # Turn a data dictionary returned OTDataModule's DictDataset + # into the form expected by the OTNO + + x = sample["trans"].squeeze(0).to(self.device) + ind_dec = sample["ind_dec"].squeeze(0).to(self.device) + + # Output data + truth = sample["press"].squeeze(0).unsqueeze(-1).to(self.device) + + batch_dict = dict(x=x, ind_dec=ind_dec, y=truth) + + sample.update(batch_dict) + return sample + + def postprocess(self, out, sample): + if not self.training: + out = self.normalizer.inverse_transform(out) + y = self.normalizer.inverse_transform(sample["y"].squeeze(0)) + sample["y"] = y + sample = {"y": sample["y"]} + return out, sample + + def to(self, device): + self.device = device + self.normalizer = self.normalizer.to(device) + return self + + def wrap(self, model): + self.model = model + + def forward(self, sample): + sample = self.preprocess(sample) + out = self.model(sample) + out, sample = self.postprocess(out, sample) + return out, sample diff --git a/sources/neuraloperator/neuralop/data/datasets/darcy.py b/sources/neuraloperator/neuralop/data/datasets/darcy.py new file mode 100644 index 0000000000000000000000000000000000000000..c6599a204183c653a9307044f38dcce660c7b18a --- /dev/null +++ b/sources/neuraloperator/neuralop/data/datasets/darcy.py @@ -0,0 +1,251 @@ +import logging +import os +from pathlib import Path +from typing import Union, List + +import torch +from torch.utils.data import DataLoader + +from .pt_dataset import PTDataset +from .web_utils import download_from_zenodo_record + +from neuralop.utils import get_project_root + +logger = logging.Logger(logging.root.level) + + +class DarcyDataset(PTDataset): + """ + DarcyDataset stores data generated according to Darcy's Law. + Input is a coefficient function and outputs describe flow. + + Data source: https://zenodo.org/records/12784353 + + Parameters + ---------- + root_dir : Union[Path, str] + root at which to download data files + n_train : int + number of train instances + n_tests : List[int] + number of test instances per test dataset + batch_size : int + batch size of training set + test_batch_sizes : List[int] + batch size of test sets + train_resolution : int + resolution of data for training set + test_resolutions : List[int], optional + resolution of data for testing sets, by default [16,32] + encode_input : bool, optional + whether to normalize inputs in provided DataProcessor, + by default False + encode_output : bool, optional + whether to normalize outputs in provided DataProcessor, + by default True + encoding : str, optional + parameter for input/output normalization. Whether + to normalize by channel ("channel-wise") or + by pixel ("pixel-wise"), default "channel-wise" + channel_dim : int, optional + dimension of saved tensors to index data channels, by default 1 + subsampling_rate : int or List[int], optional + rate at which to subsample each input dimension, by default None + dtype : torch.dtype, optional + dtype to cast input tensors to after loading. The bundled Darcy + coefficient fields are stored as torch.bool, so this defaults to + torch.float32 to keep them usable by float models. Pass None to + preserve the saved dtype. Default is torch.float32. + download : bool, optional + whether to download data if not present, by default True + + Attributes + ---------- + train_db: torch.utils.data.Dataset of training examples + test_db: "" of test examples + data_processor: neuralop.data.transforms.DataProcessor to process data examples + optional, default is None + """ + + def __init__( + self, + root_dir: Union[Path, str], + n_train: int, + n_tests: List[int], + batch_size: int, + test_batch_sizes: List[int], + train_resolution: int, + test_resolutions: List[int] = [16, 32], + encode_input: bool = False, + encode_output: bool = True, + encoding="channel-wise", + channel_dim=1, + subsampling_rate=None, + dtype: torch.dtype = torch.float32, + download: bool = True, + ): + """Initialize the DarcyDataset. + + See class docstring for detailed parameter descriptions. + """ + + # convert root dir to Path + if isinstance(root_dir, str): + root_dir = Path(root_dir) + if not root_dir.exists(): + root_dir.mkdir(parents=True) + + # Zenodo record ID for Darcy-Flow dataset + zenodo_record_id = "12784353" + + # List of resolutions needed for dataset object + resolutions = set(test_resolutions + [train_resolution]) + + # We store data at these resolutions on the Zenodo archive + available_resolutions = [16, 32, 64, 128, 421] + for res in resolutions: + assert ( + res in available_resolutions + ), f"Error: resolution {res} not available" + + # download darcy data from zenodo archive if passed + if download: + files_to_download = [] + already_downloaded_files = [x.name for x in root_dir.iterdir()] + for res in resolutions: + if ( + f"darcy_train_{res}.pt" not in already_downloaded_files + or f"darcy_test_{res}.pt" not in already_downloaded_files + ): + files_to_download.append(f"darcy_{res}.tgz") + download_from_zenodo_record( + record_id=zenodo_record_id, + root=root_dir, + files_to_download=files_to_download, + ) + + # once downloaded/if files already exist, init PTDataset + super().__init__( + root_dir=root_dir, + dataset_name="darcy", + n_train=n_train, + n_tests=n_tests, + batch_size=batch_size, + test_batch_sizes=test_batch_sizes, + train_resolution=train_resolution, + test_resolutions=test_resolutions, + encode_input=encode_input, + encode_output=encode_output, + encoding=encoding, + channel_dim=channel_dim, + input_subsampling_rate=subsampling_rate, + output_subsampling_rate=subsampling_rate, + dtype=dtype, + ) + + +# legacy Small Darcy Flow example +example_data_root = get_project_root() / "neuralop/data/datasets/data" + + +def load_darcy_flow_small( + n_train, + n_tests, + batch_size, + test_batch_sizes, + data_root=example_data_root, + test_resolutions=[16, 32], + encode_input=False, + encode_output=True, + encoding="channel-wise", + channel_dim=1, +): + dataset = DarcyDataset( + root_dir=data_root, + n_train=n_train, + n_tests=n_tests, + batch_size=batch_size, + test_batch_sizes=test_batch_sizes, + train_resolution=16, + test_resolutions=test_resolutions, + encode_input=encode_input, + encode_output=encode_output, + channel_dim=channel_dim, + encoding=encoding, + download=True, + ) + + # return dataloaders for backwards compat + train_loader = DataLoader( + dataset.train_db, + batch_size=batch_size, + num_workers=1, + pin_memory=True, + persistent_workers=False, + ) + + test_loaders = {} + for res, test_bsize in zip(test_resolutions, test_batch_sizes): + test_loaders[res] = DataLoader( + dataset.test_dbs[res], + batch_size=test_bsize, + shuffle=False, + num_workers=1, + pin_memory=True, + persistent_workers=False, + ) + + return train_loader, test_loaders, dataset.data_processor + + +# legacy pt Darcy Flow loader +def load_darcy_pt( + n_train, + n_tests, + batch_size, + test_batch_sizes, + data_root="./neuralop/data/datasets/data", + train_resolution=16, + test_resolutions=[16, 32], + encode_input=False, + encode_output=True, + encoding="channel-wise", + channel_dim=1, + num_workers=1, +): + dataset = DarcyDataset( + root_dir=data_root, + n_train=n_train, + n_tests=n_tests, + batch_size=batch_size, + test_batch_sizes=test_batch_sizes, + train_resolution=train_resolution, + test_resolutions=test_resolutions, + encode_input=encode_input, + encode_output=encode_output, + encoding=encoding, + channel_dim=channel_dim, + download=False, + ) + + # return dataloaders for backwards compat + train_loader = DataLoader( + dataset.train_db, + batch_size=batch_size, + num_workers=num_workers, + pin_memory=True, + persistent_workers=False, + ) + + test_loaders = {} + for res, test_bsize in zip(test_resolutions, test_batch_sizes): + test_loaders[res] = DataLoader( + dataset.test_dbs[res], + batch_size=test_bsize, + shuffle=False, + num_workers=num_workers, + pin_memory=True, + persistent_workers=False, + ) + + return train_loader, test_loaders, dataset.data_processor diff --git a/sources/neuraloperator/neuralop/data/datasets/data/burgers_test_16.pt b/sources/neuraloperator/neuralop/data/datasets/data/burgers_test_16.pt new file mode 100644 index 0000000000000000000000000000000000000000..9e09cd832b556cb80026b8b4e96fb52da7a73bb3 --- /dev/null +++ b/sources/neuraloperator/neuralop/data/datasets/data/burgers_test_16.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:70bb1591e31b254e74ac6097a5520de299da38115cb3f814e8d0f6f19057d201 +size 2766540 diff --git a/sources/neuraloperator/neuralop/data/datasets/data/burgers_train_16.pt b/sources/neuraloperator/neuralop/data/datasets/data/burgers_train_16.pt new file mode 100644 index 0000000000000000000000000000000000000000..606d8b014604147f264384f19f44d44269f7a089 --- /dev/null +++ b/sources/neuraloperator/neuralop/data/datasets/data/burgers_train_16.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d12335adc0d96357a893dc39d72957fa89fda852b00902d94da95aa06af23fa0 +size 2766547 diff --git a/sources/neuraloperator/neuralop/data/datasets/data/darcy_test_16.pt b/sources/neuraloperator/neuralop/data/datasets/data/darcy_test_16.pt new file mode 100644 index 0000000000000000000000000000000000000000..ceba2a9f58875cec17b86c1b58af5ddb21feadf4 --- /dev/null +++ b/sources/neuraloperator/neuralop/data/datasets/data/darcy_test_16.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d2b19af9d4a6ae04ba2de54b8ecccc8b89766472faf6ce7f506c0b2a60f69a4c +size 64999 diff --git a/sources/neuraloperator/neuralop/data/datasets/data/darcy_test_32.pt b/sources/neuraloperator/neuralop/data/datasets/data/darcy_test_32.pt new file mode 100644 index 0000000000000000000000000000000000000000..65c8430e79227b584d527fb99dcf832fdb795581 --- /dev/null +++ b/sources/neuraloperator/neuralop/data/datasets/data/darcy_test_32.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bcbd10622373e94df84a17fcdb72ac4317d76e024c2499d21fd1fd34d0742cfd +size 256999 diff --git a/sources/neuraloperator/neuralop/data/datasets/data/darcy_train_16.pt b/sources/neuraloperator/neuralop/data/datasets/data/darcy_train_16.pt new file mode 100644 index 0000000000000000000000000000000000000000..c964e572654967bb8cf8bfa6f847b4243776aafb --- /dev/null +++ b/sources/neuraloperator/neuralop/data/datasets/data/darcy_train_16.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0be662acdb1dab7dfd1a1da0b140e97f75cc94f98a14edcf768abe6968b3b418 +size 1280999 diff --git a/sources/neuraloperator/neuralop/data/datasets/data/mini_car.pt b/sources/neuraloperator/neuralop/data/datasets/data/mini_car.pt new file mode 100644 index 0000000000000000000000000000000000000000..339834a405f226820f26279357830b1dcdeb2753 --- /dev/null +++ b/sources/neuraloperator/neuralop/data/datasets/data/mini_car.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cc4941066a1abe0d10461aec5069eea0f0e595248469e1522a4f873965f784f2 +size 1243042 diff --git a/sources/neuraloperator/neuralop/data/datasets/data/ot_expand3.0_reg1e-06_train2_test1.pt b/sources/neuraloperator/neuralop/data/datasets/data/ot_expand3.0_reg1e-06_train2_test1.pt new file mode 100644 index 0000000000000000000000000000000000000000..5aaf3e85254a8e7e6689c22f3edc0a287ebaaf0e --- /dev/null +++ b/sources/neuraloperator/neuralop/data/datasets/data/ot_expand3.0_reg1e-06_train2_test1.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1e59079c9e3b5a610cc00345e20d01fb145ee9e76c161bf47db88d27738500f5 +size 1796741 diff --git a/sources/neuraloperator/neuralop/data/datasets/dict_dataset.py b/sources/neuraloperator/neuralop/data/datasets/dict_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..2fd3d60dc66cba84d24cb38aaafbea1017e14876 --- /dev/null +++ b/sources/neuraloperator/neuralop/data/datasets/dict_dataset.py @@ -0,0 +1,41 @@ +from typing import List + +from torch.utils.data import Dataset + + +class DictDataset(Dataset): + """DictDataset is a basic dataset form that stores each batch + as a dictionary of tensors or other data structures + + + """ + + def __init__( + self, + data_list: List[dict], + constant: dict = None, + ): + """ + + Parameters + ---------- + data_list : List[dict] + list of individual batch dictionaries + constant : dict, optional + if each data batch shares some constant valued key/val pairs, + they can be stored in constant for simplicity + """ + + self.data_list = data_list + self.constant = constant + + def __getitem__(self, index): + return_dict = self.data_list[index] + + if self.constant is not None: + return_dict.update(self.constant) + + return return_dict + + def __len__(self): + return len(self.data_list) diff --git a/sources/neuraloperator/neuralop/data/datasets/hdf5_dataset.py b/sources/neuraloperator/neuralop/data/datasets/hdf5_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..e91e8fa6a727e3bb2a87eff20795fa40788bbf7c --- /dev/null +++ b/sources/neuraloperator/neuralop/data/datasets/hdf5_dataset.py @@ -0,0 +1,76 @@ +import h5py +import torch +from torch.utils.data import Dataset + + +class H5pyDataset(Dataset): + """PDE h5py dataset""" + + def __init__( + self, + data_path, + resolution=128, + transform_x=None, + transform_y=None, + n_samples=None, + ): + resolution_to_step = {128: 8, 256: 4, 512: 2, 1024: 1} + try: + subsample_step = resolution_to_step[resolution] + except KeyError: + raise ValueError( + f"Got resolution={resolution}, " + f"expected one of {resolution_to_step.keys()}" + ) + + self.subsample_step = subsample_step + self.data_path = data_path + self._data = None + self.transform_x = transform_x + self.transform_y = transform_y + + if n_samples is not None: + self.n_samples = n_samples + else: + with h5py.File(str(self.data_path), "r") as f: + self.n_samples = f["x"].shape[0] + + @property + def data(self): + if self._data is None: + self._data = h5py.File(str(self.data_path), "r") + return self._data + + def _attribute(self, variable, name): + return self.data[variable].attrs[name] + + def __len__(self): + return self.n_samples + + def __getitem__(self, idx): + if torch.is_tensor(idx): + idx = idx.tolist() + if isinstance(idx, int): + assert ( + idx < self.n_samples + ), f"Trying to access sample {idx} of dataset with {self.n_samples} samples" + else: + for i in idx: + assert i < self.n_samples, ( + f"Trying to access sample {i} " + f"of dataset with {self.n_samples} samples" + ) + + x = self.data["x"][idx, :: self.subsample_step, :: self.subsample_step] + y = self.data["y"][idx, :: self.subsample_step, :: self.subsample_step] + + x = torch.tensor(x, dtype=torch.float32) + y = torch.tensor(y, dtype=torch.float32) + + if self.transform_x: + x = self.transform_x(x) + + if self.transform_y: + y = self.transform_y(y) + + return {"x": x, "y": y} diff --git a/sources/neuraloperator/neuralop/data/datasets/mesh_datamodule.py b/sources/neuraloperator/neuralop/data/datasets/mesh_datamodule.py new file mode 100644 index 0000000000000000000000000000000000000000..c116c0408302ce0770ade50a5c68133b49460083 --- /dev/null +++ b/sources/neuraloperator/neuralop/data/datasets/mesh_datamodule.py @@ -0,0 +1,321 @@ +from pathlib import Path +from timeit import default_timer +from typing import List, Union + +import numpy as np + +# import open3d for io if built. Otherwise, +# the class will build, but no files will be loaded. +try: + import open3d as o3d + + o3d_warn = False +except ModuleNotFoundError: + o3d_warn = True + +import torch +from torch.utils.data import DataLoader + +from .dict_dataset import DictDataset +from ..transforms.normalizers import UnitGaussianNormalizer + + +class MeshDataModule: + def __init__( + self, + root_dir: Union[str, Path], + item_dir_name: Union[str, Path], + n_train: int = None, + n_test: int = None, + query_res: List[int] = None, + attributes: List[str] = None, + ): + """MeshDataModule provides a general dataset for irregular coordinate meshes + for use in a GNO-based architecture + + Parameters + ---------- + root_dir : Union[str, Path] + str or Path to root directory of CFD dataset + item_dir_name : Union[str, Path] + directory in which individual item subdirs are stored + n_train : int, optional + hard limit on number of training examples + if n_train is greater than the actual number + of training examples available, nothing is changed + n_test : int, optional + hard limit on number of test examples + if n_test is greater than the actual number + of testing examples available, nothing is changed + query_res : List[int], optional + resolution of latent query points along each dimension + attributes : List[str], optional + list of string keys for attributes in the dataset to return + as keys for each batch dict + """ + + if o3d_warn: + print("Warning: you are attempting to run MeshDataModule without the required dependency open3d.") + raise ModuleNotFoundError() + if isinstance(root_dir, str): + root_dir = Path(root_dir) + + # Ensure path is valid + root_dir = root_dir.expanduser() + assert root_dir.exists(), "Path does not exist" + assert root_dir.is_dir(), "Path is not a directory" + + # Read train and test indicies + with open(root_dir / "train.txt") as file: + train_ind = file.readline().split(",") + + with open(root_dir / "test.txt") as file: + test_ind = file.readline().split(",") + + if n_train is not None: + if n_train < len(train_ind): + train_ind = train_ind[0:n_train] + + if n_test is not None: + if n_test < len(test_ind): + test_ind = test_ind[0:n_test] + + # set train and test sizes + train_ind = train_ind[0:n_train] + test_ind = test_ind[0:n_test] + n_train = len(train_ind) + n_test = len(test_ind) + print("n_train n_test are", n_train, n_test) + + mesh_ind = train_ind + test_ind + # remove trailing newlines from train and test indices + mesh_ind = [x.rstrip() for x in mesh_ind] + + data_dir = root_dir / "data" + + # Load all meshes + + meshes = [] + for ind in mesh_ind: + mesh = o3d.io.read_triangle_mesh( + str(data_dir / (item_dir_name + ind + "/tri_mesh.ply")) + ) + meshes.append(mesh) + + # Dataset wide bounding box + min_b, max_b = self.get_global_bounding_box(meshes) + + # are_watertight = self.are_watertight(meshes) + are_watertight = True + + # Uniform query points if not provided + if isinstance(query_res, list) or isinstance(query_res, tuple): + tx = np.linspace(min_b[0], max_b[0], query_res[0]) + ty = np.linspace(min_b[1], max_b[1], query_res[1]) + tz = np.linspace(min_b[2], max_b[2], query_res[2]) + + query_points = np.stack( + np.meshgrid(tx, ty, tz, indexing="ij"), axis=-1 + ).astype(np.float32) + else: + raise TypeError() + + # Compute data from meshes + data = [] + deleted_meshes = [] + self.time_to_distance = 0.0 + for i, mesh in enumerate(meshes): + item_dict = {} + + mesh = mesh.compute_triangle_normals() + mesh = mesh.compute_vertex_normals() + + item_dict["vertices"] = np.asarray(mesh.vertices) + item_dict["vertex_normals"] = np.asarray(mesh.vertex_normals) + item_dict["triangle_normals"] = np.asarray(mesh.triangle_normals) + + centroids, area = self.compute_triangle_centroids( + item_dict["vertices"], np.asarray(mesh.triangles) + ) + + item_dict["centroids"] = centroids + item_dict["triangle_areas"] = area + + # Normalize vertex data based on global bound + item_dict["vertices"] = self.range_normalize( + item_dict["vertices"], min_b, max_b, 0, 1 + ) + + item_dict["centroids"] = self.range_normalize( + item_dict["centroids"], min_b, max_b, 0, 1 + ) + + if query_points is not None: + tt = default_timer() + try: + distance, closest = self.compute_distances( + mesh, query_points, are_watertight + ) + except: + deleted_meshes.append(mesh_ind[i]) + print(f"{i}-th mesh is empty and will not be added to the dataset") + continue + self.time_to_distance += default_timer() - tt + item_dict["distance"] = np.expand_dims(distance, -1) + item_dict["closest_points"] = closest + + # Normalize vertex data based on global bound + item_dict["closest_points"] = self.range_normalize( + item_dict["closest_points"], min_b, max_b, 0, 1 + ) + data.append(item_dict) + + self.time_to_distance /= len(meshes) + + del meshes + + # remove all broken meshes from training set + n_train -= len(deleted_meshes) + print(f"{deleted_meshes=}") + + # Bounds based on training data + min_dist, max_dist = self.get_bounds_from_data(data[0:n_train], "distance") + min_area, max_area = self.get_bounds_from_data( + data[0:n_train], "triangle_areas" + ) + + for data_dict in data: + data_dict["distance"] = self.range_normalize( + data_dict["distance"], min_dist, max_dist, 1e-6, 1 + ) + data_dict["normalized_triangle_areas"] = self.range_normalize( + data_dict["triangle_areas"], min_area, max_area, 1e-6, 1 + ) + + # Convert to torch + for data_dict in data: + for key in data_dict: + data_dict[key] = torch.from_numpy(data_dict[key]).to(torch.float32) + + # Load non-mesh data + if attributes is not None: + for j, ind in enumerate(mesh_ind): + # skip corrupted meshes we caught while adding to dataset + if ind in deleted_meshes: + print(f"{j}-th pressure field ind {ind} was deleted.") + continue + for attr in attributes: + path = str(data_dir / (item_dir_name + ind + "/" + attr + ".npy")) + data[j][attr] = torch.from_numpy((np.load(path))) + + if isinstance(data[j][attr], torch.Tensor): + data[j][attr] = data[j][attr].to(torch.float32) + + # Compute Gaussian normalizers based on training data + normalizer_keys = [] + for attr in attributes: + if isinstance(data[0][attr], torch.Tensor): + normalizer_keys.append(attr) + # returns keyed dict of UnitGaussianNormalizer instances + self.normalizers = UnitGaussianNormalizer.from_dataset( + data, dim=[1], keys=normalizer_keys + ) + + # Encode all data + for attr in normalizer_keys: + for j in range(len(data)): + data_elem = data[j][attr] + if data_elem.shape[0] != 1: + data_elem = data_elem.unsqueeze(0) + data[j][attr] = self.normalizers[attr].transform(data_elem) + + if not bool(self.normalizers): + self.normalizers = None + else: + self.normalizers = None + + # Set-up constant dict + query_points = self.range_normalize(query_points, min_b, max_b, 0, 1) + + query_points = torch.from_numpy(query_points).to(torch.float32) + constant = {"query_points": query_points} + + # Datasets + self.train_data = DictDataset(data[0:n_train], constant) + self.test_data = DictDataset(data[n_train:], constant) + + def get_global_bounding_box(self, meshes): + min_b = np.zeros((3, len(meshes))) + max_b = np.zeros((3, len(meshes))) + for j, mesh in enumerate(meshes): + try: + min_b[:, j] = mesh.get_min_bound() + max_b[:, j] = mesh.get_max_bound() + except IndexError: + print(f"{j}-th mesh could not be bounded. ") + pass + + min_b = min_b.min(axis=1) + max_b = max_b.max(axis=1) + + return min_b, max_b + + def are_watertight(self, meshes): + for mesh in meshes: + if not mesh.is_watertight(): + return False + + return True + + def compute_triangle_centroids(self, vertices, triangles): + A, B, C = ( + vertices[triangles[:, 0]], + vertices[triangles[:, 1]], + vertices[triangles[:, 2]], + ) + + centroids = (A + B + C) / 3 + areas = np.sqrt(np.sum(np.cross(B - A, C - A) ** 2, 1)) / 2 + + return centroids, areas + + def compute_distances(self, mesh, query_points, signed_distance): + mesh = o3d.t.geometry.TriangleMesh.from_legacy(mesh) + scene = o3d.t.geometry.RaycastingScene() + _ = scene.add_triangles(mesh) + + if signed_distance: + dist = scene.compute_signed_distance(query_points).numpy() + else: + dist = scene.compute_distance(query_points).numpy() + + closest = scene.compute_closest_points(query_points)["points"].numpy() + + return dist, closest + + def range_normalize(self, data, min_b, max_b, new_min, new_max): + data = (data - min_b) / (max_b - min_b) + data = (new_max - new_min) * data + new_min + + return data + + def get_bounds_from_data(self, data, key): + global_min = data[0][key].min() + global_max = data[0][key].max() + + for j in range(1, len(data)): + current_min = data[j][key].min() + current_max = data[j][key].max() + + if current_min < global_min: + global_min = current_min + if current_max > global_max: + global_max = current_max + + return global_min, global_max + + def train_loader(self, **kwargs): + return DataLoader(self.train_data, **kwargs) + + def test_loader(self, **kwargs): + return DataLoader(self.test_data, **kwargs) diff --git a/sources/neuraloperator/neuralop/data/datasets/navier_stokes.py b/sources/neuraloperator/neuralop/data/datasets/navier_stokes.py new file mode 100644 index 0000000000000000000000000000000000000000..0f9aadd5323b6e219bf3643bf6d30c2a545940f8 --- /dev/null +++ b/sources/neuraloperator/neuralop/data/datasets/navier_stokes.py @@ -0,0 +1,192 @@ +import logging +import os +from pathlib import Path +from typing import Union, List + +from torch.utils.data import DataLoader + +from .pt_dataset import PTDataset +from .web_utils import download_from_zenodo_record +from neuralop.utils import get_project_root + +logger = logging.Logger(logging.root.level) + + +class NavierStokesDataset(PTDataset): + """ + NavierStokesDataset stores data generated according to the 2d + incompressible Navier-Stokes equations. Input and output are both + 2d fields with one channel of data which describes the vorticity at each point. + + Data source: https://zenodo.org/records/12825163 + + Parameters + ---------- + root_dir : Union[Path, str] + root at which to download data files + n_train : int + number of train instances + n_tests : List[int] + number of test instances per test dataset + batch_size : int + batch size of training set + test_batch_sizes : List[int] + batch size of test sets + train_resolution : int + resolution of data for training set + test_resolutions : List[int], optional + resolution of data for testing sets, by default [16,32] + encode_input : bool, optional + whether to normalize inputs in provided DataProcessor, + by default False + encode_output : bool, optional + whether to normalize outputs in provided DataProcessor, + by default True + encoding : str, optional + parameter for input/output normalization. Whether + to normalize by channel ("channel-wise") or + by pixel ("pixel-wise"), default "channel-wise" + channel_dim : int, optional + dimension of saved tensors to index data channels, by default 1 + subsampling_rate : int or List[int], optional + rate at which to subsample each input dimension, by default None + download : bool, optional + whether to download data if not present, by default True + + Attributes + ---------- + train_db: torch.utils.data.Dataset of training examples + test_db: "" of test examples + data_processor: neuralop.data.transforms.DataProcessor to process data examples + optional, default is None + """ + + def __init__( + self, + root_dir: Union[Path, str], + n_train: int, + n_tests: List[int], + batch_size: int, + test_batch_sizes: List[int], + train_resolution: int, + test_resolutions: int = [16, 32], + encode_input: bool = False, + encode_output: bool = True, + encoding="channel-wise", + channel_dim=1, + subsampling_rate=None, + download: bool = True, + ): + """Initialize the NavierStokesDataset. + + See class docstring for detailed parameter descriptions. + """ + # convert root dir to Path + if isinstance(root_dir, str): + root_dir = Path(root_dir) + if not root_dir.exists(): + root_dir.mkdir(parents=True) + + # Zenodo record ID for Navier-Stokes dataset + zenodo_record_id = "12825163" + + # List of resolutions needed for dataset object + resolutions = set(test_resolutions + [train_resolution]) + + # We store data at these resolutions on the Zenodo archive + available_resolutions = [128, 1024] + for res in resolutions: + assert ( + res in available_resolutions + ), f"Error: resolution {res} not available" + + # download darcy data from zenodo archive if passed + if download: + files_to_download = [] + already_downloaded_files = [x.name for x in root_dir.iterdir()] + for res in resolutions: + if ( + f"nsforcing_train_{res}.pt" not in already_downloaded_files + or f"nsforcing_test_{res}.pt" not in already_downloaded_files + ): + files_to_download.append(f"nsforcing_{res}.tgz") + download_from_zenodo_record( + record_id=zenodo_record_id, + root=root_dir, + files_to_download=files_to_download, + ) + + # once downloaded/if files already exist, init PTDataset + super().__init__( + root_dir=root_dir, + n_train=n_train, + n_tests=n_tests, + dataset_name="nsforcing", + batch_size=batch_size, + test_batch_sizes=test_batch_sizes, + train_resolution=train_resolution, + test_resolutions=test_resolutions, + encode_input=encode_input, + encode_output=encode_output, + encoding=encoding, + channel_dim=channel_dim, + input_subsampling_rate=subsampling_rate, + output_subsampling_rate=subsampling_rate, + ) + + +example_data_root = get_project_root() / "neuralop/datasets/data" + + +# load navier stokes pt for backwards compatibility +def load_navier_stokes_pt( + n_train, + n_tests, + batch_size, + test_batch_sizes, + data_root=example_data_root, + train_resolution=128, + test_resolutions=[128], + encode_input=False, + encode_output=True, + encoding="channel-wise", + channel_dim=1, + subsampling_rate=None, + num_workers=1, +): + dataset = NavierStokesDataset( + root_dir=data_root, + n_train=n_train, + n_tests=n_tests, + batch_size=batch_size, + test_batch_sizes=test_batch_sizes, + train_resolution=train_resolution, + test_resolutions=test_resolutions, + encode_input=encode_input, + encode_output=encode_output, + encoding=encoding, + channel_dim=channel_dim, + subsampling_rate=subsampling_rate, + ) + + # return dataloaders for backwards compat + train_loader = DataLoader( + dataset.train_db, + batch_size=batch_size, + num_workers=num_workers, + pin_memory=True, + persistent_workers=False, + ) + + test_loaders = {} + for res, test_bsize in zip(test_resolutions, test_batch_sizes): + test_loaders[res] = DataLoader( + dataset.test_dbs[res], + batch_size=test_bsize, + shuffle=False, + num_workers=num_workers, + pin_memory=True, + persistent_workers=False, + ) + + return train_loader, test_loaders, dataset.data_processor diff --git a/sources/neuraloperator/neuralop/data/datasets/nonlinear_poisson.py b/sources/neuraloperator/neuralop/data/datasets/nonlinear_poisson.py new file mode 100644 index 0000000000000000000000000000000000000000..922c9dec1f93f65af44ba428b46b64bfa56e7771 --- /dev/null +++ b/sources/neuraloperator/neuralop/data/datasets/nonlinear_poisson.py @@ -0,0 +1,559 @@ +from pathlib import Path +import random +from typing import List, Union +import pickle +import numpy as np + +import torch +from torch.utils.data import DataLoader + +from .dict_dataset import DictDataset +from ..transforms.data_processors import DefaultDataProcessor +from .web_utils import download_from_zenodo_record + + +path = Path(__file__).resolve().parent.joinpath("data") + + +def generate_latent_queries( + query_res: int, + pad: float = 0.0, + domain_lims: List[List[float]] = [[-1.4, 1.4], [-1.4, 1.4]], +): + """generate_latent_queries creates the point cloud of query points in latent space + on which to run the FNO. + + Parameters + ---------- + query_res : int + number of points along each dimension in the original grid. + If unpadded, the grid is assumed to be a square in latent space, e.g. no matter + the original coordinates the grid will have an equal number for all dimensions + pad : float, optional + additional side lengths in the latent domain to fill in with query points, by default 0. + * if ``pad > 0``, as many points as possible with the same spacing as the original square + will be concatenated onto the latent grid. + domain_lims : list, optional + limits of the domain to cover with query points, by default [[-1.4,1.4],[-1.4,1.4]] + + Returns + ------- + latent_queries : torch.Tensor + output coordinate point cloud (_, d_1, d_2, 2) + """ + oneDMeshes = [] + for lower, upper in domain_lims: + oneDMesh = np.linspace(lower, upper, query_res) + if pad > 0: + start = np.linspace(lower - pad / query_res, lower, pad + 1) + stop = np.linspace(upper, upper + pad / query_res, pad + 1) + oneDMesh = np.concatenate([start, oneDMesh, stop]) + oneDMeshes.append(oneDMesh) + grid = np.stack(np.meshgrid(*oneDMeshes, indexing="xy")) # c, x, y, z(?) + grid = torch.from_numpy(grid.astype(np.float32)) + latent_queries = grid.permute(*list(range(1, len(domain_lims) + 1)), 0) + return latent_queries + + +def generate_output_queries( + grid_res: int, + coefs: dict, + domain_lims: List[List[float]] = [[-1.4, 1.4], [-1.4, 1.4]], + tol: float = 1e-7, +): + """generate_output_queries creates output query coordinates within the domain + for use in computing physics loss according to the parameters of a particular + instance + + Parameters + ---------- + grid_res : int + resolution of points to generate + coefs : dict[torch.Tensor] + dictionary of coefficients describing a particular instance + of the Poisson equation + domain_lims : List[List[float]], optional + limits of the output domain on which to generate points, + by default [[-1.4,1.4],[-1.4,1.4]] + tol : float, optional + relative tolerance of error for boundary comparison, by default 1e-7 + + Returns + ------- + XY_filtered : torch.Tensor + grid of coordinate points within the boundary of one particular instance of + Poisson's equation. + """ + xi = domain_lims[0][0] + (domain_lims[0][1] - domain_lims[0][0]) * torch.rand(grid_res) + yi = domain_lims[1][0] + (domain_lims[1][1] - domain_lims[1][0]) * torch.rand(grid_res) + + c1, c2 = coefs["c1"].item(), coefs["c2"].item() + + # Rejection sampling + theta = torch.arctan2(xi, yi) + length = torch.sqrt(xi**2 + yi**2) + r0 = 1.0 + c1 * torch.cos(4 * theta) + c2 * torch.cos(8 * theta) + mask = r0 > length - tol + + X_filtered = xi[mask] + Y_filtered = yi[mask] + + XY_filtered = torch.stack((X_filtered, Y_filtered), dim=-1) + + return XY_filtered + + +def source(x, beta, mu_1, mu_2): + # Calculate the squared differences between x and the means + diff = (x[:, 0].unsqueeze(1) - torch.tensor(mu_1)) ** 2 + (x[:, 1].unsqueeze(1) - torch.tensor(mu_2)) ** 2 + exponent = torch.exp(-diff) + + # Multiply by beta and sum along the appropriate axis + result = torch.tensor(beta) * exponent + source_terms = result.sum(dim=1) + + return source_terms + + +class NonlinearPoissonDataset: + """ + NonlinearPoissonDataset provides up to 10,000 instances + of Poisson's equation in 2d over irregular point clouds. Originally created in + [1]_, adapted to include boundary points and more specificity in [2]_. + + Equation: ∇·((1 + 0.1u^2)∇u(x)) = f(x) + + Parameters + ---------- + data_path : Path + full resolved path to .obj dataset file + n_train : int, optional + number of instances in training set, by default 1 + n_test : int, optional + number of instances in test set, by default 1 + n_in : int, optional + number of points in input domain point cloud, by default 6000 + n_out : int, optional + number of domain points in output queries point cloud, by default 6000 + n_bound : int, optional + number of boundary points in output queries point cloud, by default 1024 + n_eval : int, optional + number of randomly generated points in output domain for evaluation, by default 6000 + latent_query_res : int, optional + single-side resolution of latent query grid, by default 48 + domain_padding : int, optional + factor by which to pad the size of latent queries, by default 0 + input_min_sample_points : _type_, optional + minimum number of sample points to use if resampling inputs, by default None + input_max_sample_points : _type_, optional + minimum number of sample points to use if resampling inputs, by default None + input_subsample_level : _type_, optional + if provided, float factor by which to subsample inputs, by default None + output_subsample_level : _type_, optional + if provided, float factor by which to subsample outputs, by default None + train_out_res : _type_, optional + resolution of randomly sampled grid of output queries, by default None + If set to N, output queries are generated by selecting N random X values and + N random Y values, the creating a torch.meshgrid of coordinates from these values, + then filtering out those outside the boundary. + provide_output_queries_as_dict : bool, optional + whether to return a dictionary of output queries, by default True. + * If true, output_queries is a dict: ``{'boundary': boundary_queries, 'domain': domain_queries}`` + * If false, output_queries is a tensor indexed: ``output_queries[:, :num_bound, ...]``: boundary queries, + ``output_queries[:, num_bound:, ...]``: domain queries + download: bool, optional + Whether to download the data file from Zenodo to the provided ``data_path``, by default True. + + References + ---------- + .. [1]: Qin, T., Beatson, A., Oktay, D., McGreivy, N., and Adams, R. "Meta-PDE: + Learning to Solve PDEs Quickly Without a Mesh" (2022). ArXiv preprint, https://arxiv.org/pdf/2211.01604. + + .. [2]: Lin, R., et al. Placeholder Mollified Graph Neural Operators reference. (2025). + """ + + def __init__( + self, + data_path: Union[str, Path], + n_train: int = 1, + n_test: int = 1, + n_in: int = 6000, + n_out: int = 6000, + n_bound: int = 1024, + n_eval: int = 6000, + latent_query_res: int = 48, + domain_padding: int = 0, + input_min_sample_points: int = None, + input_max_sample_points: int = None, + input_subsample_level: int = None, + output_subsample_level: int = None, + train_out_res: int = None, + provide_output_queries_as_dict: bool = True, + download: bool = True, + ): + if isinstance(data_path, str): + data_path = Path(data_path).expanduser().resolve() + + # download data if not already stored at data_path + zenodo_record_id = "15001788" + if download: + if not data_path.exists(): + root_dir = data_path.parent + if not root_dir.exists(): + root_dir.mkdir(parents=True) + download_from_zenodo_record( + record_id=zenodo_record_id, + root=root_dir, + files_to_download=["nonlinear_poisson.obj"], + ) + else: + print(f"File {data_path} already exists. Skipping download.") + + # Load the data + with open(data_path, "rb") as data_file: + data = pickle.load(data_file) + print("Dictionary loaded successfully.") + + random.shuffle(data) + train_end_idx = int(0.7 * len(data)) + print(f"Loading {n_train} train instances...") + if n_test > len(data) - train_end_idx: + n_test = len(data) - train_end_idx + print(f"Loading {n_test} test instances...") + + data_list = [] + + for idx, instance in enumerate(data): + f_f = torch.tensor(instance["train_source_terms_domain"][:n_in], dtype=torch.float32) + f_g = torch.tensor(instance['train_bc_domain'][:n_in], dtype=torch.float32) + f_dist = torch.tensor(instance["train_distances_domain"][:n_in], dtype=torch.float32) + + input_geom = torch.tensor(instance["train_points_domain"][:n_in], dtype=torch.float32) + + if idx < n_train: + if train_out_res: + # Using uniform output mesh + out_p_domain = generate_output_queries(train_out_res, instance["coefs"]) + out_source_domain = source( + out_p_domain, + instance["coefs"]["beta"], + instance["coefs"]["mu_1"], + instance["coefs"]["mu_2"], + ) + y_domain = torch.ones(out_p_domain.shape[0]) + out_p_domain.requires_grad = True + else: + # Using randomly sampled Fenics mesh + out_p_domain = torch.tensor(instance["val_points_domain"][:n_out], dtype=torch.float32) + out_source_domain = torch.tensor(instance["val_source_terms_domain"][:n_out], dtype=torch.float32) + y_domain = torch.tensor(instance["val_values_domain"][:n_out], dtype=torch.float32) + out_p_domain.requires_grad = True + + # Give the boundary points for the output during training + out_p_bound = torch.tensor(instance["val_points_boundary"][:n_bound], dtype=torch.float32) + out_source_bound = torch.tensor(instance["val_source_terms_boundary"][:n_bound], dtype=torch.float32) + y_bound = torch.tensor(instance["val_values_boundary"][:n_bound], dtype=torch.float32) + + out_p_bound.requires_grad = True + out_source = torch.cat((out_source_bound, out_source_domain)) + else: + out_p_bound = None + out_p_domain = torch.tensor(instance["val_points_domain"][:n_eval], dtype=torch.float32) + out_source_domain = torch.tensor(instance["val_source_terms_domain"][:n_eval], dtype=torch.float32) + y_domain = torch.tensor(instance["val_values_domain"][:n_eval], dtype=torch.float32) + y_bound = None + + input_geom = torch.vstack((torch.tensor(instance["train_points_boundary"][:n_in], dtype=torch.float32), input_geom)) + latent_queries = generate_latent_queries(query_res=latent_query_res,pad=domain_padding) + + # Add source terms on the boundary and interior + f_f = torch.cat((torch.tensor(instance["train_source_terms_boundary"][:n_in], dtype=torch.float32), f_f)) + f_g = torch.cat((torch.tensor(instance["train_bc_boundary"][:n_in], dtype=torch.float32), f_g)) + f_dist = torch.cat((torch.zeros(n_in), f_dist)) + f_f = f_f.unsqueeze(dim=-1) + f_g = f_g.unsqueeze(dim=-1) + f_dist = f_dist.unsqueeze(dim=-1) + f = torch.cat((f_f, f_g, f_dist), dim=-1) + + data_dict = { + "x": f, # input function + # input coords + "input_geom": input_geom, + # latent grid + "latent_queries": latent_queries, + # domain info + "output_queries_domain": out_p_domain, + "output_source_terms_domain": out_source_domain, + "y_domain": y_domain, + "coefs": instance["coefs"], + "num_boundary": n_bound, + "out_sub_level": output_subsample_level + if output_subsample_level + else 1, + } + + # insert boundary y and output queries + # avoid collating None for boundary values by inserting only if the tensors exist + if y_bound is not None: + data_dict["y_bound"] = y_bound + data_dict["output_queries_bound"] = out_p_bound + data_dict["output_source_terms_bound"] = out_source_bound + data_list.append(data_dict) + + self._train_db = data_list[:n_train] + self._test_db = data_list[train_end_idx : train_end_idx + n_test] + self.data_processor = PoissonGINODataProcessor( + input_min=input_min_sample_points, + input_max=input_max_sample_points, + input_sub_level=input_subsample_level, + output_sub_level=output_subsample_level, + return_dict=provide_output_queries_as_dict, + ) + + @property + def train_db(self): + return self._train_db + + @property + def test_db(self): + return self._test_db + + +def load_nonlinear_poisson_pt( + data_path, + query_res=48, + domain_padding=0, + val_on_same_instance=False, + n_train=1, + n_test=1, + n_in=6000, + n_out=6000, + n_eval=6000, + n_bound=1024, + input_min_sample_points=None, + input_max_sample_points=None, + input_subsample_level=None, + output_subsample_level=None, + train_out_res=None, + return_dict=True, +): + dataset = NonlinearPoissonDataset( + data_path=data_path, + n_train=n_train, + n_test=n_test, + n_in=n_in, + n_out=n_out, + n_eval=n_eval, + n_bound=n_bound, + latent_query_res=query_res, + domain_padding=domain_padding, + train_out_res=train_out_res, + ) + + if val_on_same_instance: + train_dataloader = test_dataloader = DataLoader(DictDataset(dataset.train_db[1:])) + else: + train_dataloader = DataLoader(DictDataset(dataset.train_db)) + test_dataloader = DataLoader(DictDataset(dataset.test_db)) + + data_processor = PoissonGINODataProcessor( + input_min=input_min_sample_points, + input_max=input_max_sample_points, + input_sub_level=input_subsample_level, + output_sub_level=output_subsample_level, + return_dict=return_dict, + ) + return train_dataloader, test_dataloader, data_processor + + +class PoissonGINODataProcessor(DefaultDataProcessor): + """PoissonGINODataProcessor does the same thing + as a DefaultDataProcessor with the addition of randomly subsampling + points in the model's domain and codomain. Written specifically + for the forward call signature of neuralop.models.GINO + """ + + def __init__( + self, + device="cpu", + in_normalizer=None, + out_normalizer=None, + positional_encoding=None, + input_min=100, + input_max=1000, + input_sub_level=None, + output_sub_level=None, + return_dict=True, + ): + """A simple processor to pre/post process data before training/inferencing a model. + + Parameters + ---------- + in_normalizer : Transform, optional, default is None + normalizer (e.g. StandardScaler) for the input samples + out_normalizer : Transform, optional, default is None + normalizer (e.g. StandardScaler) for the target and predicted samples + positional_encoding : Processor, optional, default is None + class that appends a positional encoding to the input + input_sub_level : float, optional, default is None + level at which to subsample points in the domain (between 0 and 1) + output_sub_level : float, optional, default is None + level at which to subsample points in the codomain (between 0 and 1) + """ + super().__init__() + self.in_normalizer = in_normalizer + self.out_normalizer = out_normalizer + self.positional_encoding = positional_encoding + self.input_sub_level = input_sub_level + if not output_sub_level: + output_sub_level = 1 + self.output_sub_level = output_sub_level + self.device = device + self.input_min = input_min + self.input_max = input_max + self.return_dict = return_dict + + def preprocess(self, data_dict, batched=True): + # load input function of shape (_, n_in, in_dim) + x = data_dict["x"].to(self.device) + + # Load input geometry of shape (_, n_in, 2) + input_geom = data_dict["input_geom"].to(self.device) + + # squeeze out extra dims if DataLoader's builtin collate adds one + if input_geom.ndim == 4: + input_geom = input_geom.squeeze(0) + + if x.ndim == 4: + x = x.squeeze(0) + + # Subsample inputs along the point dimension of the tensor (1) + if self.input_sub_level is not None: + # Sample set percentage + n_in = int(input_geom.shape[1] * self.input_sub_level) + else: + # Sample random in between range + n_in = random.randint(self.input_min, self.input_max) + + input_indices = random.sample(list(range(input_geom.shape[-2])), k=n_in) + x = x[:, input_indices, ...] + input_geom = input_geom[:, input_indices, ...] + + # Load output truth values of shape (_, n_out, _) + # if in training mode, values will be stored separately + # for the boundary conditions and interior of the domain + if "y_bound" in data_dict.keys(): + y_bound = data_dict["y_bound"] + else: + y_bound = None + + y_domain = data_dict["y_domain"] + + # Load output query coordinates of shape (_, n_out, 2) + # if in training mode, values will be stored separately + # for the boundary conditions and interior of the domain + output_queries_bound = data_dict.get("output_queries_bound", None) + output_queries_domain = data_dict["output_queries_domain"] + + # Subsample all points defined on the output domain/boundary + # along the point dimension (1) + n_bound = data_dict["num_boundary"].item() + n_bound_out = n_bound * self.output_sub_level + n_domain_out = output_queries_domain.shape[1] * self.output_sub_level + + output_indices_bound = random.sample(list(range(0, n_bound)), k=int(n_bound_out)) + output_indices_domain = random.sample(list(range(0, output_queries_domain.shape[1])), k=int(n_domain_out)) + + # boundary points in both output queries and ground truth + # are only stored separately in train mode + if y_bound is not None: + y_bound = y_bound[:, output_indices_bound] + output_queries_bound = output_queries_bound[:, output_indices_bound] + + y_domain = y_domain[:, output_indices_domain] + output_queries_domain = output_queries_domain[:, output_indices_domain] + + if "output_source_terms_domain" in data_dict.keys(): + output_source_terms_domain = data_dict["output_source_terms_domain"] + output_source_terms_domain = output_source_terms_domain[:, output_indices_domain, ...] + else: + output_source_terms_domain = None + + if "output_source_terms_bound" in data_dict.keys(): + output_source_terms_bound = data_dict["output_source_terms_bound"] + output_source_terms_bound = output_source_terms_bound[:, output_indices_bound, ...] + else: + output_source_terms_bound = None + + # when output points and query coords are stored separately, we pass + # the queries into the GINO model as a dictionary, and receive a dict + # of outputs in return corresponding to the function evaluated at each set of queries. + if y_bound is not None: + # add feature dimensions to make y shape (_, n_out, 1) + y_bound = y_bound.unsqueeze(-1).to(self.device) + y_domain = y_domain.unsqueeze(-1).to(self.device) + + if self.out_normalizer is not None and self.train: + y_bound = self.out_normalizer.transform(y_bound) + y_domain = self.out_normalizer.transform(y_domain) + + if self.return_dict: + y = { + "boundary": y_bound, + "domain": y_domain, + } + else: + y = torch.cat((y_bound, y_domain), dim=1) + # load both boundaries and interior points to device so they exist + # separately in the computational graph for later use in physics + output_queries_domain = output_queries_domain.to(self.device) + output_queries_bound = output_queries_bound.to(self.device) + if self.return_dict: + output_queries = { + "boundary": output_queries_bound, + "domain": output_queries_domain, + } + else: + output_queries = torch.cat((output_queries_bound, output_queries_domain), dim=1) + else: + y = y_domain.unsqueeze(-1).to(self.device) # add feature dim + output_queries = output_queries_domain.to(self.device) + if self.out_normalizer is not None and self.train: + y = self.out_normalizer.transform(y) + + if self.in_normalizer is not None: + x = self.in_normalizer.transform(x) + if self.positional_encoding is not None: + x = self.positional_encoding(x, batched=batched) + + data_dict["x"] = x + + # In eval mode, pass whole tensors instead of dicts of queries and y + if not self.training and isinstance(y, dict): + y = torch.cat((y["boundary"], y["domain"]), dim=1) + output_queries = torch.cat( + (output_queries["boundary"], output_queries["domain"]), dim=1 + ) + data_dict["y"] = y + data_dict["input_geom"] = input_geom.to(self.device) + data_dict["output_queries"] = output_queries + + if output_source_terms_domain is not None: + data_dict["output_source_terms_domain"] = output_source_terms_domain.to(self.device) + + # no transformation needed for the cube of latent queries + data_dict["latent_queries"] = data_dict["latent_queries"].to(self.device).squeeze(0) + + return data_dict + + def postprocess(self, output, data_dict): + y = data_dict["y"] + if self.out_normalizer and not self.train: + output = self.out_normalizer.inverse_transform(output) + y = self.out_normalizer.inverse_transform(y) + data_dict["y"] = y + return output, data_dict + + +if __name__ == "__main__": + train_data = load_nonlinear_poisson_pt(str(path)) diff --git a/sources/neuraloperator/neuralop/data/datasets/ot_datamodule.py b/sources/neuraloperator/neuralop/data/datasets/ot_datamodule.py new file mode 100644 index 0000000000000000000000000000000000000000..4eb84fe798f54247353ab503c53f584bd9abe7ed --- /dev/null +++ b/sources/neuraloperator/neuralop/data/datasets/ot_datamodule.py @@ -0,0 +1,235 @@ +from pathlib import Path +from timeit import default_timer +from typing import List, Union + +import numpy as np + +# import open3d for io if built. Otherwise, +# the class will build, but no files will be loaded. +try: + import open3d as o3d + + o3d_warn = False +except ModuleNotFoundError: + o3d_warn = True + +try: + import ot + from ot.bregman import empirical_sinkhorn2_geomloss + + ot_warn = False +except ModuleNotFoundError: + ot_warn = True + +import torch + +# Get the directory of the current script +script_dir = Path(__file__).parent + + +class OTDataModule: + def __init__( + self, + root_dir: Union[str, Path], + item_dir_name: Union[str, Path], + n_train: int = None, + n_test: int = None, + attributes: List[str] = None, + expand_factor: float = 3.0, + reg: float = 1e-06, + device: Union[str, torch.device] = "cuda", + ): + """MeshDataModule provides a general dataset for irregular coordinate meshes + for use in a GNO-based architecture + + Parameters + ---------- + root_dir : Union[str, Path] + str or Path to root directory of CFD dataset + item_dir_name : Union[str, Path] + directory in which individual item subdirs are stored + n_train : int, optional + hard limit on number of training examples + if n_train is greater than the actual number + of training examples available, nothing is changed + n_test : int, optional + hard limit on number of test examples + if n_test is greater than the actual number + of testing examples available, nothing is changed + attributes : List[str], optional + list of string keys for attributes in the dataset to return + as keys for each batch dict + expand_factor : float, optional + Scale factor to map physical mesh size to latent mesh size (e.g., torus/sphere). + Affects OT plan surjectivity: smaller values may lead to incomplete mappings, while larger values increase computational cost but improve surjectivity. + Choose a value balancing accuracy and efficiency, by default 3. + reg : float, optional + Regularization coefficient for the Sinkhorn algorithm. + Affects OT plan surjectivity: smaller values increase precision (where fewer non-surjective plans indicate higher precision) but incur higher computational cost. + Choose a value balancing accuracy and efficiency, by default 1e-06. + device : Union[str, torch.device], optional + Device for OT computation. + """ + self.device = device + + if o3d_warn: + print( + "Warning: you are attempting to run MeshDataModule without the required dependency open3d." + ) + raise ModuleNotFoundError() + if isinstance(root_dir, str): + root_dir = Path(root_dir) + + # Ensure path is valid + root_dir = root_dir.expanduser() + assert root_dir.exists(), "Path does not exist" + assert root_dir.is_dir(), "Path is not a directory" + + # Read train and test indicies + with open(root_dir / "train.txt") as file: + train_ind = file.readline().split(",") + + with open(root_dir / "test.txt") as file: + test_ind = file.readline().split(",") + + if n_train is not None: + if n_train < len(train_ind): + train_ind = train_ind[0:n_train] + + if n_test is not None: + if n_test < len(test_ind): + test_ind = test_ind[0:n_test] + + # set train and test sizes + train_ind = train_ind[0:n_train] + test_ind = test_ind[0:n_test] + n_train = len(train_ind) + n_test = len(test_ind) + print("n_train n_test are", n_train, n_test) + + mesh_ind = train_ind + test_ind + # remove trailing newlines from train and test indices + mesh_ind = [x.rstrip() for x in mesh_ind] + + data_dir = root_dir / "data" + + # Load all meshes and compute OT + data = [] + n_non_surjective = 0 + n_missed_points = 0 + for ind in mesh_ind: + mesh = o3d.io.read_triangle_mesh( + str(data_dir / (item_dir_name + ind + "/tri_mesh.ply")) + ) + target = torch.from_numpy( + np.asarray(mesh.vertices).squeeze().astype(np.float32()) + ).to(self.device) # (3586,3) car vertices + mesh.compute_vertex_normals() + normal = torch.from_numpy(np.asarray(mesh.vertex_normals).astype(np.float32())) + + # OT + n_t = len(target) # number of target samples + n_s_sqrt = int(np.sqrt(expand_factor) * np.ceil(np.sqrt(n_t))) # sqrt of the number of source samples + source = self.torus_grid(n_s_sqrt) # build source gird + _, log = empirical_sinkhorn2_geomloss( + X_s=source.to(self.device), X_t=target, reg=reg, log=True + ) # utilize weighted Sinkhorn a=a.to(device), b=b.to(device), + gamma = log["lazy_plan"][:].detach() # convert the lazy tensor to torch.tensor (dense) + + # normalize the OT plan matrix by column + row_norms = torch.norm(gamma, p=1, dim=1, keepdim=True) + gamma_encoder = gamma / row_norms + + # transport target to source + transport = torch.mm(gamma_encoder, target) + + # encoder: target -> source + distances = torch.cdist(transport, target) + # find the closest point in "target" (car vertices) to each point in "transport" (latent grids) + indices_encoder = torch.argmin(distances, dim=1) + + # reset the transport as the closest point in target + transport = target[indices_encoder] + unique = len(torch.unique(indices_encoder)) + n_missed_points += n_t - unique + if unique != n_t: + n_non_surjective += 1 + + # decoder: source -> target + # find the closest point in "transport" (latent grids) to each point in "target" (car vertices) + indices_decoder = torch.argmin(distances, dim=0) + + item_dict = { + "target": target.cpu(), + "source": source.cpu(), + "ind_enc": indices_encoder.cpu(), + "ind_dec": indices_decoder.cpu(), + "nor_t": normal, + "nor_s": self.torus_normals(n_s_sqrt), + "trans": transport.cpu(), + } + for attr in attributes: + if attr not in item_dict: + attr_data = np.load( + str(data_dir / (item_dir_name + ind + "/" + attr + ".npy")) + ) + item_dict[attr] = torch.from_numpy(attr_data.astype(np.float32())) + data.append(item_dict) + + self.data = data + torch.save( + data, + script_dir + / "data" + / f"ot_expand{expand_factor}_reg{reg}_train{n_train}_test{n_test}.pt", + ) + print( + f"Number of none surjective OT plan is {n_non_surjective:d}; average missed points is {n_missed_points/(n_train+n_test):.2f}" + ) + + def read_indices(self, file_path): + with open(file_path, "r") as file: + indices = [line.strip() for line in file if line.strip().isdigit()] + return indices + + def torus_grid(self, n_s_sqrt, r=0.5, R=1.0): + theta = torch.linspace(0, 2 * torch.pi, n_s_sqrt + 1)[:-1] + phi = torch.linspace(0, 2 * torch.pi, n_s_sqrt + 1)[:-1] + # Create a grid using meshgrid + X, Y = torch.meshgrid(theta, phi, indexing="ij") + points = torch.stack((X, Y)).reshape((2, -1)).T + + x = (R + r * torch.cos(points[:, 0])) * torch.cos(points[:, 1]) + y = (R + r * torch.cos(points[:, 0])) * torch.sin(points[:, 1]) + z = r * torch.sin(points[:, 0]) + grid = torch.stack((x, y, z), dim=1) + + return grid + + def torus_normals(self, n_s_sqrt, r=0.5, R=1.0): + theta = torch.linspace(0, 2 * np.pi, n_s_sqrt + 1)[:-1] + phi = torch.linspace(0, 2 * np.pi, n_s_sqrt + 1)[:-1] + theta, phi = torch.meshgrid(theta, phi, indexing="ij") + + # Partial derivatives + # dP/dtheta + dx_dtheta = -r * torch.sin(theta) * torch.cos(phi) + dy_dtheta = -r * torch.sin(theta) * torch.sin(phi) + dz_dtheta = r * torch.cos(theta) + + # dP/dphi + dx_dphi = -(R + r * torch.cos(theta)) * torch.sin(phi) + dy_dphi = (R + r * torch.cos(theta)) * torch.cos(phi) + dz_dphi = torch.zeros_like(dx_dphi) + + # Cross product to find normal vectors + nx = dy_dtheta * dz_dphi - dz_dtheta * dy_dphi + ny = dz_dtheta * dx_dphi - dx_dtheta * dz_dphi + nz = dx_dtheta * dy_dphi - dy_dtheta * dx_dphi + + # Stack and normalize + normals = torch.stack((nx, ny, nz), dim=-1) + norm = torch.linalg.norm(normals, dim=2, keepdim=True) + normals = normals / norm + + return normals diff --git a/sources/neuraloperator/neuralop/data/datasets/pt_dataset.py b/sources/neuraloperator/neuralop/data/datasets/pt_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..2b2a107012fab1c961d7020ce0042cc560035844 --- /dev/null +++ b/sources/neuraloperator/neuralop/data/datasets/pt_dataset.py @@ -0,0 +1,247 @@ +from functools import partialmethod +from pathlib import Path +from typing import List, Union, Optional + +import torch + +from .tensor_dataset import TensorDataset +from ..transforms.data_processors import DefaultDataProcessor +from ..transforms.normalizers import UnitGaussianNormalizer + + +class PTDataset: + """PTDataset is a base Dataset class for our library. + PTDatasets contain input-output pairs a(x), u(x) and may also + contain additional information, e.g. function parameters, + input geometry or output query points. + + datasets may implement a download flag at init, which provides + access to a number of premade datasets for sample problems provided + in our Zenodo archive. + + Parameters + ---------- + root_dir : Union[Path, str] + root at which to download data files + dataset_name : str + prefix of pt data files to store/access + n_train : int + number of train instances + n_tests : List[int] + number of test instances per test dataset + batch_size : int + batch size of training set + test_batch_sizes : List[int] + batch size of test sets + train_resolution : int + resolution of data for training set + test_resolutions : List[int] + resolution of data for testing sets + encode_input : bool, optional + whether to normalize inputs in provided DataProcessor, + by default False + encode_output : bool, optional + whether to normalize outputs in provided DataProcessor, + by default True + encoding : str, optional + parameter for input/output normalization. Whether + to normalize by channel ("channel-wise") or + by pixel ("pixel-wise"), default "channel-wise" + input_subsampling_rate : int or List[int], optional + rate at which to subsample each input dimension, by default None + output_subsampling_rate : int or List[int], optional + rate at which to subsample each output dimension, by default None + channel_dim : int, optional + dimension of saved tensors to index data channels, by default 1 + dtype : torch.dtype, optional + dtype to cast input tensors to after loading. If None, the original + dtype of the saved data is preserved (e.g. torch.complex64 stays + complex). Pass torch.float32 to restore the previous default behaviour. + Default is None. + channels_squeezed : bool, optional + If the channels dim is 1, whether that is explicitly kept in the saved tensor. + If not, we need to unsqueeze it to explicitly have a channel dim. + Only applies when there is only one data channel, as in our example problems + Defaults to True + + All datasets are required to expose the following attributes after init: + + train_db: torch.utils.data.Dataset of training examples + test_db: torch.utils.data.Dataset of test examples + data_processor: neuralop.data.transforms.DataProcessor to process data examples + optional, default is None + """ + + def __init__( + self, + root_dir: Union[Path, str], + dataset_name: str, + n_train: int, + n_tests: List[int], + batch_size: int, + test_batch_sizes: List[int], + train_resolution: int, + test_resolutions: List[int], + encode_input: bool = False, + encode_output: bool = True, + encoding="channel-wise", + input_subsampling_rate=None, + output_subsampling_rate=None, + channel_dim=1, + dtype=None, + channels_squeezed=True, + ): + """Initialize the PTDataset. + + See class docstring for detailed parameter descriptions. + """ + + if isinstance(root_dir, str): + root_dir = Path(root_dir) + + self.root_dir = root_dir + + # save dataloader properties for later + self.batch_size = batch_size + self.test_resolutions = test_resolutions + self.test_batch_sizes = test_batch_sizes + + # Load train data + + data = torch.load( + Path(root_dir).joinpath(f"{dataset_name}_train_{train_resolution}.pt").as_posix() + ) + + x_train = data["x"].to(dtype).clone() + if channels_squeezed: + x_train = x_train.unsqueeze(channel_dim) + + # optionally subsample along data indices + ## Input subsampling + input_data_dims = data["x"].ndim - 2 # batch and channels + # convert None and 0 to 1 + if not input_subsampling_rate: + input_subsampling_rate = 1 + if not isinstance(input_subsampling_rate, list): + # expand subsampling rate along dims if one per dim is not provided + input_subsampling_rate = [input_subsampling_rate] * input_data_dims + # make sure there is one subsampling rate per data dim + assert ( + len(input_subsampling_rate) == input_data_dims + ), f"Error: length mismatch between input_subsampling_rate and dimensions of data.\ + input_subsampling_rate must be one int shared across all dims, or an iterable of\ + length {len(input_data_dims)}, got {input_subsampling_rate}" + # Construct full indices along which to grab X + train_input_indices = [slice(0, n_train, None)] + [slice(None, None, rate) for rate in input_subsampling_rate] + train_input_indices.insert(channel_dim, slice(None)) + train_input_indices = tuple(train_input_indices) + x_train = x_train[train_input_indices] + + y_train = data["y"].clone() + if channels_squeezed: + y_train = y_train.unsqueeze(channel_dim) + + ## Output subsampling + output_data_dims = data["y"].ndim - 2 + # convert None and 0 to 1 + if not input_subsampling_rate: + output_subsampling_rate = 1 + if not isinstance(output_subsampling_rate, list): + # expand subsampling rate along dims if one per dim is not provided + output_subsampling_rate = [output_subsampling_rate] * output_data_dims + # make sure there is one subsampling rate per data dim + assert ( + len(output_subsampling_rate) == output_data_dims + ), f"Error: length mismatch between output_subsampling_rate and dimensions of data.\ + input_subsampling_rate must be one int shared across all dims, or an iterable of\ + length {len(output_data_dims)}, got {output_subsampling_rate}" + + # Construct full indices along which to grab Y + train_output_indices = [slice(0, n_train, None)] + [slice(None, None, rate) for rate in output_subsampling_rate] + train_output_indices.insert(channel_dim, slice(None)) + train_output_indices = tuple(train_output_indices) + y_train = y_train[train_output_indices] + + del data + + # Fit optional encoders to train data + # Actual encoding happens within DataProcessor + if encode_input: + if encoding == "channel-wise": + reduce_dims = list(range(x_train.ndim)) + # preserve mean for each channel + reduce_dims.pop(channel_dim) + elif encoding == "pixel-wise": + reduce_dims = [0] + + input_encoder = UnitGaussianNormalizer(dim=reduce_dims) + input_encoder.fit(x_train) + else: + input_encoder = None + + if encode_output: + if encoding == "channel-wise": + reduce_dims = list(range(y_train.ndim)) + # preserve mean for each channel + reduce_dims.pop(channel_dim) + elif encoding == "pixel-wise": + reduce_dims = [0] + + output_encoder = UnitGaussianNormalizer(dim=reduce_dims) + output_encoder.fit(y_train) + else: + output_encoder = None + + # Save train dataset + self._train_db = TensorDataset( + x_train, + y_train, + ) + + # create DataProcessor + self._data_processor = DefaultDataProcessor( + in_normalizer=input_encoder, out_normalizer=output_encoder + ) + + # load test data + self._test_dbs = {} + for res, n_test in zip(test_resolutions, n_tests): + print(f"Loading test db for resolution {res} with {n_test} samples ") + data = torch.load(Path(root_dir).joinpath(f"{dataset_name}_test_{res}.pt").as_posix()) + + x_test = data["x"].to(dtype).clone() + if channels_squeezed: + x_test = x_test.unsqueeze(channel_dim) + # optionally subsample along data indices + test_input_indices = [slice(0, n_test, None)] + [slice(None, None, rate) for rate in input_subsampling_rate] + test_input_indices.insert(channel_dim, slice(None)) + test_input_indices = tuple(test_input_indices) + x_test = x_test[test_input_indices] + + y_test = data["y"].clone() + if channels_squeezed: + y_test = y_test.unsqueeze(channel_dim) + test_output_indices = [slice(0, n_test, None)] + [slice(None, None, rate) for rate in output_subsampling_rate] + test_output_indices.insert(channel_dim, slice(None)) + test_output_indices = tuple(test_output_indices) + y_test = y_test[test_output_indices] + + del data + + test_db = TensorDataset( + x_test, + y_test, + ) + self._test_dbs[res] = test_db + + @property + def data_processor(self): + return self._data_processor + + @property + def train_db(self): + return self._train_db + + @property + def test_dbs(self): + return self._test_dbs diff --git a/sources/neuraloperator/neuralop/data/datasets/spherical_swe.py b/sources/neuraloperator/neuralop/data/datasets/spherical_swe.py new file mode 100644 index 0000000000000000000000000000000000000000..ea400c1aaf7ea240715021e096b71254ec70db80 --- /dev/null +++ b/sources/neuraloperator/neuralop/data/datasets/spherical_swe.py @@ -0,0 +1,130 @@ +from math import ceil, floor + +import torch +from torch.utils.data import DataLoader +from torch_harmonics.examples import ShallowWaterSolver + + +def load_spherical_swe( + n_train, + n_tests, + batch_size, + test_batch_sizes, + train_resolution=(256, 512), + test_resolutions=[(256, 512)], + device=torch.device("cpu"), +): + """Load the Spherical Shallow Water equations Dataloader""" + + print(f"Loading train dataloader at resolution {train_resolution} with {n_train} samples and batch-size={batch_size}") + + train_dataset = SphericalSWEDataset(dims=train_resolution, num_examples=n_train, device=device) + + train_loader = DataLoader( + train_dataset, + batch_size=batch_size, + shuffle=True, + num_workers=0, + persistent_workers=False, + ) + + test_loaders = dict() + for res, n_test, test_batch_size in zip(test_resolutions, n_tests, test_batch_sizes): + print(f"Loading test dataloader at resolution {res} with {n_test} samples and batch-size={test_batch_size}") + + test_dataset = SphericalSWEDataset(dims=res, num_examples=n_test, device=device) + test_loader = DataLoader( + test_dataset, + batch_size=test_batch_size, + shuffle=True, + num_workers=0, + persistent_workers=False, + ) + test_loaders[res] = test_loader + + return train_loader, test_loaders + + +class SphericalSWEDataset(torch.utils.data.Dataset): + """Custom Dataset class for PDE training data""" + + def __init__( + self, + dt=3600, + dims=(256, 512), + initial_condition="random", + num_examples=32, + device=torch.device("cpu"), + normalize=True, + stream=None, + ): + # Caution: this is a heuristic which can break and lead to diverging results + dt_min = 256 / dims[0] * 150 + nsteps = int(floor(dt / dt_min)) + + self.num_examples = num_examples + self.device = device + self.stream = stream + + self.nlat = dims[0] + self.nlon = dims[1] + + # number of solver steps used to compute the target + self.nsteps = nsteps + self.normalize = normalize + + lmax = ceil(self.nlat / 3) + mmax = lmax + dt_solver = dt / float(self.nsteps) + self.solver = ( + ShallowWaterSolver( + self.nlat, + self.nlon, + dt_solver, + lmax=lmax, + mmax=mmax, + grid="equiangular" + ) + .to(self.device).float() + ) + + self.set_initial_condition(ictype=initial_condition) + + if self.normalize: + inp0, _ = self._get_sample() + self.inp_mean = torch.mean(inp0, dim=(-1, -2)).reshape(-1, 1, 1) + self.inp_var = torch.var(inp0, dim=(-1, -2)).reshape(-1, 1, 1) + + def __len__(self): + length = self.num_examples if self.ictype == "random" else 1 + return length + + def set_initial_condition(self, ictype="random"): + self.ictype = ictype + + def set_num_examples(self, num_examples=32): + self.num_examples = num_examples + + def _get_sample(self): + if self.ictype == "random": + inp = self.solver.random_initial_condition(mach=0.2) + elif self.ictype == "galewsky": + inp = self.solver.galewsky_initial_condition() + + # solve pde for n steps to return the target + tar = self.solver.timestep(inp, self.nsteps) + inp = self.solver.spec2grid(inp) + tar = self.solver.spec2grid(tar) + + return inp, tar + + def __getitem__(self, index): + with torch.inference_mode(): + with torch.no_grad(): + inp, tar = self._get_sample() + + if self.normalize: + inp = (inp - self.inp_mean) / torch.sqrt(self.inp_var) + tar = (tar - self.inp_mean) / torch.sqrt(self.inp_var) + + return {"x": inp.clone(), "y": tar.clone()} diff --git a/sources/neuraloperator/neuralop/data/datasets/tensor_dataset.py b/sources/neuraloperator/neuralop/data/datasets/tensor_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..f75bf60dccacf32de493aa7926ab8f91613e4f46 --- /dev/null +++ b/sources/neuraloperator/neuralop/data/datasets/tensor_dataset.py @@ -0,0 +1,54 @@ +from torch.utils.data.dataset import Dataset + + +class TensorDataset(Dataset): + def __init__(self, x, y, transform_x=None, transform_y=None): + assert x.size(0) == y.size(0), "Size mismatch between tensors" + self.x = x + self.y = y + self.transform_x = transform_x + self.transform_y = transform_y + + def __getitem__(self, index): + x = self.x[index] + y = self.y[index] + + if self.transform_x is not None: + x = self.transform_x(x) + + if self.transform_y is not None: + y = self.transform_y(y) + + return {"x": x, "y": y} + + def __len__(self): + return self.x.size(0) + + +class GeneralTensorDataset(Dataset): + def __init__(self, sets, transforms): + assert len(sets) == len(transforms), "Size mismatch between number of tensors and transforms" + self.n = len(sets) + if self.n > 1: + for j in range(1,self.n): + assert sets[j].size(0) == sets[0].size(0), "Size mismatch between tensors" + + self.sets = sets + self.transforms = transforms + + def __getitem__(self, index): + if self.n > 1: + items = [] + for j in range(self.n): + items.append(self.sets[j][index]) + if self.transforms[j] is not None: + items[j] = self.transforms[j](items[j]) + else: + items = self.sets[0][index] + if self.transforms[0] is not None: + items = self.transforms[0](items) + + return items + + def __len__(self): + return self.sets[0].size(0) diff --git a/sources/neuraloperator/neuralop/data/datasets/tests/__init__.py b/sources/neuraloperator/neuralop/data/datasets/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/sources/neuraloperator/neuralop/data/datasets/tests/test_ptdatasets.py b/sources/neuraloperator/neuralop/data/datasets/tests/test_ptdatasets.py new file mode 100644 index 0000000000000000000000000000000000000000..67e0d1c1572fc990a78a9157ba295607ce35a539 --- /dev/null +++ b/sources/neuraloperator/neuralop/data/datasets/tests/test_ptdatasets.py @@ -0,0 +1,77 @@ +from ..burgers import Burgers1dTimeDataset +from ..darcy import DarcyDataset +from ..navier_stokes import NavierStokesDataset +from pathlib import Path + +import os +import shutil + +import pytest + +test_data_dir = Path("./dataset_test") + + +@pytest.mark.parametrize("resolution", [16]) +def test_DarcyDatasetDownload(resolution): + dataset = DarcyDataset( + root_dir=test_data_dir, + n_train=5, + n_tests=[5], + batch_size=1, + test_batch_sizes=[1], + train_resolution=resolution, + test_resolutions=[resolution, resolution * 2], + download=True, + ) + + downloaded_files = os.listdir(test_data_dir) + for split in ["train", "test"]: + for res in [resolution, resolution * 2]: + assert f"darcy_{split}_{res}.pt" in downloaded_files + assert dataset.train_db + assert dataset.test_dbs + assert dataset.data_processor + shutil.rmtree(test_data_dir) + + +burgers_root = Path("./neuralop/data/datasets/data/").resolve() + + +@pytest.mark.parametrize("resolution", [16]) +def test_BurgersDataset(resolution): + dataset = Burgers1dTimeDataset( + root_dir=burgers_root, + n_train=5, + n_tests=[5], + batch_size=1, + test_batch_sizes=[1], + train_resolution=resolution, + test_resolutions=[resolution], + ) + + assert dataset.train_db + assert dataset.test_dbs + assert dataset.data_processor + + +def test_NSDownload(): + # monkeypatch bypasses confirmation input + dataset = NavierStokesDataset( + root_dir=test_data_dir, + n_train=5, + n_tests=[5], + batch_size=1, + test_batch_sizes=[1], + train_resolution=128, + test_resolutions=[128], + download=True, + ) + + downloaded_files = os.listdir(test_data_dir) + for split in ["train", "test"]: + for res in [128]: + assert f"nsforcing_{split}_{res}.pt" in downloaded_files + assert dataset.train_db + assert dataset.test_dbs + assert dataset.data_processor + shutil.rmtree(test_data_dir) diff --git a/sources/neuraloperator/neuralop/data/datasets/the_well_dataset.py b/sources/neuraloperator/neuralop/data/datasets/the_well_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..bcbbe4930f156042838801813e2a127ff9f00a19 --- /dev/null +++ b/sources/neuraloperator/neuralop/data/datasets/the_well_dataset.py @@ -0,0 +1,224 @@ +from pathlib import Path +from typing import Literal, List +import yaml + +import torch + +from the_well.data import WellDataset +from the_well.utils.download import well_download + + +from ..transforms.normalizers import UnitGaussianNormalizer +from ..transforms.the_well_data_processors import TheWellDataProcessor + + +class TheWellDataset: + """__init__ _summary_ + Base Class for TheWell [1]_ datasets + + Parameters + ---------- + root_dir : Path + shared root path at which to download all TheWell datasets + well_dataset_name : str + name of the dataset to download + n_train : int + _description_ + n_test : int + _description_ + download : bool, optional + _description_, by default True + + References + ---------- + .. [1] : Ohana, R., McCabe, M., Meyer, L., Morel, R., Agocs, F., Benitez, M., Berger, M., + Burkhart, B., Dalziel, S., Fielding, D., Fortunato, D., Goldberg, J., Hirashima, K., Jiang, Y., + Kerswell, R., Maddu, S., Miller, J., Mukhopadhyay, P., Nixon, S., Shen, J., Watteaux, R., + Blancard, B., Rozet, F., and Parker, L., and Cranmer, M., and Ho, S. (2024). + The Well: a Large-Scale Collection of Diverse Physics Simulations for Machine Learning. + NeurIPS 2024, https://openreview.net/forum?id=00Sx577BT3. + """ + + def __init__( + self, + root_dir: Path, + well_dataset_name: str, + train_task: Literal["next_step"] = "next_step", + eval_tasks: List[Literal["next_step", "rollout"]] = ["next_step"], + n_steps_input: int = 1, + n_steps_output: int = 1, + download: bool = True, + first_only: bool = True, + ): + base_path = root_dir / f"datasets/{well_dataset_name}/data" + + if download: + for split in ["train", "test", "valid"]: + data_path = base_path / split + if not data_path.exists(): + well_download( + root_dir, + dataset=well_dataset_name, + split=split, + first_only=first_only, + ) + + if train_task == "next_step": + self._train_db = WellDataset( + path=str(base_path / "train"), + n_steps_input=n_steps_input, + n_steps_output=n_steps_output, + full_trajectory_mode=False, + return_grid=False, + use_normalization=False, + ) + else: + raise NotImplementedError( + f"no training set available for training task {train_task}. Choose from ['next_step']" + ) + + self._test_dbs = {} + + if "next_step" in eval_tasks: + self._test_dbs["next_step"] = WellDataset( + path=str(base_path / "test"), + n_steps_input=n_steps_input, + n_steps_output=n_steps_output, + return_grid=False, + use_normalization=False, + ) + if "autoregression" in eval_tasks: + self._test_dbs["autoregression"] = WellDataset( + path=str(base_path / "test"), + full_trajectory_mode=True, + return_grid=False, + use_normalization=False, + ) + + stats_path = base_path / "../stats.yaml" + with open(stats_path, "r") as f: + stats = yaml.safe_load(f) + from pprint import pprint + + pprint(stats) + + dataset_field_names = self._train_db.field_names + pprint(dataset_field_names) + + # store channel-specific means for fields encoding the components of each physical variable + channel_means = [] + channel_stds = [] + + # keep track of constant field statistics separately + const_means = [] + const_stds = [] + + # Loop through fields separately: const, vector and + # tensor fields need to be handled differently. + + # scalar fields have scalar means + for field_name in dataset_field_names[0]: + channel_means.append(stats["mean"][field_name]) + channel_stds.append(stats["std"][field_name]) + + # vector-valued fields have vector means, 1 degree of nesting to unpack + indiv_vector_fields = dataset_field_names[1] + vector_fields = set(["_".join(x.split("_")[:-1]) for x in indiv_vector_fields]) + for field_name in vector_fields: + channel_means.extend(stats["mean"][field_name]) + channel_stds.extend(stats["std"][field_name]) + + # tensor-valued fields have tensor means, 2 degrees of nesting to unpack + indiv_tensor_fields = dataset_field_names[2] + tensor_fields = set(["_".join(x.split("_")[:-1]) for x in indiv_tensor_fields]) + for field_name in tensor_fields: + channel_means.extend([x for xs in stats["mean"][field_name] for x in xs]) + channel_stds.extend([x for xs in stats["std"][field_name] for x in xs]) + + # add a batch dimension and a dummy time dimension : final shape (1, channels, 1) + # all reshaping/channel flattening will be performed after normalizing + channel_means = torch.tensor(channel_means).unsqueeze(0).unsqueeze(-1) + channel_stds = torch.tensor(channel_stds).unsqueeze(0).unsqueeze(-1) + + # unsqueeze means and stds along the spatial dimensions: final shape (1, channels, 1, 1, ... 1) + for _ in range(self.train_db.metadata.n_spatial_dims): + channel_means = channel_means.unsqueeze(-1) + channel_stds = channel_stds.unsqueeze(-1) + + data_normalizer = UnitGaussianNormalizer(mean=channel_means, std=channel_stds) + + # if there are any constant fields, provide a constant normalizer + if const_means: + const_means = torch.tensor(const_means).unsqueeze(0) + const_stds = torch.tensor(const_stds).unsqueeze(0) + + # unsqueeze means and stds along the spatial dimensions + for _ in range(self.train_db.metadata.n_spatial_dims): + const_means = const_means.unsqueeze(-1) + const_stds = const_stds.unsqueeze(-1) + + const_fields_normalizer = UnitGaussianNormalizer(mean=const_means, std=const_stds) + else: + const_fields_normalizer = None + + self._data_processor = TheWellDataProcessor( + data_normalizer=data_normalizer, + const_normalizer=const_fields_normalizer, + n_steps_input=n_steps_input, + n_steps_output=n_steps_output, + time_as_channels=True, + ) + + @property + def train_db(self): + return self._train_db + + @property + def test_dbs(self): + return self._test_dbs + + @property + def data_processor(self): + return self._data_processor + + +class ActiveMatterDataset(TheWellDataset): + def __init__( + self, + root_dir, + train_task="next_step", + eval_tasks=["next_step"], + n_steps_input: int = 1, + n_steps_output: int = 1, + download: bool = True, + first_only=True, + ): + super().__init__( + root_dir, + well_dataset_name="active_matter", + train_task=train_task, + eval_tasks=eval_tasks, + n_steps_input=n_steps_input, + n_steps_output=n_steps_output, + download=download, + first_only=first_only, + ) + + +class MHD64Dataset(TheWellDataset): + def __init__( + self, + root_dir, + train_task="next_step", + eval_tasks=["next_step"], + download=True, + first_only=True, + ): + super().__init__( + root_dir, + well_dataset_name="MHD_64", + train_task=train_task, + eval_tasks=eval_tasks, + download=download, + first_only=first_only, + ) diff --git a/sources/neuraloperator/neuralop/data/datasets/web_utils.py b/sources/neuraloperator/neuralop/data/datasets/web_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8b0b465acf30a18bd146ad5401b545ae8310d678 --- /dev/null +++ b/sources/neuraloperator/neuralop/data/datasets/web_utils.py @@ -0,0 +1,171 @@ +""" +Utils for downloading dataset files from the web. + +Mostly borrowed from torchvision.datasets.utils +""" + +import hashlib +import logging +import os +from pathlib import Path +import requests +import sys +from typing import Any, Optional, Union, List +import tarfile + +logger = logging.Logger(name=__name__) +logger.setLevel(logging.root.level) + +# md5 utils from torchvision.datasets.utils + + +def calculate_md5(fpath: Union[str, Path], chunk_size: int = 1024 * 1024) -> str: + # Setting the `usedforsecurity` flag does not change anything about the functionality, but indicates that we are + # not using the MD5 checksum for cryptography. This enables its usage in restricted environments like FIPS. Without + # it torchvision.datasets is unusable in these environments since we perform a MD5 check everywhere. + if sys.version_info >= (3, 9): + md5 = hashlib.md5(usedforsecurity=False) + else: + md5 = hashlib.md5() + with open(fpath, "rb") as f: + while chunk := f.read(chunk_size): + md5.update(chunk) + return md5.hexdigest() + + +def check_md5(fpath: Union[str, Path], md5: str, **kwargs: Any) -> bool: + return md5 == calculate_md5(fpath, **kwargs) + + +def check_integrity(fpath: Union[str, Path], md5: Optional[str] = None) -> bool: + if isinstance(fpath, str): + fpath = Path(fpath) + if not fpath.is_file(): + return False + if md5 is None: + return True + return check_md5(fpath, md5) + + +def download_from_url( + url: str, + root: Union[str, Path], + filename: Optional[Union[str, Path]] = None, + md5: Optional[str] = None, + size: Optional[int] = None, + chunk_size: Optional[int] = 256 * 64, + extract_tars: bool = True, +) -> None: + """download_from_url downloads a file from a url with + an optional md5 checksum. + + If the file is a tarball, optionally extract. + + Parameters + ---------- + url : str + url where dataset archive file is stored + root : Union[str, Path] + root of dataset folder on local machine + filename : Optional[Union[str, Path]], optional + name into which to download, by default None + md5 : Optional[str], optional + md5 checksum to verify file correctness, by default None + size: Optional[int], optional + size of the file expected in bytes, to check + chunk_size : int, optional + size of chunks to use when streaming files + extract_tars: bool, optional + whether to extract .tgz archives, by default True + """ + if isinstance(root, str): + root = Path(root) + + root = root.expanduser() + if not filename: + # grab file ext from basename + filename = url.split("/")[-1] + fpath = root / filename + + root.mkdir(parents=True, exist_ok=True) + + # check if file is already present locally + if check_integrity(fpath, md5): + logger.info("Using downloaded and verified file: " + str(fpath)) + return + + # download and stream file in chunks + with requests.get(url, stream=True) as r: + r.raise_for_status() + with open(fpath, "wb") as f: + curr_size = 0 + for chunk in r.iter_content(chunk_size=chunk_size): + if chunk: + # write file, flush and fsync to prevent memory bloat + f.write(chunk) + f.flush() + os.fsync(f.fileno()) + # print progress dynamically + curr_size += chunk_size + prog = curr_size / size + print(f"Download in progress: {prog:.2%}", end="\r") + + assert ( + fpath.stat().st_size == size + ), ( + f"Error: mismatch between expected and true size of downloaded file {fpath}. " + "Delete the file and try again." + ) + + # check integrity of downloaded file + if not check_integrity(fpath, md5): + raise RuntimeError("File not found or corrupted.") + else: + logger.info("saved to {fpath} successfully") + # extract tarfiles to their given filenames on root + if extract_tars: + logger.info("Extracting {fpath}...") + archive = tarfile.open(fpath) + archive.extractall(path=root) + name_str = ", ".join(archive.getnames()) + logger.info(f"Extracted {name_str}") + + +def download_from_zenodo_record( + record_id: str, + root: Union[str, Path], + files_to_download: Optional[List[str]] = None, +): + """download_from_zenodo_record downloads files in "files_to_download" + from zenodo record with ID record_id + + Parameters + ---------- + record_id : str + ID of record in Zenodo's database + root : Union[str, Path] + root directory into which to download archive + files_to_download : Optional[List[str]] + list of filenames to download from record. + If None, downloads all. Default None + """ + if files_to_download is not None and len(files_to_download) == 0: + return + zenodo_api_url = "https://zenodo.org/api/records/" + url = f"{zenodo_api_url}{record_id}" + resp = requests.get(url) + assert ( + resp.status_code == 200 + ), f"Error: request failed with status code {resp.status_code}" + response_json = resp.json() + for file_record in response_json["files"]: + fname = file_record["key"] + if files_to_download is None or fname in files_to_download: + download_from_url( + url=file_record["links"]["self"], + md5=file_record["checksum"][4:], # md5 stored as 'md5:xxxxx' + size=file_record["size"], + root=root, + filename=fname, + extract_tars=True, + ) diff --git a/sources/neuraloperator/neuralop/data/datasets/zarr_dataset.py b/sources/neuraloperator/neuralop/data/datasets/zarr_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..ac1b74eade53e9886212735b67b595a337c74205 --- /dev/null +++ b/sources/neuraloperator/neuralop/data/datasets/zarr_dataset.py @@ -0,0 +1,119 @@ +import torch + +try: + import zarr +except ModuleNotFoundError as e: + raise e( + "trying to import zarr_dataset without optional dependency zarr. Please install and try again." + ) +from torch.utils.data import Dataset + + +class ZarrDataset(Dataset): + """PDE h5py dataset""" + + def __init__( + self, + filename, + resolution=128, + transform_x=None, + transform_y=None, + n_samples=None, + ): + resolution_to_step = {128: 8, 256: 4, 512: 2, 1024: 1} + try: + subsample_step = resolution_to_step[resolution] + except KeyError: + raise ValueError( + f"Got resolution={resolution}, " + f"expected one of {resolution_to_step.keys()}" + ) + + self.subsample_step = subsample_step + self.filename = str(filename) + + self._data = None + self.transform_x = transform_x + self.transform_y = transform_y + + if n_samples is not None: + self.n_samples = n_samples + else: + data = zarr.open(self.filename, mode="r") + self.n_samples = data.shape[0] + del data + + def attrs(self, array_name, name): + data = zarr.open( + self.filename, mode="r", synchronizer=zarr.ThreadSynchronizer() + ) + value = data[array_name].attrs[name] + del data + return value + + @property + def data(self): + if self._data is None: + self._data = zarr.open( + self.filename, mode="r", synchronizer=zarr.ThreadSynchronizer() + ) + return self._data + + def __len__(self): + return self.n_samples + + def __getitem__(self, idx): + if torch.is_tensor(idx): + idx = idx.tolist() + + if isinstance(idx, int): + assert ( + idx < self.n_samples + ), f"Trying to access sample {idx} of dataset with {self.n_samples} samples" + else: + for i in idx: + assert i < self.n_samples, ( + f"Trying to access sample {i} " + f"of dataset with {self.n_samples} samples" + ) + + x = self.data["x"][idx, :: self.subsample_step, :: self.subsample_step] + y = self.data["y"][idx, :: self.subsample_step, :: self.subsample_step] + + x = torch.tensor(x, dtype=torch.float32) + y = torch.tensor(y, dtype=torch.float32).unsqueeze(0) + + if self.transform_x: + x = self.transform_x(x) + + if self.transform_y: + y = self.transform_y(y) + + return {"x": x, "y": y} + + def __getitems__(self, idx): + if torch.is_tensor(idx): + idx = idx.tolist() + + x = torch.tensor( + [ + self.data["x"][i, :: self.subsample_step, :: self.subsample_step] + for i in idx + ], + dtype=torch.float32, + ) + y = torch.tensor( + [ + self.data["y"][i, :: self.subsample_step, :: self.subsample_step] + for i in idx + ], + dtype=torch.float32, + ) + + if self.transform_x: + x = self.transform_x(x) + + if self.transform_y: + y = self.transform_y(y) + + return {"x": x, "y": y} diff --git a/sources/neuraloperator/neuralop/data/transforms/__init__.py b/sources/neuraloperator/neuralop/data/transforms/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/sources/neuraloperator/neuralop/data/transforms/__pycache__/__init__.cpython-313.pyc b/sources/neuraloperator/neuralop/data/transforms/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a65c3920ec9aac226b7f508d7028c88284a6ab6b Binary files /dev/null and b/sources/neuraloperator/neuralop/data/transforms/__pycache__/__init__.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/data/transforms/__pycache__/base_transforms.cpython-313.pyc b/sources/neuraloperator/neuralop/data/transforms/__pycache__/base_transforms.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a567d212d7c62ac61b530036e25f3a4800ab0d2 Binary files /dev/null and b/sources/neuraloperator/neuralop/data/transforms/__pycache__/base_transforms.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/data/transforms/__pycache__/data_processors.cpython-313.pyc b/sources/neuraloperator/neuralop/data/transforms/__pycache__/data_processors.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..48de49d035ca3e6eb0c683915f5c8af56dd82023 Binary files /dev/null and b/sources/neuraloperator/neuralop/data/transforms/__pycache__/data_processors.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/data/transforms/__pycache__/normalizers.cpython-313.pyc b/sources/neuraloperator/neuralop/data/transforms/__pycache__/normalizers.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c856b47a548104c9f685d2f1d084a7184b9a76f Binary files /dev/null and b/sources/neuraloperator/neuralop/data/transforms/__pycache__/normalizers.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/data/transforms/base_transforms.py b/sources/neuraloperator/neuralop/data/transforms/base_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..4196c4a439a5fd51609f1a35216bf032fda92b64 --- /dev/null +++ b/sources/neuraloperator/neuralop/data/transforms/base_transforms.py @@ -0,0 +1,151 @@ +from abc import abstractmethod +from typing import List + +import torch + + +class Transform(torch.nn.Module): + """ + Applies transforms or inverse transforms to + model inputs or outputs, respectively + """ + + def __init__(self): + super().__init__() + + @abstractmethod + def transform(self): + pass + + @abstractmethod + def inverse_transform(self): + pass + + @abstractmethod + def cuda(self): + pass + + @abstractmethod + def cpu(self): + pass + + @abstractmethod + def to(self, device): + pass + + +class CompositeTransform(Transform): + """Composite transform composes a list of + Transforms into one Transform object. + + Transformations are not assumed to be commutative + + Parameters + ---------- + transforms : List[Transform] + list of transforms to be applied to data + in order + """ + + def __init__(self, transforms: List[Transform]): + """Initialize the CompositeTransform. + + See class docstring for detailed parameter descriptions. + """ + super.__init__() + self.transforms = transforms + + def transform(self, data_dict): + for tform in self.transforms: + data_dict = tform.transform(self.data_dict) + return data_dict + + def inverse_transform(self, data_dict): + for tform in self.transforms[::-1]: + data_dict = tform.transform(self.data_dict) + return data_dict + + def to(self, device): + # all Transforms are required to implement .to() + self.transforms = [t.to(device) for t in self.transforms if hasattr(t, "to")] + return self + + +class DictTransform(Transform): + """When a model has multiple input and output fields, + apply a different transform to each field, + tries to apply the inverse_transform to each output + + Parameters + ----------- + + transform_dict: dict + dictionary of output encoders + input_mappings: dict[tuple(Slice)] + indices of an output tensor x to use for + each field, such that x[mappings[field]] + returns the correct slice of x. + return_mappings: dict[tuple(Slice)] + same as above. if only certain indices + of encoder output are important, this indexes those. + """ + + def __init__(self, transform_dict, input_mappings, return_mappings=None): + self.transforms = transform_dict + self.output_fields = transform_dict.keys() + self.input_mappings = input_mappings + self.return_mappings = return_mappings + + assert ( + transform_dict.keys() == input_mappings.keys() + ), f"Error: expected keys in transform_dict and input_mappings to match,\ + received {transform_dict.keys()=}\n{input_mappings.keys()=}" + if self.return_mappings: + assert ( + transform_dict.keys() == return_mappings.keys() + ), f"Error: expected keys in transform_dict and return_mappings to match,\ + received {transform_dict.keys()=}\n{return_mappings.keys()=}" + + def transform(self, tensor_dict): + """ + Parameters + ---------- + tensor_dict : Torch.tensor dict + model output, indexed according to self.mappings + """ + out = torch.zeros_like(tensor_dict) + + for field, indices in self.input_mappings.items(): + encoded = self.transforms[field].transform(tensor_dict[indices]) + if self.return_mappings: + encoded = encoded[self.return_mappings[field]] + out[indices] = encoded + + return out + + def inverse_transform(self, x): + """ + Parameters + ---------- + x : Torch.tensor + model output, indexed according to self.mappings + """ + out = torch.zeros_like(x) + for field, indices in self.input_mappings.items(): + decoded = self.transforms[field].inverse_transform(x[indices]) + print(f"{decoded.shape=}") + if self.return_mappings: + decoded = decoded[self.return_mappings[field]] + out[indices] = decoded + + return out + + def cpu(self): + self.encoders = {k: v.cpu() for k, v in self.transforms.items()} + + def cuda(self): + self.encoders = {k: v.cuda() for k, v in self.transforms.items()} + + def to(self, device): + self.encoders = {k: v.to(device) for k, v in self.transforms.items()} + return self diff --git a/sources/neuraloperator/neuralop/data/transforms/data_processors.py b/sources/neuraloperator/neuralop/data/transforms/data_processors.py new file mode 100644 index 0000000000000000000000000000000000000000..4129579f19899b459253e59b648912e547d76420 --- /dev/null +++ b/sources/neuraloperator/neuralop/data/transforms/data_processors.py @@ -0,0 +1,418 @@ +from abc import ABCMeta, abstractmethod + +import torch +from neuralop.training.patching import MultigridPatching2D + + +import torch +from neuralop.training.patching import MultigridPatching2D + + +class DataProcessor(torch.nn.Module, metaclass=ABCMeta): + + def __init__(self): + """ + DataProcessor exposes functionality for pre- + and post-processing data during training or inference. + + To be a valid DataProcessor within the Trainer requires + that the following methods are implemented: + + - to(device): load necessary information to device, in keeping + with PyTorch convention + - preprocess(data): processes data from a new batch before being + put through a model's forward pass + - postprocess(out): processes the outputs of a model's forward pass + before loss and backward pass + - wrap(self, model): + wraps a model in preprocess and postprocess steps to create one forward pass + - forward(self, x): + forward pass providing that a model has been wrapped + """ + super().__init__() + + @abstractmethod + def to(self, device): + pass + + @abstractmethod + def preprocess(self, x): + pass + + @abstractmethod + def postprocess(self, x): + pass + + # default wrap method + def wrap(self, model): + self.model = model + return self + + # default train and eval methods + def train(self, val: bool = True): + super().train(val) + if self.model is not None: + self.model.train() + + def eval(self): + super().eval() + if self.model is not None: + self.model.eval() + + @abstractmethod + def forward(self, x): + pass + + +class DefaultDataProcessor(DataProcessor): + """DefaultDataProcessor is a simple processor + to pre/post process data before training/inferencing a model. + + Parameters + ---------- + in_normalizer : Transform, optional, default is None + normalizer (e.g. StandardScaler) for the input samples + out_normalizer : Transform, optional, default is None + normalizer (e.g. StandardScaler) for the target and predicted samples + """ + + def __init__(self, in_normalizer=None, out_normalizer=None): + """Initialize the DefaultDataProcessor. + + See class docstring for detailed parameter descriptions. + """ + super().__init__() + self.in_normalizer = in_normalizer + self.out_normalizer = out_normalizer + self.device = "cpu" + self.model = None + + def to(self, device): + if self.in_normalizer is not None: + self.in_normalizer = self.in_normalizer.to(device) + if self.out_normalizer is not None: + self.out_normalizer = self.out_normalizer.to(device) + self.device = device + return self + + def preprocess(self, data_dict, batched=True): + """preprocess a batch of data into the format + expected in model's forward call + + By default, training loss is computed on normalized out and y + and eval loss is computed on unnormalized out and y + + Parameters + ---------- + data_dict : dict + input data dictionary with at least + keys 'x' (inputs) and 'y' (ground truth) + batched : bool, optional + whether data contains a batch dim, by default True + + Returns + ------- + dict + preprocessed data_dict + """ + x = data_dict["x"].to(self.device) + y = data_dict["y"].to(self.device) + + if self.in_normalizer is not None: + x = self.in_normalizer.transform(x) + if self.out_normalizer is not None and self.training: + y = self.out_normalizer.transform(y) + + data_dict["x"] = x + data_dict["y"] = y + + return data_dict + + def postprocess(self, output, data_dict): + """postprocess model outputs and data_dict + into format expected by training or val loss + + By default, training loss is computed on normalized out and y + and eval loss is computed on unnormalized out and y + + Parameters + ---------- + output : torch.Tensor + raw model outputs + data_dict : dict + dictionary containing single batch + of data + + Returns + ------- + out, data_dict + postprocessed outputs and data dict + """ + if self.out_normalizer and not self.training: + output = self.out_normalizer.inverse_transform(output) + return output, data_dict + + def forward(self, **data_dict): + """forward call wraps a model + to perform preprocessing, forward, and post- + processing all in one call + + Returns + ------- + output, data_dict + postprocessed data for use in loss + """ + data_dict = self.preprocess(data_dict) + output = self.model(data_dict["x"]) + output = self.postprocess(output) + return output, data_dict + + +class IncrementalDataProcessor(torch.nn.Module): + def __init__( + self, + in_normalizer=None, + out_normalizer=None, + device="cpu", + subsampling_rates=[2, 1], + dataset_resolution=16, + dataset_indices=[2, 3], + epoch_gap=10, + verbose=False, + ): + """An incremental processor to pre/post process data before training/inferencing a model + In particular this processor first regularizes the input resolution based on the sub_list and dataset_indices + in the spatial domain based on a fixed number of epochs. We incrementally increase the resolution like done + in curriculum learning to train the model. This is useful for training models on large datasets with high + resolution data. + + Parameters + ---------- + in_normalizer : Transform, optional, default is None + normalizer (e.g. StandardScaler) for the input samples + out_normalizer : Transform, optional, default is None + normalizer (e.g. StandardScaler) for the target and predicted samples + device : str, optional, default is 'cpu' + device 'cuda' or 'cpu' where computations are performed + subsampling_rates : list, optional, default is [2, 1] + list of subsampling rates to use + dataset_resolution : int, optional, default is 16 + resolution of the input data + dataset_indices : list, optional, default is [2, 3] + list of indices of the dataset to slice to regularize the input resolution - Spatial Dimensions + epoch_gap : int, optional, default is 10 + number of epochs to wait before increasing the resolution + verbose : bool, optional, default is False + if True, print the current resolution + """ + super().__init__() + self.in_normalizer = in_normalizer + self.out_normalizer = out_normalizer + self.device = device + self.sub_list = subsampling_rates + self.dataset_resolution = dataset_resolution + self.dataset_indices = dataset_indices + self.epoch_gap = epoch_gap + self.verbose = verbose + self.epoch = 0 + + self.current_index = 0 + self.current_logged_epoch = 0 + self.current_sub = self.index_to_sub_from_table(self.current_index) + self.current_res = int(self.dataset_resolution / self.current_sub) + + print(f"Original Incre Res: change index to {self.current_index}") + print(f"Original Incre Res: change sub to {self.current_sub}") + print(f"Original Incre Res: change res to {self.current_res}") + + def to(self, device): + if self.in_normalizer is not None: + self.in_normalizer = self.in_normalizer.to(device) + if self.out_normalizer is not None: + self.out_normalizer = self.out_normalizer.to(device) + self.device = device + return self + + def epoch_wise_res_increase(self, epoch): + # Update the current_sub and current_res values based on the epoch + if ( + epoch % self.epoch_gap == 0 + and epoch != 0 + and (self.current_logged_epoch != epoch) + ): + self.current_index += 1 + self.current_sub = self.index_to_sub_from_table(self.current_index) + self.current_res = int(self.dataset_resolution / self.current_sub) + self.current_logged_epoch = epoch + + if self.verbose: + print(f"Incre Res Update: change index to {self.current_index}") + print(f"Incre Res Update: change sub to {self.current_sub}") + print(f"Incre Res Update: change res to {self.current_res}") + + def index_to_sub_from_table(self, index): + # Get the sub value from the sub_list based on the index + if index >= len(self.sub_list): + return self.sub_list[-1] + else: + return self.sub_list[index] + + def regularize_input_res(self, x, y): + # Regularize the input data based on the current_sub and dataset_name + for idx in self.dataset_indices: + indexes = torch.arange(0, x.size(idx), self.current_sub, device=self.device) + x = x.index_select(dim=idx, index=indexes) + y = y.index_select(dim=idx, index=indexes) + return x, y + + def step(self, loss=None, epoch=None, x=None, y=None): + if x is not None and y is not None: + self.epoch_wise_res_increase(epoch) + return self.regularize_input_res(x, y) + + def preprocess(self, data_dict, batched=True): + x = data_dict["x"].to(self.device) + y = data_dict["y"].to(self.device) + + if self.in_normalizer is not None: + x = self.in_normalizer.transform(x) + if self.out_normalizer is not None and self.train: + y = self.out_normalizer.transform(y) + + if self.training: + x, y = self.step(epoch=self.epoch, x=x, y=y) + + data_dict["x"] = x + data_dict["y"] = y + + return data_dict + + def postprocess(self, output, data_dict): + y = data_dict["y"] + if self.out_normalizer and not self.train: + output = self.out_normalizer.inverse_transform(output) + y = self.out_normalizer.inverse_transform(y) + data_dict["y"] = y + return output, data_dict + + def forward(self, **data_dict): + data_dict = self.preprocess(data_dict) + output = self.model(data_dict["x"]) + output = self.postprocess(output) + return output, data_dict + + +class MGPatchingDataProcessor(DataProcessor): + def __init__( + self, + model: torch.nn.Module, + levels: int, + padding_fraction: float, + stitching: float, + device: str = "cpu", + use_distributed: bool = False, + in_normalizer=None, + out_normalizer=None, + ): + """MGPatchingDataProcessor + Applies multigrid patching to inputs out-of-place + with an optional output encoder/other data transform + + Parameters + ---------- + model: nn.Module + model to wrap in MultigridPatching2D + levels : int + number of multi-grid patching levels to use + padding_fraction : float + fraction by which to pad inputs in multigrid-patching + stitching : bool + whether to stitch back the output from the multi-grid patches + in_normalizer : neuralop.datasets.transforms.Transform, optional + OutputEncoder to decode model inputs, by default None + in_normalizer : neuralop.datasets.transforms.Transform, optional + OutputEncoder to decode model outputs, by default None + device : str, optional + device 'cuda' or 'cpu' where computations are performed + """ + super().__init__() + self.levels = levels + self.padding_fraction = padding_fraction + self.stitching = stitching + self.patcher = MultigridPatching2D( + model=model, + levels=self.levels, + padding_fraction=self.padding_fraction, + stitching=self.stitching, + use_distributed=use_distributed, + ) + self.device = device + + # set normalizers to none by default + self.in_normalizer, self.out_normalizer = None, None + if in_normalizer: + self.in_normalizer = in_normalizer.to(self.device) + if out_normalizer: + self.out_normalizer = out_normalizer.to(self.device) + self.model = model + + def to(self, device): + self.device = device + if self.in_normalizer: + self.in_normalizer = self.in_normalizer.to(self.device) + if self.out_normalizer: + self.out_normalizer = self.out_normalizer.to(self.device) + return self + + def preprocess(self, data_dict, batched=True): + """ + Preprocess data assuming that if encoder exists, it has + encoded all data during data loading + + Parameters + ---------- + data_dict: dict + dictionary keyed with 'x', 'y' etc + represents one batch of data input to a model + batched: bool + whether the first dimension of 'x', 'y' represents batching + """ + data_dict = { + k: v.to(self.device) for k, v in data_dict.items() if torch.is_tensor(v) + } + x, y = data_dict["x"], data_dict["y"] + if self.in_normalizer: + x = self.in_normalizer.transform(x) + y = self.out_normalizer.transform(y) + data_dict["x"], data_dict["y"] = self.patcher.patch(x, y) + + return data_dict + + def postprocess(self, out, data_dict): + """ + Postprocess model outputs. + + Parameters + ---------- + data_dict: dict + dictionary keyed with 'x', 'y' etc + represents one batch of data input to a model + out: torch.Tensor + model output predictions + """ + y = data_dict["y"] + out, y = self.patcher.unpatch(out, y, evaluation=not self.training) + + if self.out_normalizer: + y = self.out_normalizer.inverse_transform(y) + out = self.out_normalizer.inverse_transform(out) + + data_dict["y"] = y + + return out, data_dict + + def forward(self, **data_dict): + data_dict = self.preprocess(data_dict) + output = self.model(**data_dict) + output, data_dict = self.postprocess(output, data_dict) + return output, data_dict diff --git a/sources/neuraloperator/neuralop/data/transforms/normalizers.py b/sources/neuraloperator/neuralop/data/transforms/normalizers.py new file mode 100644 index 0000000000000000000000000000000000000000..acf4bdd818b8af3123ed271531b3cddb428cfed2 --- /dev/null +++ b/sources/neuraloperator/neuralop/data/transforms/normalizers.py @@ -0,0 +1,264 @@ +from typing import Dict + +from ...utils import count_tensor_params +from .base_transforms import Transform, DictTransform +import torch + + +class Normalizer(Transform): + def __init__(self, mean, std, eps=1e-6): + self.mean = mean + self.std = std + self.eps = eps + + def transform(self, data): + return (data - self.mean) / (self.std + self.eps) + + def inverse_transform(self, data): + return (data * (self.std + self.eps)) + self.mean + + def to(self, device): + self.mean = self.mean.to(device) + self.std = self.std.to(device) + + def cuda(self): + self.mean = self.mean.cuda() + self.std = self.std.cuda() + + def cpu(self): + self.mean = self.mean.cpu() + self.std = self.std.cpu() + + +class UnitGaussianNormalizer(Transform): + """ + UnitGaussianNormalizer normalizes data to be zero mean and unit std. + + Parameters + ---------- + mean : torch.tensor or None + has to include batch-size as a dim of 1 + e.g. for tensors of shape ``(batch_size, channels, height, width)``, + the mean over height and width should have shape ``(1, channels, 1, 1)`` + std : torch.tensor or None + eps : float, default is 0 + for safe division by the std + dim : int list, default is None + if not None, dimensions of the data to reduce over to compute the mean and std. + + .. important:: + + Has to include the batch-size (typically 0). + For instance, to normalize data of shape ``(batch_size, channels, height, width)`` + along batch-size, height and width, pass ``dim=[0, 2, 3]`` + + mask : torch.Tensor or None, default is None + If not None, a tensor with the same size as a sample, + with value 0 where the data should be ignored and 1 everywhere else + + Notes + ----- + The resulting mean will have the same size as the input MINUS the specified dims. + If you do not specify any dims, the mean and std will both be scalars. + """ + + def __init__(self, mean=None, std=None, eps=1e-7, dim=None, mask=None): + """Initialize the UnitGaussianNormalizer. + + See class docstring for detailed parameter descriptions. + """ + super().__init__() + + self.register_buffer("mean", mean) + self.register_buffer("std", std) + self.register_buffer("mask", mask) + + self.eps = eps + if mean is not None: + self.ndim = mean.ndim + if isinstance(dim, int): + dim = [dim] + self.dim = dim + self.n_elements = 0 + + def fit(self, data_batch): + self.update_mean_std(data_batch) + + def partial_fit(self, data_batch, batch_size=1): + if 0 in list(data_batch.shape): + return + count = 0 + n_samples = len(data_batch) + while count < n_samples: + samples = data_batch[count : count + batch_size] + # print(samples.shape) + # if batch_size == 1: + # samples = samples.unsqueeze(0) + if self.n_elements: + self.incremental_update_mean_std(samples) + else: + self.update_mean_std(samples) + count += batch_size + + def update_mean_std(self, data_batch): + self.ndim = data_batch.ndim # Note this includes batch-size + if self.mask is None: + self.n_elements = count_tensor_params(data_batch, self.dim) + self.mean = torch.mean(data_batch, dim=self.dim, keepdim=True) + self.squared_mean = torch.mean(data_batch**2, dim=self.dim, keepdim=True) + self.std = torch.std(data_batch, dim=self.dim, keepdim=True) + else: + batch_size = data_batch.shape[0] + dim = [i - 1 for i in self.dim if i] + shape = [s for i, s in enumerate(self.mask.shape) if i not in dim] + self.n_elements = torch.count_nonzero(self.mask, dim=dim) * batch_size + self.mean = torch.zeros(shape) + self.std = torch.zeros(shape) + self.squared_mean = torch.zeros(shape) + data_batch[:, self.mask == 1] = 0 + self.mean[self.mask == 1] = ( + torch.sum(data_batch, dim=dim, keepdim=True) / self.n_elements + ) + self.squared_mean = ( + torch.sum(data_batch**2, dim=dim, keepdim=True) / self.n_elements + ) + self.std = torch.std(data_batch, dim=self.dim, keepdim=True) + + def incremental_update_mean_std(self, data_batch): + if self.mask is None: + n_elements = count_tensor_params(data_batch, self.dim) + dim = self.dim + else: + dim = [i - 1 for i in self.dim if i] + n_elements = torch.count_nonzero(self.mask, dim=dim) * data_batch.shape[0] + data_batch[:, self.mask == 1] = 0 + + self.mean = (1.0 / (self.n_elements + n_elements)) * ( + self.n_elements * self.mean + torch.sum(data_batch, dim=dim, keepdim=True) + ) + self.squared_mean = (1.0 / (self.n_elements + n_elements)) * ( + self.n_elements * self.squared_mean + + torch.sum(data_batch**2, dim=dim, keepdim=True) + ) + self.n_elements += n_elements + + # 1/(n_i + n_j) * (n_i * sum(x_i^2)/n_i + sum(x_j^2) - (n_i*sum(x_i)/n_i + sum(x_j))^2) + # = 1/(n_i + n_j) * (sum(x_i^2) + sum(x_j^2) - sum(x_i)^2 - 2sum(x_i)sum(x_j) - sum(x_j)^2)) + # multiply by (n_i + n_j) / (n_i + n_j + 1) for unbiased estimator + self.std = ( + torch.sqrt(self.squared_mean - self.mean**2) + * self.n_elements + / (self.n_elements - 1) + ) + + def transform(self, x): + return (x - self.mean) / (self.std + self.eps) + + def inverse_transform(self, x): + return x * (self.std + self.eps) + self.mean + + def forward(self, x): + return self.transform(x) + + def cuda(self): + self.mean = self.mean.cuda() + self.std = self.std.cuda() + return self + + def cpu(self): + self.mean = self.mean.cpu() + self.std = self.std.cpu() + return self + + def to(self, device): + self.mean = self.mean.to(device) + self.std = self.std.to(device) + return self + + @classmethod + def from_dataset(cls, dataset, dim=None, keys=None, mask=None): + """Return a dictionary of normalizer instances, fitted on the given dataset + + Parameters + ---------- + dataset : pytorch dataset + each element must be a dict {key: sample} + e.g. {'x': input_samples, 'y': target_labels} + dim : int list, default is None + * If None, reduce over all dims (scalar mean and std) + * Otherwise, must include batch-dimensions and all over dims to reduce over + keys : str list or None + if not None, a normalizer is instanciated only for the given keys + """ + for i, data_dict in enumerate(dataset): + if not i: + if not keys: + keys = data_dict.keys() + instances = {key: cls(dim=dim, mask=mask) for key in keys} + for i, data_dict in enumerate(dataset): + for key, sample in data_dict.items(): + if key in keys: + instances[key].partial_fit(sample.unsqueeze(0)) + return instances + + +class DictUnitGaussianNormalizer(DictTransform): + """DictUnitGaussianNormalizer composes + DictTransform and UnitGaussianNormalizer to normalize different + fields of a model output tensor to Gaussian distributions w/ + mean 0 and unit variance. + + Parameters + ---------- + normalizer_dict : Dict[str, UnitGaussianNormalizer] + dictionary of normalizers, keyed to fields + input_mappings : Dict[slice] + slices of input tensor to grab per field, must share keys with above + return_mappings : Dict[slice] + _description_ + """ + + def __init__( + self, + normalizer_dict: Dict[str, UnitGaussianNormalizer], + input_mappings: Dict[str, slice], + return_mappings: Dict[str, slice], + ): + assert set(normalizer_dict.keys()) == set( + input_mappings.keys() + ), "Error: normalizers and model input fields must be keyed identically" + assert set(normalizer_dict.keys()) == set( + return_mappings.keys() + ), "Error: normalizers and model output fields must be keyed identically" + + super().__init__( + transform_dict=normalizer_dict, + input_mappings=input_mappings, + return_mappings=return_mappings, + ) + + @classmethod + def from_dataset(cls, dataset, dim=None, keys=None, mask=None): + """Return a dictionary of normalizer instances, fitted on the given dataset + + Parameters + ---------- + dataset : pytorch dataset + each element must be a dict {key: sample} + e.g. {'x': input_samples, 'y': target_labels} + dim : int list, default is None + * If None, reduce over all dims (scalar mean and std) + * Otherwise, must include batch-dimensions and all over dims to reduce over + keys : str list or None + if not None, a normalizer is instanciated only for the given keys + """ + for i, data_dict in enumerate(dataset): + if not i: + if not keys: + keys = data_dict.keys() + instances = {key: cls(dim=dim, mask=mask) for key in keys} + for i, data_dict in enumerate(dataset): + for key, sample in data_dict.items(): + if key in keys: + instances[key].partial_fit(sample.unsqueeze(0)) + return instances diff --git a/sources/neuraloperator/neuralop/data/transforms/patching_transforms.py b/sources/neuraloperator/neuralop/data/transforms/patching_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..8d41362a204f113065083edbb3778ad8b47867f1 --- /dev/null +++ b/sources/neuraloperator/neuralop/data/transforms/patching_transforms.py @@ -0,0 +1,128 @@ +from typing import List + +import torch +from torch.utils.data import Dataset + +from .base_transforms import Transform +from ...training.patching import MultigridPatching2D + + +class MGPatchingTransform(Transform): + """Wraps MultigridPatching2D to expose canonical + transform .transform() and .inverse_transform() API + + Parameters + ---------- + model: nn.Module + model to wrap in MultigridPatching2D + levels : int + mg_patching level parameter for MultigridPatching2D + padding_fraction : float + mg_padding_fraction parameter for MultigridPatching2D + stitching : float + mg_patching_stitching parameter for MultigridPatching2D + """ + + def __init__( + self, + model: torch.nn.Module, + levels: int, + padding_fraction: float, + stitching: float, + ): + """Initialize the MGPatchingTransform. + + See class docstring for detailed parameter descriptions. + """ + super.__init__() + + self.levels = levels + self.padding_fraction = padding_fraction + self.stitching = stitching + self.patcher = MultigridPatching2D( + model=model, + levels=self.levels, + padding_fraction=self.padding_fraction, + stitching=self.stitching, + ) + + def transform(self, data_dict): + x = data_dict["x"] + y = data_dict["y"] + + x, y = self.patcher.patch(x, y) + + data_dict["x"] = x + data_dict["y"] = y + return data_dict + + def inverse_transform(self, data_dict): + x = data_dict["x"] + y = data_dict["y"] + + x, y = self.patcher.unpatch(x, y) + + data_dict["x"] = x + data_dict["y"] = y + return data_dict + + def to(self, _): + # nothing to pass to device + return self + + +class RandomMGPatch: + def __init__(self, levels=2): + self.levels = levels + self.step = 2**levels + + def __call__(self, data): + def _get_patches(shifted_image, step, height, width): + """Take as input an image and return multi-grid patches centered around the middle of the image""" + if step == 1: + return (shifted_image,) + else: + # Notice that we need to stat cropping at start_h = (height - patch_size)//2 + # (//2 as we pad both sides) + # Here, the extracted patch-size is half the size so patch-size = height//2 + # Hence the values height//4 and width // 4 + start_h = height // 4 + start_w = width // 4 + + patches = _get_patches(shifted_image[:, start_h:-start_h, start_w:-start_w], step//2, height//2, width//2) + + return (shifted_image[:, ::step, ::step], *patches) + + x, y = data + channels, height, width = x.shape + center_h = height // 2 + center_w = width // 2 + + # Sample a random patching position + pos_h = torch.randint(low=0, high=height, size=(1,))[0] + pos_w = torch.randint(low=0, high=width, size=(1,))[0] + + shift_h = center_h - pos_h + shift_w = center_w - pos_w + + shifted_x = torch.roll(x, (shift_h, shift_w), dims=(0, 1)) + patches_x = _get_patches(shifted_x, self.step, height, width) + shifted_y = torch.roll(y, (shift_h, shift_w), dims=(0, 1)) + patches_y = _get_patches(shifted_y, self.step, height, width) + + return torch.cat(patches_x, dim=0), patches_y[-1] + + +class MGPTensorDataset(Dataset): + def __init__(self, x, y, levels=2): + assert x.size(0) == y.size(0), "Size mismatch between tensors" + self.x = x + self.y = y + self.levels = 2 + self.transform = RandomMGPatch(levels=levels) + + def __getitem__(self, index): + return self.transform((self.x[index], self.y[index])) + + def __len__(self): + return self.x.size(0) diff --git a/sources/neuraloperator/neuralop/data/transforms/tests/__init__.py b/sources/neuraloperator/neuralop/data/transforms/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/sources/neuraloperator/neuralop/data/transforms/tests/test_data_processor.py b/sources/neuraloperator/neuralop/data/transforms/tests/test_data_processor.py new file mode 100644 index 0000000000000000000000000000000000000000..c753088fa1b7c086829d08a19cb96c75f2ffabae --- /dev/null +++ b/sources/neuraloperator/neuralop/data/transforms/tests/test_data_processor.py @@ -0,0 +1,146 @@ +import pytest + +import torch +from torch.testing import assert_close + +from ..data_processors import ( + DefaultDataProcessor, + IncrementalDataProcessor, + MGPatchingDataProcessor, +) +from ..normalizers import UnitGaussianNormalizer + +from neuralop.tests.test_utils import DummyModel + + +def test_DefaultDataProcessor_pipeline(): + if torch.backends.cuda.is_built(): + device = "cuda" + else: + device = "cpu" + + x = torch.randn((1, 2, 64, 64)) + y = torch.randn((1, 2, 64, 64)) + + normalizer = UnitGaussianNormalizer( + mean=torch.zeros((1, 2, 1, 1)), std=torch.ones((1, 2, 1, 1)), eps=1e-5 + ) + + pipeline = DefaultDataProcessor(in_normalizer=normalizer, out_normalizer=normalizer) + + data = {"x": x, "y": y} # data on cpu at this point + + xform_data = pipeline.preprocess(data) + + # model outputs will be on device by default + out = torch.randn((1, 2, 64, 64)).to(device) + + _, inv_xform_data = pipeline.postprocess(out, xform_data) + + assert_close(inv_xform_data["y"].cpu(), data["y"]) + + +def test_DefaultDataProcessor_train_eval(): + if torch.backends.cuda.is_built(): + device = "cuda" + else: + device = "cpu" + + model = DummyModel(features=10) + + normalizer = UnitGaussianNormalizer( + mean=torch.zeros((1, 2, 1, 1)), std=torch.ones((1, 2, 1, 1)), eps=1e-5 + ) + + pipeline = DefaultDataProcessor(in_normalizer=normalizer, out_normalizer=normalizer) + wrapped_model = pipeline.wrap(model).to(device) + + assert wrapped_model.device == device + + wrapped_model.train() + assert wrapped_model.training + assert wrapped_model.model.training + + wrapped_model.eval() + assert not wrapped_model.training + assert not wrapped_model.model.training + + +# ensure that the data processor incrementally increases the resolution +def test_incremental_resolution(): + if torch.backends.cuda.is_built(): + device = "cuda" + else: + device = "cpu" + + x = torch.randn((1, 2, 16, 16)).to(device) + y = torch.randn((1, 2, 16, 16)).to(device) + indice_list = [2, 3] + + data_transform = IncrementalDataProcessor( + in_normalizer=None, + out_normalizer=None, + device=device, + subsampling_rates=[2], + dataset_resolution=16, + dataset_indices=indice_list, + epoch_gap=10, + verbose=True, + ) + + # model outputs will be on device by default + x_new, y_new = data_transform.regularize_input_res(x, y) + + # This is cause x_new.shape = (1, 2, 8, 8) + # This is cause y_new.shape = (1, 2, 8, 8) + for i in indice_list: + assert x_new.shape[i] < x.shape[i] + assert y_new.shape[i] < y.shape[i] + + +@pytest.mark.parametrize("levels", [1, 2]) +@pytest.mark.parametrize("padding_fraction", [0, 0.1]) +def test_full_mgp2d(levels, padding_fraction): + batch_size = 16 + channels = 1 + side_len = 32 + + model = DummyModel(16) + processor = MGPatchingDataProcessor( + model=model, + levels=levels, + padding_fraction=padding_fraction, + stitching=False, # cpu-only, single process + use_distributed=False, + ) + processor.train() + + x = torch.randn(batch_size, channels, side_len, side_len) + y = torch.randn(batch_size, channels, side_len, side_len) + sample = {"x": x, "y": y} + patched_sample = processor.preprocess(sample) + + n_patches = 2**levels + padding = int(round(side_len * padding_fraction)) + patched_padded_side_len = int((side_len // n_patches) + (2 * padding)) + unpatch_side_len = int(side_len // n_patches) + + assert patched_sample["x"].shape == ( + (n_patches**2) * batch_size, + channels + levels, + patched_padded_side_len, + patched_padded_side_len, + ) + + # mimic output after scattering x to model parallel region + patched_out_shape = (batch_size, 1, *patched_sample["x"].shape[2:]) + patched_out = torch.randn(patched_out_shape) + + unpatched_out, unpatched_y = processor.postprocess(patched_out, patched_sample) + + assert unpatched_out.shape == ( + batch_size, + channels, + unpatch_side_len, + unpatch_side_len, + ) diff --git a/sources/neuraloperator/neuralop/data/transforms/tests/test_unit_gaussian_normalizer.py b/sources/neuraloperator/neuralop/data/transforms/tests/test_unit_gaussian_normalizer.py new file mode 100644 index 0000000000000000000000000000000000000000..623b154818e16d4d19ea11ea2e1dd9123eaa8888 --- /dev/null +++ b/sources/neuraloperator/neuralop/data/transforms/tests/test_unit_gaussian_normalizer.py @@ -0,0 +1,63 @@ +from ..normalizers import UnitGaussianNormalizer +import torch +from torch.testing import assert_close +from flaky import flaky + + +@flaky(max_runs=4, min_passes=3) +def test_UnitGaussianNormalizer_created_from_stats(eps=1e-6): + x = torch.rand(16, 3, 40, 50, 60) * 2.5 + mean = torch.mean(x, dim=[0, 2, 3, 4], keepdim=True) + std = torch.std(x, dim=[0, 2, 3, 4], keepdim=True) + + # Init normalizer with ground-truth mean and std + normalizer = UnitGaussianNormalizer(mean=mean, std=std, eps=eps) + x_normalized = normalizer.transform(x) + x_unnormalized = normalizer.inverse_transform(x_normalized) + + assert_close(x_unnormalized, x) + assert torch.mean(x_normalized) <= eps + assert (torch.std(x_normalized) - 1) <= eps + + +@flaky(max_runs=4, min_passes=3) +def test_UnitGaussianNormalizer_from_data(eps=1e-6): + x = torch.rand(16, 3, 40, 50, 60) * 2.5 + mean = torch.mean(x, dim=[0, 2, 3, 4], keepdim=True) + std = torch.std(x, dim=[0, 2, 3, 4], keepdim=True) + # Init by fitting whole data at once + normalizer = UnitGaussianNormalizer(dim=[0, 2, 3, 4], eps=eps) + normalizer.fit(x) + + assert_close(normalizer.mean, mean) + assert_close(normalizer.std, std, rtol=eps, atol=eps) + + x_normalized = normalizer.transform(x) + x_unnormalized = normalizer.inverse_transform(x_normalized) + + assert_close(x_unnormalized, x) + assert torch.mean(x_normalized) <= eps + assert (torch.std(x_normalized) - 1) <= eps + + assert_close(normalizer.mean, mean) + assert_close(normalizer.std, std, rtol=eps, atol=eps) + + +@flaky(max_runs=4, min_passes=3) +def test_UnitGaussianNormalizer_incremental_update(eps=1e-6): + x = torch.rand(16, 3, 40, 50, 60) * 2.5 + mean = torch.mean(x, dim=[0, 2, 3, 4], keepdim=True) + std = torch.std(x, dim=[0, 2, 3, 4], keepdim=True) + # Incrementally compute mean and var + normalizer = UnitGaussianNormalizer(dim=[0, 2, 3, 4], eps=eps) + normalizer.partial_fit(x, batch_size=2) + + x_normalized = normalizer.transform(x) + x_unnormalized = normalizer.inverse_transform(x_normalized) + + assert_close(x_unnormalized, x) + assert torch.mean(x_normalized) <= eps + assert (torch.std(x_normalized) - 1) <= eps + + assert_close(normalizer.mean, mean) + assert_close(normalizer.std, std, rtol=eps, atol=eps) diff --git a/sources/neuraloperator/neuralop/data/transforms/the_well_data_processors.py b/sources/neuraloperator/neuralop/data/transforms/the_well_data_processors.py new file mode 100644 index 0000000000000000000000000000000000000000..b01f0d6603529ae0218dc756113fe6dc23be7918 --- /dev/null +++ b/sources/neuraloperator/neuralop/data/transforms/the_well_data_processors.py @@ -0,0 +1,187 @@ +from ..transforms.data_processors import DefaultDataProcessor + +try: + from einops import rearrange +except ModuleNotFoundError: + print( + "Trying to import data processors for TheWell without required dependency\ + ``einops``. Run ``pip install einops`` and try again." + ) + raise ModuleNotFoundError + +import torch + + +class TheWellDataProcessor(DefaultDataProcessor): + """ + TheWellDataProcessor converts data from ``neuralop.data.datasets.TheWellDataset`` + into the form expected by our models. + + Parameters + ---------- + data_normalizer : nn.Module + data transform to normalize/unnormalize time-varying spatial variables in x and y + channel-wise. The problems in The Well are trajectories in time, + so x and y are points from the same trajectory and thus share statistics. + const_normalizer : nn.Module, optional + data transform to normalize/unnormalize constant input variables in x + channel-wise. If they exist, these constant fields are concatenated onto x + after normalizing and flattening. + n_steps_input : int + number of timesteps to be used as input to the model + n_steps_output : int + number of timesteps to be used as output to the model + time_as_channels : bool, optional + _description_, by default True + """ + + def __init__( + self, + data_normalizer, + const_normalizer=None, + n_steps_input: int = 1, + n_steps_output: int = 1, + time_as_channels: bool = True, + ): + super().__init__() + self.data_normalizer = data_normalizer + self.const_normalizer = const_normalizer + self.n_steps_input = n_steps_input + self.n_steps_output = n_steps_output + self.time_as_channels = time_as_channels + + if self.time_as_channels: + assert ( + self.n_steps_output == 1 + ), "if attempting to predict multiple timesteps of output, use a spatiotemporal model instead of flattening." + + def to(self, device): + self.device = device + if self.data_normalizer is not None: + self.data_normalizer = self.data_normalizer.to(self.device) + if self.const_normalizer is not None: + self.const_normalizer = self.const_normalizer.to(self.device) + return self + + def preprocess(self, data_dict, step=None): + """ + Code adapted from the_well.data.data_formatter.DefaultChannelsFirstFormatter + """ + ## processing x + # in next-step mode, or if x is not yet set + if step is None: + # by default, in The Well, x is stored in shape (b, time, d1, d2, ... dN, channels) + x = data_dict["input_fields"].to(self.device) + x = x.permute(0, -1, *list(range(1, x.ndim - 1))) + data_dict["input_fields"] = x # store permuted version for later + elif step == 0: + x = data_dict["output_fields"][:, : self.n_steps_input, ...].to(self.device) + + # always move channels to the second dimension + x = x.permute(0, -1, *list(range(1, x.ndim - 1))) + data_dict["input_fields"] = x # store permuted version for later + in_channels = x.shape[1] + else: + # otherwise input fields are set in self.postprocess (see below) + x = data_dict["input_fields"].to(self.device) + if self.data_normalizer is not None: + x = self.data_normalizer.transform(x) + + # Normalization is performed channel-wise, so we flatten time along the channel dim once data has been normalized + if self.time_as_channels: + x = rearrange(x, "b c t ... -> b (t c) ...") + + # Retrieve, normalize and concat constant variable channels if they exist + + if "constant_fields" in data_dict: + # TODO repeat along time + flat_constants = rearrange(data_dict["constant_fields"], "b ... c -> b c ...") + constant_channels = flat_constants.shape[1] + + if self.const_normalizer is not None: + flat_constants = self.const_normalizer.transform(flat_constants) + + # if x stays spatiotemporal, repeat constants along time dim + if not self.time_as_channels: + flat_constants = flat_constants.unsqueeze(2).repeat(1, 1, x.shape[2], *[1]*(x.ndim - 3)) + + # concatenate along channels after normalizing + x = torch.cat( + [ + x, + flat_constants.to(self.device), + ], + dim=1, + ) + + ### Processing y + # by default, in The Well, y is stored in shape (b, time, d1, d2, ... dN, channels) + y = data_dict["output_fields"].to(self.device) + # always move channels to the second dimension + # shape (b, c, t, ...) + y = y.permute(0, -1, *list(range(1, y.ndim - 1))) + + # if in autoregressive (AR) mode, skip default preprocessing, infer number of steps and roll y forward + if step is not None: + # the first n_steps_input steps are reserved for x. + step += self.n_steps_input + + # if we're past the end of y's timesteps, return an empty sample. + if step >= y.shape[2]: + return None + else: + # here y is shape (b, c, t, ...) + # roll y forward one timestep + y = y[:, :, step : step + self.n_steps_output, ...] + + # normalize y after selecting only the relevant timesteps + if self.data_normalizer is not None: + y = self.data_normalizer.transform(y) + + # In both modes, permute y's dimensions into the same order as x's + if self.time_as_channels: + y = rearrange(y, "b c t ... -> b (t c) ...") + + data_dict["x"] = x + data_dict["y"] = y + + return data_dict + + def postprocess(self, output, data_dict, step=None): + """ + Code adapted from the_well.data.data_formatter.DefaultChannelsFirstFormatter + """ + + y = data_dict["y"] + + # Unnormalize: outputs/ground truth/(sometimes inputs) + if self.data_normalizer is not None: + # in next-step mode, out and y are unnormalized unly during eval. + if (step is None and not self.training) or step is not None: + # before unnormalizing, reshape out + y to add a time dim + # we can unsqueeze because we assume n_steps_output == 1. + if self.time_as_channels: + y = y.unsqueeze(2) + output = output.unsqueeze(2) + + y = self.data_normalizer.inverse_transform(y) + output = self.data_normalizer.inverse_transform(output) + + # after normalizing, squeeze time dim out again (note n_steps_output forced to 1) + if self.time_as_channels: + y = y.squeeze(2) + output = output.squeeze(2) + + # if in AR mode, append output to x + if step is not None: + # only grab variable fields + input_vars = data_dict["input_fields"].to(self.device) + # on step=0, the channels are permuted to dim 1 + # concatenate along time dim (add to output) + input_vars = torch.cat((input_vars, output.unsqueeze(2)), dim=2) + # roll forward by one step + input_vars = input_vars[:, :, -self.n_steps_input :, ...] + data_dict["input_fields"] = input_vars + + data_dict["y"] = y + return output, data_dict diff --git a/sources/neuraloperator/neuralop/layers/__init__.py b/sources/neuraloperator/neuralop/layers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/sources/neuraloperator/neuralop/layers/__pycache__/__init__.cpython-313.pyc b/sources/neuraloperator/neuralop/layers/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6def47b5b21bc4e5fea50b1d9dca1fb5943ab7d4 Binary files /dev/null and b/sources/neuraloperator/neuralop/layers/__pycache__/__init__.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/layers/__pycache__/base_spectral_conv.cpython-313.pyc b/sources/neuraloperator/neuralop/layers/__pycache__/base_spectral_conv.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d0e910636625f28a82f8244bad95a97d494fadf Binary files /dev/null and b/sources/neuraloperator/neuralop/layers/__pycache__/base_spectral_conv.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/layers/__pycache__/channel_mlp.cpython-313.pyc b/sources/neuraloperator/neuralop/layers/__pycache__/channel_mlp.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e39d79f4ff9d5a1cea98502d03c0a45bf106428d Binary files /dev/null and b/sources/neuraloperator/neuralop/layers/__pycache__/channel_mlp.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/layers/__pycache__/coda_layer.cpython-313.pyc b/sources/neuraloperator/neuralop/layers/__pycache__/coda_layer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f675e03319e437cdeaec1c41af8b6ddee113c69 Binary files /dev/null and b/sources/neuraloperator/neuralop/layers/__pycache__/coda_layer.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/layers/__pycache__/complex.cpython-313.pyc b/sources/neuraloperator/neuralop/layers/__pycache__/complex.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7cdd79dfe77d6be5f68bcad6f43d1ab3495d751 Binary files /dev/null and b/sources/neuraloperator/neuralop/layers/__pycache__/complex.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/layers/__pycache__/einsum_utils.cpython-313.pyc b/sources/neuraloperator/neuralop/layers/__pycache__/einsum_utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23e262c765ad9c38898514c876aed7ce7ad6ef4a Binary files /dev/null and b/sources/neuraloperator/neuralop/layers/__pycache__/einsum_utils.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/layers/__pycache__/embeddings.cpython-313.pyc b/sources/neuraloperator/neuralop/layers/__pycache__/embeddings.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f22fd5855c116b5a5e410031cef1099b444b4c5 Binary files /dev/null and b/sources/neuraloperator/neuralop/layers/__pycache__/embeddings.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/layers/__pycache__/fno_block.cpython-313.pyc b/sources/neuraloperator/neuralop/layers/__pycache__/fno_block.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a79595d88105cd8fce812126ae650666525e80d Binary files /dev/null and b/sources/neuraloperator/neuralop/layers/__pycache__/fno_block.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/layers/__pycache__/fourier_continuation.cpython-313.pyc b/sources/neuraloperator/neuralop/layers/__pycache__/fourier_continuation.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..831b9e1d9f4853069efc610d23f354574c81927f Binary files /dev/null and b/sources/neuraloperator/neuralop/layers/__pycache__/fourier_continuation.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/layers/__pycache__/gno_block.cpython-313.pyc b/sources/neuraloperator/neuralop/layers/__pycache__/gno_block.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1355eeaaae24cbc6fc0a0c9e91bf06388be635e3 Binary files /dev/null and b/sources/neuraloperator/neuralop/layers/__pycache__/gno_block.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/layers/__pycache__/gno_weighting_functions.cpython-313.pyc b/sources/neuraloperator/neuralop/layers/__pycache__/gno_weighting_functions.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..accb7f8bed85e0031241c7ad56f8a1c65997c356 Binary files /dev/null and b/sources/neuraloperator/neuralop/layers/__pycache__/gno_weighting_functions.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/layers/__pycache__/integral_transform.cpython-313.pyc b/sources/neuraloperator/neuralop/layers/__pycache__/integral_transform.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f3ab4792b149fe5a9e3e0e22eec930530845eb1 Binary files /dev/null and b/sources/neuraloperator/neuralop/layers/__pycache__/integral_transform.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/layers/__pycache__/neighbor_search.cpython-313.pyc b/sources/neuraloperator/neuralop/layers/__pycache__/neighbor_search.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c1b74cfd4bca59a2f8e378612beb8b643fef8ee Binary files /dev/null and b/sources/neuraloperator/neuralop/layers/__pycache__/neighbor_search.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/layers/__pycache__/normalization_layers.cpython-313.pyc b/sources/neuraloperator/neuralop/layers/__pycache__/normalization_layers.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26b985b6a8517164d5b2b470bdc1fdd9b9be1bf9 Binary files /dev/null and b/sources/neuraloperator/neuralop/layers/__pycache__/normalization_layers.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/layers/__pycache__/padding.cpython-313.pyc b/sources/neuraloperator/neuralop/layers/__pycache__/padding.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bad70aec620f580a591b1cd1866a807755a22664 Binary files /dev/null and b/sources/neuraloperator/neuralop/layers/__pycache__/padding.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/layers/__pycache__/resample.cpython-313.pyc b/sources/neuraloperator/neuralop/layers/__pycache__/resample.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3ad313ba18572f06f24fb2ba177978c63d55c71 Binary files /dev/null and b/sources/neuraloperator/neuralop/layers/__pycache__/resample.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/layers/__pycache__/rno_block.cpython-313.pyc b/sources/neuraloperator/neuralop/layers/__pycache__/rno_block.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6885e7c644b122c9eb300db1d4c705c760d85d79 Binary files /dev/null and b/sources/neuraloperator/neuralop/layers/__pycache__/rno_block.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/layers/__pycache__/segment_csr.cpython-313.pyc b/sources/neuraloperator/neuralop/layers/__pycache__/segment_csr.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..502e4da4e67ac5ab2051cd1b3c462de9c6559364 Binary files /dev/null and b/sources/neuraloperator/neuralop/layers/__pycache__/segment_csr.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/layers/__pycache__/skip_connections.cpython-313.pyc b/sources/neuraloperator/neuralop/layers/__pycache__/skip_connections.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4af547d1435a13640b97bb4cca74499b90dfa0de Binary files /dev/null and b/sources/neuraloperator/neuralop/layers/__pycache__/skip_connections.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/layers/__pycache__/spectral_convolution.cpython-313.pyc b/sources/neuraloperator/neuralop/layers/__pycache__/spectral_convolution.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40c6a52fd46772f1ba38502f0d086dce8ea38e15 Binary files /dev/null and b/sources/neuraloperator/neuralop/layers/__pycache__/spectral_convolution.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/layers/__pycache__/spherical_convolution.cpython-313.pyc b/sources/neuraloperator/neuralop/layers/__pycache__/spherical_convolution.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..caf640668599938d50cf22bca97b5f2c96f2f865 Binary files /dev/null and b/sources/neuraloperator/neuralop/layers/__pycache__/spherical_convolution.cpython-313.pyc differ diff --git a/sources/neuraloperator/neuralop/layers/attention_kernel_integral.py b/sources/neuraloperator/neuralop/layers/attention_kernel_integral.py new file mode 100644 index 0000000000000000000000000000000000000000..ccc014c5f6ec2c8fe25a1b5c58dd20deaf6ad1af --- /dev/null +++ b/sources/neuraloperator/neuralop/layers/attention_kernel_integral.py @@ -0,0 +1,246 @@ +import torch +from torch import nn +import math +from torch.nn.init import xavier_uniform_, zeros_ + + +class AttentionKernelIntegral(torch.nn.Module): + """Kernel integral transform with attention + + Computes \\int_{Omega} k(x, y) * f(y) dy, + where: + K(x, y) = \\sum_{c=1}^d q_c(x) * k_c(y), q(x) = [q_1(x); ...; q_d(x)], k(y) = [k_1(y); ...; k_d(y)] + f(y) = v(y) + More specifically, this module supports using just one input function (self-attention) or + two input functions (cross-attention) to compute the kernel integral transform. + + 1. Self-attention: + input function u(.), sampling grid D_x = {x_i}_{i=1}^N + query function: q(x_i) = u(x_i) W_q + key function: k(x_i) = u(x_i) W_k + value function: v(x_i) = u(x_i) W_v + + 2. Cross-attention: + first input function u_qry(.), sampling grid D_x = {x_i}_{i=1}^N + second input function u_src(.), sampling grid D_y = {y_j}_{j=1}^M, D_y can be different from D_x + query function: q(x_i) = u_qry(x_i) W_q + key function: k(y_j) = u_src(y_j) W_k + value function: v(y_j) = u_src(y_j) W_v + + Self-attention can be considered as a special case of cross-attention, where u = u_qry = u_src and D_x = D_y. + + The kernel integral transform will be numerically computed as: + \\int_{Omega} k(x, y) * f(y) dy \\appox \\sum_{j=1}^M * k(x, y_j) * f(y_j) * w(y_j) + For uniform quadrature, the weights w(y_j) = 1/M. + For non-uniform quadrature, the weights w(y_j) is specified as an input to the forward function. + + Parameters + ---------- + in_channels : int + Number of input channels + out_channels : int + Number of output channels + n_heads : int + Number of attention heads in multi-head attention + head_n_channels : int + Dimension of each attention head, determines how many function bases to use for the kernel + k(x, y) = \\sum_{c=1}^d \\q_c(x) * \\k_c(y), head_n_channels controls the d + pos_dim : int + Dimension of the domain, determines the dimension of coordinates + project_query : bool, optional + Whether to project the query function with pointwise linear layer + (this is sometimes not needed when using cross-attention), by default True + """ + + def __init__( + self, + in_channels, + out_channels, + n_heads, + head_n_channels, + project_query=True, + ): + super().__init__() + self.n_heads = n_heads + self.head_n_channels = head_n_channels + self.in_channels = in_channels + self.out_channels = out_channels + + self.project_query = project_query + if project_query: + self.to_q = nn.Linear(in_channels, head_n_channels * n_heads, bias=False) + else: + self.to_q = nn.Identity() + + self.to_k = nn.Linear(in_channels, head_n_channels * n_heads, bias=False) + + self.k_norm = nn.InstanceNorm1d(head_n_channels, affine=False) + self.v_norm = nn.InstanceNorm1d(head_n_channels, affine=False) + + self.to_v = nn.Linear(in_channels, head_n_channels * n_heads, bias=False) + + self.to_out = ( + nn.Linear(head_n_channels * n_heads, out_channels) + if head_n_channels * n_heads != out_channels + else nn.Identity() + ) + + self.init_gain = 1 / math.sqrt(head_n_channels) + self.diagonal_weight = self.init_gain + self.initialize_qkv_weights() + + def init_weight(self, weight, init_fn): + """ + Initialization for the projection matrix + basically initialize the weights for each heads with predefined initialization function and gain, + to add the diagonal bias, it requires input channels = head_n_channels + W = init_fn(W) + I * diagonal_weight + + init_fn is xavier_uniform_ by default + """ + + for param in weight.parameters(): + if param.ndim > 1: + for h in range(self.n_heads): + init_fn(param[h * self.head_n_channels:(h + 1) * self.head_n_channels, :], gain=self.init_gain) + if self.head_n_channels == self.in_channels: + diagonal_bias = self.diagonal_weight * torch.diag(torch.ones(param.size(-1), dtype=torch.float32)) + param.data[h * self.head_n_channels:(h + 1) * self.head_n_channels, :] += diagonal_bias + + def initialize_qkv_weights(self): + """ + Initialize the weights for q, k, v projection matrix with a small gain and add a diagonal bias, + this technique has been found useful for scale-sensitive problem that has not been normalized + see Table 8 in https://arxiv.org/pdf/2105.14995.pdf + """ + init_fn = xavier_uniform_ + + if self.project_query: + self.init_weight(self.to_q, init_fn) + self.init_weight(self.to_k, init_fn) + self.init_weight(self.to_v, init_fn) + + def normalize_wrt_domain(self, u, norm_fn): + """ + Normalize the input function with respect to the domain, + reshape the tensor to [batch_size*n_heads, num_grid_points, head_n_channels] + The second dimension is equal to the number of grid points that discretize the domain + """ + # u: the input or transformed function + batch_size = u.shape[0] + u = u.view(batch_size*self.n_heads, -1, self.head_n_channels) + u = norm_fn(u) # layer norm with channel dimension or instance norm with spatial dimension + return u.view(batch_size, self.n_heads, -1, self.head_n_channels) + + def forward( + self, + u_src, + pos_src, + positional_embedding_module=None, # positional encoding module for encoding q/k + u_qry=None, + pos_qry=None, + weights=None, + associative=True, # can be much faster if num_grid_points is larger than the channel number c + return_kernel=False, + ): + """ + Computes kernel integral transform with attention + + Parameters + ---------- + u_src: input function (used to compute key and value in attention), + tensor of shape [batch_size, num_grid_points_src, channels] + pos_src: coordinate of the second source of function's sampling points y, + tensor of shape [batch_size, num_grid_points_src, pos_dim] + positional_embedding_module: positional embedding module for encoding query/key (q/k), + a torch.nn.Module + u_qry: query function, + tensor of shape [batch_size, num_grid_points_query, channels], if not provided, u_qry = u_src + pos_qry: coordinate of query points x, + tensor of shape [batch_size, num_grid_points_query, pos_dim], if not provided, pos_qry = pos_src + weights : quadrature weight w(y_j) for the kernel integral: u(x_i) = sum_{j} k(x_i, y_j) f(y_i) w(y_j), + tensor of shape [batch_size, num_grid_points_src], if not provided assume to be 1/num_grid_points_src + associative: if True, use associativity of matrix multiplication, first multiply K^T V, then multiply Q, + much faster when num_grid_points is larger than the channel number (which is usually the case) + return_kernel: if True, return the kernel matrix (for analyzing the kernel) + + Output + ---------- + u: Output function given on the query points x. + """ + + if u_qry is None: + u_qry = u_src # go back to self attention + if pos_qry is not None: + raise ValueError('Query coordinates are provided but query function is not provided') + else: + if pos_qry is None: + raise ValueError('Query coordinates are required if query function is provided') + + if return_kernel and associative: + raise ValueError("Cannot get kernel matrix when associative is set to True") + + batch_size, num_grid_points = u_src.shape[:2] # batch size and number of grid points + pos_dim = pos_src.shape[-1] # position dimension + + q = self.to_q(u_qry) + k = self.to_k(u_src) + v = self.to_v(u_src) + q = q.view(batch_size, -1, self.n_heads, self.head_n_channels).permute(0, 2, 1, 3).contiguous() + k = k.view(batch_size, -1, self.n_heads, self.head_n_channels).permute(0, 2, 1, 3).contiguous() + v = v.view(batch_size, -1, self.n_heads, self.head_n_channels).permute(0, 2, 1, 3).contiguous() + + k = self.normalize_wrt_domain(k, self.k_norm) + v = self.normalize_wrt_domain(v, self.v_norm) + + if positional_embedding_module is not None: + if pos_dim == 2: + k_freqs_1 = positional_embedding_module.forward(pos_src[..., 0]) + k_freqs_2 = positional_embedding_module.forward(pos_src[..., 1]) + k_freqs_1 = k_freqs_1.unsqueeze(1).repeat([1, self.n_heads, 1, 1]) + k_freqs_2 = k_freqs_2.unsqueeze(1).repeat([1, self.n_heads, 1, 1]) + + if pos_qry is None: + q_freqs_1 = k_freqs_1 + q_freqs_2 = k_freqs_2 + else: + q_freqs_1 = positional_embedding_module.forward(pos_qry[..., 0]) + q_freqs_2 = positional_embedding_module.forward(pos_qry[..., 1]) + q_freqs_1 = q_freqs_1.unsqueeze(1).repeat([1, self.n_heads, 1, 1]) + q_freqs_2 = q_freqs_2.unsqueeze(1).repeat([1, self.n_heads, 1, 1]) + + q = positional_embedding_module.apply_2d_rotary_pos_emb(q, q_freqs_1, q_freqs_2) + k = positional_embedding_module.apply_2d_rotary_pos_emb(k, k_freqs_1, k_freqs_2) + elif pos_dim == 1: + k_freqs = positional_embedding_module.forward(pos_src[..., 0]) + k_freqs = k_freqs.unsqueeze(1).repeat([batch_size, self.n_heads, 1, 1]) + + if pos_qry is None: + q_freqs = k_freqs + else: + q_freqs = positional_embedding_module.forward(pos_qry[..., 0]) + q_freqs = q_freqs.unsqueeze(1).repeat([batch_size, self.n_heads, 1, 1]) + + q = positional_embedding_module.apply_1d_rotary_pos_emb(q, q_freqs) + k = positional_embedding_module.apply_1d_rotary_pos_emb(k, k_freqs) + else: + raise ValueError('Currently doesnt support relative embedding >= 3 dimensions') + + if weights is not None: + weights = weights.view(batch_size, 1, num_grid_points, 1) + else: + weights = 1.0 / num_grid_points + + if associative: + dots = torch.matmul(k.transpose(-1, -2), v) + u = torch.matmul(q, dots) * weights + else: + # this is more efficient when num_grid_points<