TabQueryBench commited on
Commit
ba93d4c
·
verified ·
1 Parent(s): 8fbd445

Resume SynthData0523 hyper_parameter_tuning/n11/tabdiff batch 3

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +237 -0
  2. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/_tabdiff_runtime/tabdiff/modules/transformer.py +258 -0
  3. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/_tabdiff_runtime/tabdiff/trainer.py +657 -0
  4. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/_tabdiff_runtime/utils_train.py +198 -0
  5. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/_tabdiff_train.py +78 -0
  6. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/bo_combo.json +3 -0
  7. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/gen_20260521_040729.log +3 -0
  8. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/input_snapshot.json +3 -0
  9. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/models_tabdiff/trained.pt +3 -0
  10. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/public_gate/normalized_schema_snapshot.json +3 -0
  11. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/public_gate/public_gate_report.json +3 -0
  12. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/public_gate/staged_input_manifest.json +3 -0
  13. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/run_config.json +3 -0
  14. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/runtime_result.json +3 -0
  15. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/staged/public/staged_features.json +3 -0
  16. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/staged/public/test.csv +3 -0
  17. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/staged/public/train.csv +3 -0
  18. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/staged/public/val.csv +3 -0
  19. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/staged/tabdiff/adapter_report.json +3 -0
  20. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/staged/tabdiff/adapter_transforms_applied.json +3 -0
  21. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/staged/tabdiff/model_input_manifest.json +3 -0
  22. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabdiff-n11-15215-20260521_040729.csv +3 -0
  23. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabdiff_train_meta.json +3 -0
  24. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/X_num_test.npy +3 -0
  25. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/X_num_train.npy +3 -0
  26. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/X_num_val.npy +3 -0
  27. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/info.json +3 -0
  28. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/real.csv +3 -0
  29. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/staged_features.json +3 -0
  30. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/test.csv +3 -0
  31. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/train.csv +3 -0
  32. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/val.csv +3 -0
  33. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/y_test.npy +3 -0
  34. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/y_train.npy +3 -0
  35. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/y_val.npy +3 -0
  36. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/train_20260521_035804.log +3 -0
  37. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_gen.py +42 -0
  38. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_runtime/.gitignore +15 -0
  39. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_runtime/LICENSE +7 -0
  40. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_runtime/README.md +201 -0
  41. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_runtime/download_dataset.py +51 -0
  42. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_runtime/eval_impute.py +82 -0
  43. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_runtime/images/tabdiff_demo.gif +3 -0
  44. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_runtime/images/tabdiff_demo.mp4 +3 -0
  45. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_runtime/images/tabdiff_flowchart.jpg +3 -0
  46. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_runtime/main.py +46 -0
  47. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_runtime/process_dataset.py +646 -0
  48. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_runtime/src/__init__.py +11 -0
  49. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_runtime/src/data.py +780 -0
  50. SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_runtime/src/env.py +39 -0
.gitattributes CHANGED
@@ -17828,3 +17828,240 @@ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_03460
17828
  SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/_tabdiff_runtime/images/tabdiff_demo.gif filter=lfs diff=lfs merge=lfs -text
17829
  SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/_tabdiff_runtime/images/tabdiff_demo.mp4 filter=lfs diff=lfs merge=lfs -text
17830
  SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/_tabdiff_runtime/tabdiff/configs/tabdiff_configs.toml filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17828
  SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/_tabdiff_runtime/images/tabdiff_demo.gif filter=lfs diff=lfs merge=lfs -text
17829
  SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/_tabdiff_runtime/images/tabdiff_demo.mp4 filter=lfs diff=lfs merge=lfs -text
17830
  SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/_tabdiff_runtime/tabdiff/configs/tabdiff_configs.toml filter=lfs diff=lfs merge=lfs -text
17831
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/bo_combo.json filter=lfs diff=lfs merge=lfs -text
17832
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/gen_20260521_040729.log filter=lfs diff=lfs merge=lfs -text
17833
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/input_snapshot.json filter=lfs diff=lfs merge=lfs -text
17834
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/models_tabdiff/trained.pt filter=lfs diff=lfs merge=lfs -text
17835
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/public_gate/normalized_schema_snapshot.json filter=lfs diff=lfs merge=lfs -text
17836
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/public_gate/public_gate_report.json filter=lfs diff=lfs merge=lfs -text
17837
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/public_gate/staged_input_manifest.json filter=lfs diff=lfs merge=lfs -text
17838
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/run_config.json filter=lfs diff=lfs merge=lfs -text
17839
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/runtime_result.json filter=lfs diff=lfs merge=lfs -text
17840
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/staged/public/staged_features.json filter=lfs diff=lfs merge=lfs -text
17841
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/staged/public/test.csv filter=lfs diff=lfs merge=lfs -text
17842
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/staged/public/train.csv filter=lfs diff=lfs merge=lfs -text
17843
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/staged/public/val.csv filter=lfs diff=lfs merge=lfs -text
17844
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/staged/tabdiff/adapter_report.json filter=lfs diff=lfs merge=lfs -text
17845
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/staged/tabdiff/adapter_transforms_applied.json filter=lfs diff=lfs merge=lfs -text
17846
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/staged/tabdiff/model_input_manifest.json filter=lfs diff=lfs merge=lfs -text
17847
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabdiff-n11-15215-20260521_040729.csv filter=lfs diff=lfs merge=lfs -text
17848
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabdiff_train_meta.json filter=lfs diff=lfs merge=lfs -text
17849
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/X_num_test.npy filter=lfs diff=lfs merge=lfs -text
17850
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/X_num_train.npy filter=lfs diff=lfs merge=lfs -text
17851
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/X_num_val.npy filter=lfs diff=lfs merge=lfs -text
17852
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/info.json filter=lfs diff=lfs merge=lfs -text
17853
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/real.csv filter=lfs diff=lfs merge=lfs -text
17854
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/staged_features.json filter=lfs diff=lfs merge=lfs -text
17855
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/test.csv filter=lfs diff=lfs merge=lfs -text
17856
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/train.csv filter=lfs diff=lfs merge=lfs -text
17857
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/val.csv filter=lfs diff=lfs merge=lfs -text
17858
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/y_test.npy filter=lfs diff=lfs merge=lfs -text
17859
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/y_train.npy filter=lfs diff=lfs merge=lfs -text
17860
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/y_val.npy filter=lfs diff=lfs merge=lfs -text
17861
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/train_20260521_035804.log filter=lfs diff=lfs merge=lfs -text
17862
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_runtime/images/tabdiff_demo.gif filter=lfs diff=lfs merge=lfs -text
17863
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_runtime/images/tabdiff_demo.mp4 filter=lfs diff=lfs merge=lfs -text
17864
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_runtime/tabdiff/configs/tabdiff_configs.toml filter=lfs diff=lfs merge=lfs -text
17865
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/bo_combo.json filter=lfs diff=lfs merge=lfs -text
17866
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/gen_20260521_041828.log filter=lfs diff=lfs merge=lfs -text
17867
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/input_snapshot.json filter=lfs diff=lfs merge=lfs -text
17868
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/models_tabdiff/trained.pt filter=lfs diff=lfs merge=lfs -text
17869
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/public_gate/normalized_schema_snapshot.json filter=lfs diff=lfs merge=lfs -text
17870
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/public_gate/public_gate_report.json filter=lfs diff=lfs merge=lfs -text
17871
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/public_gate/staged_input_manifest.json filter=lfs diff=lfs merge=lfs -text
17872
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/run_config.json filter=lfs diff=lfs merge=lfs -text
17873
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/runtime_result.json filter=lfs diff=lfs merge=lfs -text
17874
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/staged/public/staged_features.json filter=lfs diff=lfs merge=lfs -text
17875
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/staged/public/test.csv filter=lfs diff=lfs merge=lfs -text
17876
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/staged/public/train.csv filter=lfs diff=lfs merge=lfs -text
17877
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/staged/public/val.csv filter=lfs diff=lfs merge=lfs -text
17878
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/staged/tabdiff/adapter_report.json filter=lfs diff=lfs merge=lfs -text
17879
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/staged/tabdiff/adapter_transforms_applied.json filter=lfs diff=lfs merge=lfs -text
17880
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/staged/tabdiff/model_input_manifest.json filter=lfs diff=lfs merge=lfs -text
17881
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/tabdiff-n11-15215-20260521_041828.csv filter=lfs diff=lfs merge=lfs -text
17882
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/tabdiff_train_meta.json filter=lfs diff=lfs merge=lfs -text
17883
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/tabular_bundle/pipeline_n11/X_num_test.npy filter=lfs diff=lfs merge=lfs -text
17884
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/tabular_bundle/pipeline_n11/X_num_train.npy filter=lfs diff=lfs merge=lfs -text
17885
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/tabular_bundle/pipeline_n11/X_num_val.npy filter=lfs diff=lfs merge=lfs -text
17886
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/tabular_bundle/pipeline_n11/info.json filter=lfs diff=lfs merge=lfs -text
17887
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/tabular_bundle/pipeline_n11/real.csv filter=lfs diff=lfs merge=lfs -text
17888
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/tabular_bundle/pipeline_n11/staged_features.json filter=lfs diff=lfs merge=lfs -text
17889
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/tabular_bundle/pipeline_n11/test.csv filter=lfs diff=lfs merge=lfs -text
17890
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/tabular_bundle/pipeline_n11/train.csv filter=lfs diff=lfs merge=lfs -text
17891
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/tabular_bundle/pipeline_n11/val.csv filter=lfs diff=lfs merge=lfs -text
17892
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/tabular_bundle/pipeline_n11/y_test.npy filter=lfs diff=lfs merge=lfs -text
17893
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/tabular_bundle/pipeline_n11/y_train.npy filter=lfs diff=lfs merge=lfs -text
17894
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/tabular_bundle/pipeline_n11/y_val.npy filter=lfs diff=lfs merge=lfs -text
17895
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/train_20260521_040854.log filter=lfs diff=lfs merge=lfs -text
17896
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/_tabdiff_runtime/images/tabdiff_demo.gif filter=lfs diff=lfs merge=lfs -text
17897
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/_tabdiff_runtime/images/tabdiff_demo.mp4 filter=lfs diff=lfs merge=lfs -text
17898
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/_tabdiff_runtime/tabdiff/configs/tabdiff_configs.toml filter=lfs diff=lfs merge=lfs -text
17899
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/bo_combo.json filter=lfs diff=lfs merge=lfs -text
17900
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/gen_20260521_042511.log filter=lfs diff=lfs merge=lfs -text
17901
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/input_snapshot.json filter=lfs diff=lfs merge=lfs -text
17902
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/models_tabdiff/trained.pt filter=lfs diff=lfs merge=lfs -text
17903
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/public_gate/normalized_schema_snapshot.json filter=lfs diff=lfs merge=lfs -text
17904
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/public_gate/public_gate_report.json filter=lfs diff=lfs merge=lfs -text
17905
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/public_gate/staged_input_manifest.json filter=lfs diff=lfs merge=lfs -text
17906
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/run_config.json filter=lfs diff=lfs merge=lfs -text
17907
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/runtime_result.json filter=lfs diff=lfs merge=lfs -text
17908
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/staged/public/staged_features.json filter=lfs diff=lfs merge=lfs -text
17909
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/staged/public/test.csv filter=lfs diff=lfs merge=lfs -text
17910
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/staged/public/train.csv filter=lfs diff=lfs merge=lfs -text
17911
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/staged/public/val.csv filter=lfs diff=lfs merge=lfs -text
17912
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/staged/tabdiff/adapter_report.json filter=lfs diff=lfs merge=lfs -text
17913
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/staged/tabdiff/adapter_transforms_applied.json filter=lfs diff=lfs merge=lfs -text
17914
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/staged/tabdiff/model_input_manifest.json filter=lfs diff=lfs merge=lfs -text
17915
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/tabdiff-n11-15215-20260521_042511.csv filter=lfs diff=lfs merge=lfs -text
17916
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/tabdiff_train_meta.json filter=lfs diff=lfs merge=lfs -text
17917
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/tabular_bundle/pipeline_n11/X_num_test.npy filter=lfs diff=lfs merge=lfs -text
17918
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/tabular_bundle/pipeline_n11/X_num_train.npy filter=lfs diff=lfs merge=lfs -text
17919
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/tabular_bundle/pipeline_n11/X_num_val.npy filter=lfs diff=lfs merge=lfs -text
17920
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/tabular_bundle/pipeline_n11/info.json filter=lfs diff=lfs merge=lfs -text
17921
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/tabular_bundle/pipeline_n11/real.csv filter=lfs diff=lfs merge=lfs -text
17922
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/tabular_bundle/pipeline_n11/staged_features.json filter=lfs diff=lfs merge=lfs -text
17923
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/tabular_bundle/pipeline_n11/test.csv filter=lfs diff=lfs merge=lfs -text
17924
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/tabular_bundle/pipeline_n11/train.csv filter=lfs diff=lfs merge=lfs -text
17925
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/tabular_bundle/pipeline_n11/val.csv filter=lfs diff=lfs merge=lfs -text
17926
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/tabular_bundle/pipeline_n11/y_test.npy filter=lfs diff=lfs merge=lfs -text
17927
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/tabular_bundle/pipeline_n11/y_train.npy filter=lfs diff=lfs merge=lfs -text
17928
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/tabular_bundle/pipeline_n11/y_val.npy filter=lfs diff=lfs merge=lfs -text
17929
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042002/train_20260521_042002.log filter=lfs diff=lfs merge=lfs -text
17930
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/_tabdiff_runtime/images/tabdiff_demo.gif filter=lfs diff=lfs merge=lfs -text
17931
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/_tabdiff_runtime/images/tabdiff_demo.mp4 filter=lfs diff=lfs merge=lfs -text
17932
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/_tabdiff_runtime/tabdiff/configs/tabdiff_configs.toml filter=lfs diff=lfs merge=lfs -text
17933
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/bo_combo.json filter=lfs diff=lfs merge=lfs -text
17934
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/gen_20260521_043250.log filter=lfs diff=lfs merge=lfs -text
17935
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/input_snapshot.json filter=lfs diff=lfs merge=lfs -text
17936
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/models_tabdiff/trained.pt filter=lfs diff=lfs merge=lfs -text
17937
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/public_gate/normalized_schema_snapshot.json filter=lfs diff=lfs merge=lfs -text
17938
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/public_gate/public_gate_report.json filter=lfs diff=lfs merge=lfs -text
17939
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/public_gate/staged_input_manifest.json filter=lfs diff=lfs merge=lfs -text
17940
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/run_config.json filter=lfs diff=lfs merge=lfs -text
17941
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/runtime_result.json filter=lfs diff=lfs merge=lfs -text
17942
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/staged/public/staged_features.json filter=lfs diff=lfs merge=lfs -text
17943
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/staged/public/test.csv filter=lfs diff=lfs merge=lfs -text
17944
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/staged/public/train.csv filter=lfs diff=lfs merge=lfs -text
17945
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/staged/public/val.csv filter=lfs diff=lfs merge=lfs -text
17946
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/staged/tabdiff/adapter_report.json filter=lfs diff=lfs merge=lfs -text
17947
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/staged/tabdiff/adapter_transforms_applied.json filter=lfs diff=lfs merge=lfs -text
17948
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/staged/tabdiff/model_input_manifest.json filter=lfs diff=lfs merge=lfs -text
17949
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/tabdiff-n11-15215-20260521_043250.csv filter=lfs diff=lfs merge=lfs -text
17950
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/tabdiff_train_meta.json filter=lfs diff=lfs merge=lfs -text
17951
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/tabular_bundle/pipeline_n11/X_num_test.npy filter=lfs diff=lfs merge=lfs -text
17952
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/tabular_bundle/pipeline_n11/X_num_train.npy filter=lfs diff=lfs merge=lfs -text
17953
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/tabular_bundle/pipeline_n11/X_num_val.npy filter=lfs diff=lfs merge=lfs -text
17954
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/tabular_bundle/pipeline_n11/info.json filter=lfs diff=lfs merge=lfs -text
17955
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/tabular_bundle/pipeline_n11/real.csv filter=lfs diff=lfs merge=lfs -text
17956
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/tabular_bundle/pipeline_n11/staged_features.json filter=lfs diff=lfs merge=lfs -text
17957
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/tabular_bundle/pipeline_n11/test.csv filter=lfs diff=lfs merge=lfs -text
17958
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/tabular_bundle/pipeline_n11/train.csv filter=lfs diff=lfs merge=lfs -text
17959
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/tabular_bundle/pipeline_n11/val.csv filter=lfs diff=lfs merge=lfs -text
17960
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/tabular_bundle/pipeline_n11/y_test.npy filter=lfs diff=lfs merge=lfs -text
17961
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/tabular_bundle/pipeline_n11/y_train.npy filter=lfs diff=lfs merge=lfs -text
17962
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/tabular_bundle/pipeline_n11/y_val.npy filter=lfs diff=lfs merge=lfs -text
17963
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_042653/train_20260521_042653.log filter=lfs diff=lfs merge=lfs -text
17964
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/_tabdiff_runtime/images/tabdiff_demo.gif filter=lfs diff=lfs merge=lfs -text
17965
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/_tabdiff_runtime/images/tabdiff_demo.mp4 filter=lfs diff=lfs merge=lfs -text
17966
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/_tabdiff_runtime/tabdiff/configs/tabdiff_configs.toml filter=lfs diff=lfs merge=lfs -text
17967
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/bo_combo.json filter=lfs diff=lfs merge=lfs -text
17968
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/gen_20260521_044033.log filter=lfs diff=lfs merge=lfs -text
17969
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/input_snapshot.json filter=lfs diff=lfs merge=lfs -text
17970
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/models_tabdiff/trained.pt filter=lfs diff=lfs merge=lfs -text
17971
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/public_gate/normalized_schema_snapshot.json filter=lfs diff=lfs merge=lfs -text
17972
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/public_gate/public_gate_report.json filter=lfs diff=lfs merge=lfs -text
17973
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/public_gate/staged_input_manifest.json filter=lfs diff=lfs merge=lfs -text
17974
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/run_config.json filter=lfs diff=lfs merge=lfs -text
17975
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/runtime_result.json filter=lfs diff=lfs merge=lfs -text
17976
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/staged/public/staged_features.json filter=lfs diff=lfs merge=lfs -text
17977
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/staged/public/test.csv filter=lfs diff=lfs merge=lfs -text
17978
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/staged/public/train.csv filter=lfs diff=lfs merge=lfs -text
17979
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/staged/public/val.csv filter=lfs diff=lfs merge=lfs -text
17980
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/staged/tabdiff/adapter_report.json filter=lfs diff=lfs merge=lfs -text
17981
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/staged/tabdiff/adapter_transforms_applied.json filter=lfs diff=lfs merge=lfs -text
17982
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/staged/tabdiff/model_input_manifest.json filter=lfs diff=lfs merge=lfs -text
17983
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/tabdiff-n11-15215-20260521_044033.csv filter=lfs diff=lfs merge=lfs -text
17984
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/tabdiff_train_meta.json filter=lfs diff=lfs merge=lfs -text
17985
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/tabular_bundle/pipeline_n11/X_num_test.npy filter=lfs diff=lfs merge=lfs -text
17986
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/tabular_bundle/pipeline_n11/X_num_train.npy filter=lfs diff=lfs merge=lfs -text
17987
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/tabular_bundle/pipeline_n11/X_num_val.npy filter=lfs diff=lfs merge=lfs -text
17988
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/tabular_bundle/pipeline_n11/info.json filter=lfs diff=lfs merge=lfs -text
17989
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/tabular_bundle/pipeline_n11/real.csv filter=lfs diff=lfs merge=lfs -text
17990
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/tabular_bundle/pipeline_n11/staged_features.json filter=lfs diff=lfs merge=lfs -text
17991
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/tabular_bundle/pipeline_n11/test.csv filter=lfs diff=lfs merge=lfs -text
17992
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/tabular_bundle/pipeline_n11/train.csv filter=lfs diff=lfs merge=lfs -text
17993
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/tabular_bundle/pipeline_n11/val.csv filter=lfs diff=lfs merge=lfs -text
17994
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/tabular_bundle/pipeline_n11/y_test.npy filter=lfs diff=lfs merge=lfs -text
17995
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/tabular_bundle/pipeline_n11/y_train.npy filter=lfs diff=lfs merge=lfs -text
17996
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/tabular_bundle/pipeline_n11/y_val.npy filter=lfs diff=lfs merge=lfs -text
17997
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_043507/train_20260521_043507.log filter=lfs diff=lfs merge=lfs -text
17998
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/_tabdiff_runtime/images/tabdiff_demo.gif filter=lfs diff=lfs merge=lfs -text
17999
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/_tabdiff_runtime/images/tabdiff_demo.mp4 filter=lfs diff=lfs merge=lfs -text
18000
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/_tabdiff_runtime/tabdiff/configs/tabdiff_configs.toml filter=lfs diff=lfs merge=lfs -text
18001
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/bo_combo.json filter=lfs diff=lfs merge=lfs -text
18002
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/gen_20260521_045741.log filter=lfs diff=lfs merge=lfs -text
18003
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/input_snapshot.json filter=lfs diff=lfs merge=lfs -text
18004
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/models_tabdiff/trained.pt filter=lfs diff=lfs merge=lfs -text
18005
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/public_gate/normalized_schema_snapshot.json filter=lfs diff=lfs merge=lfs -text
18006
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/public_gate/public_gate_report.json filter=lfs diff=lfs merge=lfs -text
18007
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/public_gate/staged_input_manifest.json filter=lfs diff=lfs merge=lfs -text
18008
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/run_config.json filter=lfs diff=lfs merge=lfs -text
18009
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/runtime_result.json filter=lfs diff=lfs merge=lfs -text
18010
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/staged/public/staged_features.json filter=lfs diff=lfs merge=lfs -text
18011
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/staged/public/test.csv filter=lfs diff=lfs merge=lfs -text
18012
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/staged/public/train.csv filter=lfs diff=lfs merge=lfs -text
18013
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/staged/public/val.csv filter=lfs diff=lfs merge=lfs -text
18014
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/staged/tabdiff/adapter_report.json filter=lfs diff=lfs merge=lfs -text
18015
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/staged/tabdiff/adapter_transforms_applied.json filter=lfs diff=lfs merge=lfs -text
18016
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/staged/tabdiff/model_input_manifest.json filter=lfs diff=lfs merge=lfs -text
18017
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/tabdiff-n11-15215-20260521_045741.csv filter=lfs diff=lfs merge=lfs -text
18018
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/tabdiff_train_meta.json filter=lfs diff=lfs merge=lfs -text
18019
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/tabular_bundle/pipeline_n11/X_num_test.npy filter=lfs diff=lfs merge=lfs -text
18020
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/tabular_bundle/pipeline_n11/X_num_train.npy filter=lfs diff=lfs merge=lfs -text
18021
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/tabular_bundle/pipeline_n11/X_num_val.npy filter=lfs diff=lfs merge=lfs -text
18022
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/tabular_bundle/pipeline_n11/info.json filter=lfs diff=lfs merge=lfs -text
18023
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/tabular_bundle/pipeline_n11/real.csv filter=lfs diff=lfs merge=lfs -text
18024
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/tabular_bundle/pipeline_n11/staged_features.json filter=lfs diff=lfs merge=lfs -text
18025
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/tabular_bundle/pipeline_n11/test.csv filter=lfs diff=lfs merge=lfs -text
18026
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/tabular_bundle/pipeline_n11/train.csv filter=lfs diff=lfs merge=lfs -text
18027
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/tabular_bundle/pipeline_n11/val.csv filter=lfs diff=lfs merge=lfs -text
18028
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/tabular_bundle/pipeline_n11/y_test.npy filter=lfs diff=lfs merge=lfs -text
18029
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/tabular_bundle/pipeline_n11/y_train.npy filter=lfs diff=lfs merge=lfs -text
18030
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/tabular_bundle/pipeline_n11/y_val.npy filter=lfs diff=lfs merge=lfs -text
18031
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_044212/train_20260521_044213.log filter=lfs diff=lfs merge=lfs -text
18032
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/_tabdiff_runtime/images/tabdiff_demo.gif filter=lfs diff=lfs merge=lfs -text
18033
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/_tabdiff_runtime/images/tabdiff_demo.mp4 filter=lfs diff=lfs merge=lfs -text
18034
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/_tabdiff_runtime/tabdiff/configs/tabdiff_configs.toml filter=lfs diff=lfs merge=lfs -text
18035
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/bo_combo.json filter=lfs diff=lfs merge=lfs -text
18036
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/gen_20260521_051447.log filter=lfs diff=lfs merge=lfs -text
18037
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/input_snapshot.json filter=lfs diff=lfs merge=lfs -text
18038
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/models_tabdiff/trained.pt filter=lfs diff=lfs merge=lfs -text
18039
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/public_gate/normalized_schema_snapshot.json filter=lfs diff=lfs merge=lfs -text
18040
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/public_gate/public_gate_report.json filter=lfs diff=lfs merge=lfs -text
18041
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/public_gate/staged_input_manifest.json filter=lfs diff=lfs merge=lfs -text
18042
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/run_config.json filter=lfs diff=lfs merge=lfs -text
18043
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/runtime_result.json filter=lfs diff=lfs merge=lfs -text
18044
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/staged/public/staged_features.json filter=lfs diff=lfs merge=lfs -text
18045
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/staged/public/test.csv filter=lfs diff=lfs merge=lfs -text
18046
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/staged/public/train.csv filter=lfs diff=lfs merge=lfs -text
18047
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/staged/public/val.csv filter=lfs diff=lfs merge=lfs -text
18048
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/staged/tabdiff/adapter_report.json filter=lfs diff=lfs merge=lfs -text
18049
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/staged/tabdiff/adapter_transforms_applied.json filter=lfs diff=lfs merge=lfs -text
18050
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/staged/tabdiff/model_input_manifest.json filter=lfs diff=lfs merge=lfs -text
18051
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/tabdiff-n11-15215-20260521_051447.csv filter=lfs diff=lfs merge=lfs -text
18052
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/tabdiff_train_meta.json filter=lfs diff=lfs merge=lfs -text
18053
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/tabular_bundle/pipeline_n11/X_num_test.npy filter=lfs diff=lfs merge=lfs -text
18054
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/tabular_bundle/pipeline_n11/X_num_train.npy filter=lfs diff=lfs merge=lfs -text
18055
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/tabular_bundle/pipeline_n11/X_num_val.npy filter=lfs diff=lfs merge=lfs -text
18056
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/tabular_bundle/pipeline_n11/info.json filter=lfs diff=lfs merge=lfs -text
18057
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/tabular_bundle/pipeline_n11/real.csv filter=lfs diff=lfs merge=lfs -text
18058
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/tabular_bundle/pipeline_n11/staged_features.json filter=lfs diff=lfs merge=lfs -text
18059
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/tabular_bundle/pipeline_n11/test.csv filter=lfs diff=lfs merge=lfs -text
18060
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/tabular_bundle/pipeline_n11/train.csv filter=lfs diff=lfs merge=lfs -text
18061
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/tabular_bundle/pipeline_n11/val.csv filter=lfs diff=lfs merge=lfs -text
18062
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/tabular_bundle/pipeline_n11/y_test.npy filter=lfs diff=lfs merge=lfs -text
18063
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/tabular_bundle/pipeline_n11/y_train.npy filter=lfs diff=lfs merge=lfs -text
18064
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/tabular_bundle/pipeline_n11/y_val.npy filter=lfs diff=lfs merge=lfs -text
18065
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_045956/train_20260521_045956.log filter=lfs diff=lfs merge=lfs -text
18066
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_tabdiff_runtime/images/tabdiff_demo.gif filter=lfs diff=lfs merge=lfs -text
18067
+ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_tabdiff_runtime/images/tabdiff_demo.mp4 filter=lfs diff=lfs merge=lfs -text
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/_tabdiff_runtime/tabdiff/modules/transformer.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.init as nn_init
5
+ import torch.nn.functional as F
6
+ from torch import Tensor
7
+
8
+ import math
9
+
10
+ class Tokenizer(nn.Module):
11
+
12
+ def __init__(self, d_numerical, categories, d_token, bias):
13
+ super().__init__()
14
+ if categories is None:
15
+ d_bias = d_numerical
16
+ self.category_offsets = None
17
+ self.category_embeddings = None
18
+ else:
19
+ d_bias = d_numerical + len(categories)
20
+ category_offsets = torch.tensor([0] + list(categories[:-1])).cumsum(0)
21
+ self.register_buffer('category_offsets', category_offsets)
22
+ self.cat_weight = nn.Parameter(Tensor(sum(categories), d_token))
23
+ nn.init.kaiming_uniform_(self.cat_weight, a=math.sqrt(5))
24
+
25
+ # take [CLS] token into account
26
+ self.weight = nn.Parameter(Tensor(d_numerical + 1, d_token))
27
+ self.bias = nn.Parameter(Tensor(d_bias, d_token)) if bias else None
28
+ # The initialization is inspired by nn.Linear
29
+ nn_init.kaiming_uniform_(self.weight, a=math.sqrt(5))
30
+ if self.bias is not None:
31
+ nn_init.kaiming_uniform_(self.bias, a=math.sqrt(5))
32
+
33
+ @property
34
+ def n_tokens(self):
35
+ return len(self.weight) + (
36
+ 0 if self.category_offsets is None else len(self.category_offsets)
37
+ )
38
+
39
+ def forward(self, x_num, x_cat):
40
+ x_some = x_num if x_cat is None else x_cat
41
+ assert x_some is not None
42
+ x_num = torch.cat(
43
+ [torch.ones(len(x_some), 1, device=x_some.device)] # [CLS]
44
+ + ([] if x_num is None else [x_num]),
45
+ dim=1,
46
+ )
47
+
48
+ x = self.weight[None] * x_num[:, :, None]
49
+
50
+ if x_cat is not None:
51
+ for start, end in zip(self.category_offsets, torch.cat([self.category_offsets[1:], torch.tensor([x_cat.shape[1]], device=x_cat.device)])):
52
+ if start < end:
53
+ x = torch.cat(
54
+ [x, x_cat[:, start:end].unsqueeze(1) @ self.cat_weight[start:end][None]],
55
+ dim=1,
56
+ )
57
+ if self.bias is not None:
58
+ bias = torch.cat(
59
+ [
60
+ torch.zeros(1, self.bias.shape[1], device=x.device),
61
+ self.bias,
62
+ ]
63
+ )
64
+ x = x + bias[None]
65
+
66
+ return x
67
+
68
+
69
+ class MultiheadAttention(nn.Module):
70
+ def __init__(self, d, n_heads, dropout, initialization = 'kaiming'):
71
+
72
+ if n_heads > 1:
73
+ assert d % n_heads == 0
74
+ assert initialization in ['xavier', 'kaiming']
75
+
76
+ super().__init__()
77
+ self.W_q = nn.Linear(d, d)
78
+ self.W_k = nn.Linear(d, d)
79
+ self.W_v = nn.Linear(d, d)
80
+ self.W_out = nn.Linear(d, d) if n_heads > 1 else None
81
+ self.n_heads = n_heads
82
+ self.dropout = nn.Dropout(dropout) if dropout else None
83
+
84
+ for m in [self.W_q, self.W_k, self.W_v]:
85
+ if initialization == 'xavier' and (n_heads > 1 or m is not self.W_v):
86
+ # gain is needed since W_qkv is represented with 3 separate layers
87
+ nn_init.xavier_uniform_(m.weight, gain=1 / math.sqrt(2))
88
+ nn_init.zeros_(m.bias)
89
+ if self.W_out is not None:
90
+ nn_init.zeros_(self.W_out.bias)
91
+
92
+ def _reshape(self, x):
93
+ batch_size, n_tokens, d = x.shape
94
+ d_head = d // self.n_heads
95
+ return (
96
+ x.reshape(batch_size, n_tokens, self.n_heads, d_head)
97
+ .transpose(1, 2)
98
+ .reshape(batch_size * self.n_heads, n_tokens, d_head)
99
+ )
100
+
101
+ def forward(self, x_q, x_kv, key_compression = None, value_compression = None):
102
+
103
+ q, k, v = self.W_q(x_q), self.W_k(x_kv), self.W_v(x_kv)
104
+ for tensor in [q, k, v]:
105
+ assert tensor.shape[-1] % self.n_heads == 0
106
+ if key_compression is not None:
107
+ assert value_compression is not None
108
+ k = key_compression(k.transpose(1, 2)).transpose(1, 2)
109
+ v = value_compression(v.transpose(1, 2)).transpose(1, 2)
110
+ else:
111
+ assert value_compression is None
112
+
113
+ batch_size = len(q)
114
+ d_head_key = k.shape[-1] // self.n_heads
115
+ d_head_value = v.shape[-1] // self.n_heads
116
+ n_q_tokens = q.shape[1]
117
+
118
+ q = self._reshape(q)
119
+ k = self._reshape(k)
120
+
121
+ a = q @ k.transpose(1, 2)
122
+ b = math.sqrt(d_head_key)
123
+ attention = F.softmax(a/b , dim=-1)
124
+
125
+
126
+ if self.dropout is not None:
127
+ attention = self.dropout(attention)
128
+ x = attention @ self._reshape(v)
129
+ x = (
130
+ x.reshape(batch_size, self.n_heads, n_q_tokens, d_head_value)
131
+ .transpose(1, 2)
132
+ .reshape(batch_size, n_q_tokens, self.n_heads * d_head_value)
133
+ )
134
+ if self.W_out is not None:
135
+ x = self.W_out(x)
136
+
137
+ return x
138
+
139
+ class Transformer(nn.Module):
140
+
141
+ def __init__(
142
+ self,
143
+ n_layers: int,
144
+ d_token: int,
145
+ n_heads: int,
146
+ d_out: int,
147
+ d_ffn_factor: int,
148
+ attention_dropout = 0.0,
149
+ ffn_dropout = 0.0,
150
+ residual_dropout = 0.0,
151
+ activation = 'relu',
152
+ prenormalization = True,
153
+ initialization = 'kaiming',
154
+ ):
155
+ super().__init__()
156
+
157
+ def make_normalization():
158
+ return nn.LayerNorm(d_token)
159
+
160
+ d_hidden = int(d_token * d_ffn_factor)
161
+ self.layers = nn.ModuleList([])
162
+ for layer_idx in range(n_layers):
163
+ layer = nn.ModuleDict(
164
+ {
165
+ 'attention': MultiheadAttention(
166
+ d_token, n_heads, attention_dropout, initialization
167
+ ),
168
+ 'linear0': nn.Linear(
169
+ d_token, d_hidden
170
+ ),
171
+ 'linear1': nn.Linear(d_hidden, d_token),
172
+ 'norm1': make_normalization(),
173
+ }
174
+ )
175
+ if not prenormalization or layer_idx:
176
+ layer['norm0'] = make_normalization()
177
+
178
+ self.layers.append(layer)
179
+
180
+ self.activation = nn.ReLU()
181
+ self.last_activation = nn.ReLU()
182
+ # self.activation = lib.get_activation_fn(activation)
183
+ # self.last_activation = lib.get_nonglu_activation_fn(activation)
184
+ self.prenormalization = prenormalization
185
+ self.last_normalization = make_normalization() if prenormalization else None
186
+ self.ffn_dropout = ffn_dropout
187
+ self.residual_dropout = residual_dropout
188
+ self.head = nn.Linear(d_token, d_out)
189
+
190
+
191
+ def _start_residual(self, x, layer, norm_idx):
192
+ x_residual = x
193
+ if self.prenormalization:
194
+ norm_key = f'norm{norm_idx}'
195
+ if norm_key in layer:
196
+ x_residual = layer[norm_key](x_residual)
197
+ return x_residual
198
+
199
+ def _end_residual(self, x, x_residual, layer, norm_idx):
200
+ if self.residual_dropout:
201
+ x_residual = F.dropout(x_residual, self.residual_dropout, self.training)
202
+ x = x + x_residual
203
+ if not self.prenormalization:
204
+ x = layer[f'norm{norm_idx}'](x)
205
+ return x
206
+
207
+ def forward(self, x):
208
+ for layer_idx, layer in enumerate(self.layers):
209
+ is_last_layer = layer_idx + 1 == len(self.layers)
210
+
211
+ x_residual = self._start_residual(x, layer, 0)
212
+ x_residual = layer['attention'](
213
+ # for the last attention, it is enough to process only [CLS]
214
+ x_residual,
215
+ x_residual,
216
+ )
217
+
218
+ x = self._end_residual(x, x_residual, layer, 0)
219
+
220
+ x_residual = self._start_residual(x, layer, 1)
221
+ x_residual = layer['linear0'](x_residual)
222
+ x_residual = self.activation(x_residual)
223
+ if self.ffn_dropout:
224
+ x_residual = F.dropout(x_residual, self.ffn_dropout, self.training)
225
+ x_residual = layer['linear1'](x_residual)
226
+ x = self._end_residual(x, x_residual, layer, 1)
227
+ return x
228
+
229
+
230
+ class Reconstructor(nn.Module):
231
+ def __init__(self, d_numerical, categories, d_token):
232
+ super(Reconstructor, self).__init__()
233
+
234
+ self.d_numerical = d_numerical
235
+ self.categories = categories
236
+ self.d_token = d_token
237
+
238
+ self.weight = nn.Parameter(Tensor(d_numerical, d_token))
239
+ nn.init.xavier_uniform_(self.weight, gain=1 / math.sqrt(2))
240
+ self.cat_recons = nn.ModuleList()
241
+
242
+ for d in categories:
243
+ recon = nn.Linear(d_token, d)
244
+ nn.init.xavier_uniform_(recon.weight, gain=1 / math.sqrt(2))
245
+ self.cat_recons.append(recon)
246
+
247
+ def forward(self, h):
248
+ h_num = h[:, :self.d_numerical]
249
+ h_cat = h[:, self.d_numerical:]
250
+
251
+ recon_x_num = torch.mul(h_num, self.weight.unsqueeze(0)).sum(-1)
252
+ recon_x_cat = []
253
+
254
+ for i, recon in enumerate(self.cat_recons):
255
+
256
+ recon_x_cat.append(recon(h_cat[:, i]))
257
+
258
+ return recon_x_num, recon_x_cat
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/_tabdiff_runtime/tabdiff/trainer.py ADDED
@@ -0,0 +1,657 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import glob
3
+ import time
4
+ import torch
5
+ from torch.optim.lr_scheduler import ReduceLROnPlateau
6
+ import numpy as np
7
+ import pandas as pd
8
+ import json
9
+
10
+ from copy import deepcopy
11
+
12
+ from utils_train import update_ema
13
+
14
+ from tqdm import tqdm
15
+
16
+ BAR = "=============="
17
+ def print_with_bar(log_msg):
18
+ log_msg = BAR + log_msg + BAR
19
+ if "End" in log_msg:
20
+ log_msg += "\n"
21
+ print(log_msg)
22
+
23
+ class Trainer:
24
+ def __init__(
25
+ self, diffusion, train_iter, dataset, test_dataset, metrics, logger,
26
+ lr, weight_decay,
27
+ steps, batch_size, check_val_every,
28
+ sample_batch_size, model_save_path, result_save_path,
29
+ num_samples_to_generate=None,
30
+ lr_scheduler='reduce_lr_on_plateau',
31
+ reduce_lr_patience=100, factor=0.9,
32
+ ema_decay=0.997,
33
+ closs_weight_schedule = "fixed",
34
+ c_lambda = 1.0,
35
+ d_lambda = 1.0,
36
+ device=torch.device('cuda:1'),
37
+ ckpt_path = None,
38
+ y_only=False,
39
+ **kwargs
40
+ ):
41
+ self.y_only = y_only
42
+ self.diffusion = diffusion
43
+ self.ema_model = deepcopy(self.diffusion._denoise_fn)
44
+ for param in self.ema_model.parameters():
45
+ param.detach_()
46
+ self.ema_num_schedule = deepcopy(self.diffusion.num_schedule)
47
+ for param in self.ema_num_schedule.parameters():
48
+ param.detach_()
49
+ self.ema_cat_schedule = deepcopy(self.diffusion.cat_schedule)
50
+ for param in self.ema_cat_schedule.parameters():
51
+ param.detach_()
52
+
53
+ self.train_iter = train_iter
54
+ self.dataset = dataset
55
+ self.test_dataset = test_dataset
56
+ self.steps = steps
57
+ self.init_lr = lr
58
+ self.optimizer = torch.optim.AdamW(self.diffusion.parameters(), lr=lr, weight_decay=weight_decay)
59
+ self.ema_decay = ema_decay
60
+ self.lr_scheduler = lr_scheduler
61
+ # PyTorch >= 2.8: ReduceLROnPlateau no longer accepts `verbose=`
62
+ self.scheduler = ReduceLROnPlateau(
63
+ self.optimizer, mode="min", factor=factor, patience=reduce_lr_patience
64
+ )
65
+ self.closs_weight_schedule = closs_weight_schedule
66
+ self.c_lambda = c_lambda
67
+ self.d_lambda = d_lambda
68
+
69
+ self.batch_size = batch_size
70
+ self.sample_batch_size = sample_batch_size
71
+ self.num_samples_to_generate = num_samples_to_generate
72
+ self.metrics = metrics
73
+ self.logger = logger
74
+ self.check_val_every = check_val_every
75
+
76
+ self.device = device
77
+ self.model_save_path = model_save_path
78
+ self.result_save_path = result_save_path
79
+ self.ckpt_path = ckpt_path
80
+ if self.ckpt_path is not None:
81
+ state_dicts = torch.load(self.ckpt_path, map_location=self.device)
82
+ self.diffusion._denoise_fn.load_state_dict(state_dicts['denoise_fn'])
83
+ self.diffusion.num_schedule.load_state_dict(state_dicts['num_schedule'])
84
+ self.diffusion.cat_schedule.load_state_dict(state_dicts['cat_schedule'])
85
+ print(f"Weights are loaded from {self.ckpt_path}")
86
+
87
+ self.curr_epoch = int(os.path.basename(self.ckpt_path).split('_')[-1].split('.')[0]) if self.ckpt_path is not None else 0
88
+
89
+ def _anneal_lr(self, step):
90
+ frac_done = step / self.steps
91
+ lr = self.init_lr * (1 - frac_done)
92
+ for param_group in self.optimizer.param_groups:
93
+ param_group["lr"] = lr
94
+
95
+ def _run_step(self, x, closs_weight, dloss_weight):
96
+ x = x.to(self.device)
97
+
98
+ self.diffusion.train()
99
+
100
+ self.optimizer.zero_grad()
101
+
102
+ dloss, closs = self.diffusion.mixed_loss(x)
103
+
104
+ loss = dloss_weight * dloss + closs_weight * closs
105
+ loss.backward()
106
+ self.optimizer.step()
107
+
108
+ return dloss, closs
109
+
110
+ def compute_loss(self): # eval loss is not weighted
111
+ curr_dloss = 0.0
112
+ curr_closs = 0.0
113
+ curr_count = 0
114
+ data_iter = self.train_iter
115
+ for batch in data_iter:
116
+ x = batch.float().to(self.device)
117
+ self.diffusion.eval()
118
+ with torch.no_grad():
119
+ batch_dloss, batch_closs = self.diffusion.mixed_loss(x)
120
+ curr_dloss += batch_dloss.item() * len(x)
121
+ curr_closs += batch_closs.item() * len(x)
122
+ curr_count += len(x)
123
+ mloss = np.around(curr_dloss / curr_count, 4)
124
+ gloss = np.around(curr_closs / curr_count, 4)
125
+ return mloss, gloss
126
+
127
+ def run_loop(self):
128
+ patience = 0
129
+ closs_weight, dloss_weight = self.c_lambda, self.d_lambda
130
+ best_loss = np.inf
131
+ best_ema_loss = np.inf
132
+ best_val_loss = np.inf
133
+ start_time = time.time()
134
+ print_with_bar(f"Starting Trainin Loop, total number of epoch = {self.steps}")
135
+ # Set up wandb's step metric
136
+ self.logger.define_metric("epoch")
137
+ self.logger.define_metric("*", step_metric="epoch")
138
+
139
+ start_epoch = self.curr_epoch
140
+ if start_epoch > 0:
141
+ print_with_bar(f"Resuming training from epoch {start_epoch}, with validation check every {self.check_val_every} epoches")
142
+ for epoch in range (start_epoch, self.steps):
143
+ self.curr_epoch = epoch+1
144
+ # Set up pbar
145
+ pbar = tqdm(self.train_iter, total=len(self.train_iter))
146
+ pbar.set_description(f"Epoch {epoch+1}/{self.steps}")
147
+
148
+ # Compute the loss weights
149
+ if self.closs_weight_schedule == "fixed":
150
+ pass
151
+ elif self.closs_weight_schedule == "anneal":
152
+ frac_done = epoch / self.steps
153
+ closs_weight = self.c_lambda * (1 - frac_done)
154
+ else:
155
+ raise NotImplementedError(f"The continuous loss weight schedule {self.closs_weight_schedule} is not implemneted")
156
+
157
+ # Training Step
158
+ curr_dloss = 0.0
159
+ curr_closs = 0.0
160
+ curr_count = 0
161
+ curr_lr = self.optimizer.param_groups[0]['lr']
162
+ for batch in pbar:
163
+ x = batch.float().to(self.device)
164
+ batch_dloss, batch_closs = self._run_step(x, closs_weight, dloss_weight)
165
+ curr_dloss += batch_dloss.item() * len(x)
166
+ curr_closs += batch_closs.item() * len(x)
167
+ curr_count += len(x)
168
+ pbar.set_postfix({
169
+ "lr": curr_lr,
170
+ "DLoss": np.around(curr_dloss/curr_count, 4),
171
+ "CLoss": np.around(curr_closs/curr_count, 4),
172
+ "TotalLoss": np.around((curr_dloss + curr_closs)/curr_count, 4),
173
+ "closs_weight": closs_weight,
174
+ "dloss_weight": dloss_weight,
175
+ })
176
+
177
+ # Log training Loss
178
+ log_dict = {}
179
+ mloss = np.around(curr_dloss / curr_count, 4)
180
+ gloss = np.around(curr_closs / curr_count, 4)
181
+ total_loss = mloss + gloss
182
+ if np.isnan(gloss):
183
+ print('Finding Nan in gaussian loss')
184
+ break
185
+ loss_dict = {
186
+ "epoch": epoch + 1,
187
+ "lr": curr_lr,
188
+ "closs_weight": closs_weight,
189
+ "dloss_weight": dloss_weight,
190
+ "loss/c_loss": gloss,
191
+ "loss/d_loss": mloss,
192
+ "loss/total_loss": total_loss
193
+ }
194
+ log_dict.update(loss_dict)
195
+
196
+ # Log the learned noise schedules for numerical dimensions
197
+ if self.dataset.d_numerical > 0: # numerical data is not empty
198
+ num_noise_dict = {}
199
+ if self.diffusion.num_schedule.rho().dim() == 0: # non-learnable num schedule
200
+ num_noise_dict = {"num_noise/rho": self.diffusion.num_schedule.rho().item()}
201
+ else:
202
+ num_noise_dict = {f"num_noise/rho_col_{i}": value.item() for i, value in enumerate(self.diffusion.num_schedule.rho())}
203
+ log_dict.update(num_noise_dict)
204
+
205
+ # Log the learned noise schedules for categlrical dimensions
206
+ if len(self.dataset.categories) > 0: # categorical data is not empty
207
+ cat_noise_dict = {}
208
+ if self.diffusion.cat_schedule.k().dim() == 0: # non-learnable cat schedule
209
+ cat_noise_dict = {"cat_noise/k": self.diffusion.cat_schedule.k().item()}
210
+ else:
211
+ cat_noise_dict = {f"cat_noise/k_col_{i}": value.item() for i, value in enumerate(self.diffusion.cat_schedule.k())}
212
+ log_dict.update(cat_noise_dict)
213
+
214
+ # Adjust learning rate
215
+ if self.lr_scheduler == 'reduce_lr_on_plateau':
216
+ self.scheduler.step(total_loss)
217
+ elif self.lr_scheduler == 'anneal':
218
+ self._anneal_lr(epoch)
219
+ elif self.lr_scheduler == 'fixed':
220
+ pass
221
+ else:
222
+ raise NotImplementedError(f"LR scheduler with name '{self.lr_scheduler}' is not implemented")
223
+
224
+ # Update EMA models
225
+ update_ema(self.ema_model.parameters(), self.diffusion._denoise_fn.parameters(), rate=self.ema_decay)
226
+ update_ema(self.ema_num_schedule.parameters(), self.diffusion.num_schedule.parameters(), rate=self.ema_decay)
227
+ update_ema(self.ema_cat_schedule.parameters(), self.diffusion.cat_schedule.parameters(), rate=self.ema_decay)
228
+
229
+ # Save ckpt base on the best training loss
230
+ if total_loss < best_loss and self.curr_epoch > 4000:
231
+ best_loss = total_loss
232
+ to_remove = glob.glob(os.path.join(self.model_save_path, f"best_model_*"))
233
+ if to_remove:
234
+ os.remove(to_remove[0])
235
+ state_dicts = {
236
+ 'denoise_fn': self.diffusion._denoise_fn.state_dict(),
237
+ 'num_schedule':self.diffusion.num_schedule.state_dict(),
238
+ 'cat_schedule': self.diffusion.cat_schedule.state_dict(),
239
+ }
240
+ torch.save(state_dicts, os.path.join(self.model_save_path, f'best_model_{np.round(total_loss,4)}_{epoch+1}.pt'))
241
+ patience = 0
242
+ else:
243
+ patience += 1 # increment patience if best loss is not surpassed
244
+
245
+ # Compute and log EMA model loss
246
+ curr_model, curr_num_schedule, curr_cat_schedule = self.to_ema_model()
247
+ ema_mloss, ema_gloss = self.compute_loss()
248
+ self.to_model(curr_model, curr_num_schedule, curr_cat_schedule)
249
+ ema_total_loss = ema_mloss + ema_gloss
250
+ ema_loss_dict = {
251
+ "ema_loss/c_loss": ema_gloss,
252
+ "ema_loss/d_loss": ema_mloss,
253
+ "ema_loss/total_loss": ema_total_loss
254
+ }
255
+
256
+ # Save the best ema ckpt
257
+ if ema_total_loss < best_ema_loss and self.curr_epoch > 4000:
258
+ best_ema_loss = ema_total_loss
259
+ to_remove = glob.glob(os.path.join(self.model_save_path, f"best_ema_model_*"))
260
+ if to_remove:
261
+ os.remove(to_remove[0])
262
+ state_dicts = {
263
+ 'denoise_fn': self.ema_model.state_dict(),
264
+ 'num_schedule':self.ema_num_schedule.state_dict(),
265
+ 'cat_schedule': self.ema_cat_schedule.state_dict(),
266
+ }
267
+ torch.save(state_dicts, os.path.join(self.model_save_path, f'best_ema_model_{np.round(ema_total_loss,4)}_{epoch+1}.pt'))
268
+
269
+ # Evaluate Sample Quality
270
+ if (epoch+1) % self.check_val_every == 0:
271
+ state_dicts = {
272
+ 'denoise_fn': self.diffusion._denoise_fn.state_dict(),
273
+ 'num_schedule':self.diffusion.num_schedule.state_dict(),
274
+ 'cat_schedule': self.diffusion.cat_schedule.state_dict(),
275
+ }
276
+ torch.save(state_dicts, os.path.join(self.model_save_path, f'model_{epoch+1}.pt'))
277
+
278
+ print_with_bar(f"Routine Generation Evaluation every {self.check_val_every}, currently at epoch #{epoch+1}, wiht total_loss={total_loss}.")
279
+ # 适配器训练:容器内无 Chrome,跳过 Kaleido 密度图
280
+ _plot_density = os.environ.get("TABDIFF_ADAPTER_TRAIN", "").strip().lower() not in ("1", "true", "yes")
281
+ out_metrics, _, _ = self.evaluate_generation(save_metric_details=True, plot_density=_plot_density)
282
+ log_dict.update(out_metrics)
283
+ print(f"Eval Resutls of the Non-EMA model:\n {out_metrics}")
284
+
285
+ # Evaluate the EMA model
286
+ torch.save(self.ema_model.state_dict(), os.path.join(self.model_save_path, f'ema_model_{epoch+1}.pt'))
287
+ ema_out_metrics, _, _ = self.evaluate_generation(ema=True, save_metric_details=True, plot_density=_plot_density)
288
+ log_dict.update({
289
+ "ema": ema_out_metrics,
290
+ })
291
+ print(f"Eval Resutls of the EMA model:\n {ema_out_metrics}")
292
+
293
+ # Submit logs
294
+ self.logger.log(log_dict)
295
+
296
+ end_time = time.time()
297
+ print_with_bar(f"Ending Trainnig Loop, totoal training time = {end_time - start_time}")
298
+ self.logger.log({
299
+ 'training_time': end_time - start_time
300
+ })
301
+
302
+ def report_test(self, num_runs):
303
+ save_dir = self.result_save_path
304
+
305
+ shape_ = []
306
+ trend_ = []
307
+ mle_ = []
308
+ c2st_ = []
309
+ for i in range(num_runs):
310
+ print_with_bar(f"GENERAL Evaluation Run {i}")
311
+ out_metrics, extras, syn_df = self.evaluate_generation()
312
+ print(f"Results of Run {i} are: \n{out_metrics}")
313
+ shape_.append(out_metrics["density/Shape"])
314
+ trend_.append(out_metrics["density/Trend"])
315
+ mle_.append(out_metrics["mle"])
316
+ c2st_.append(out_metrics["c2st"])
317
+ # Save samples for quality evaluation
318
+ save_path = os.path.join(save_dir, "all_samples")
319
+ if not os.path.exists(save_path):
320
+ os.makedirs(save_path)
321
+ syn_df.to_csv(os.path.join(save_path, f"samples_{i}.csv"), index=False)
322
+
323
+ shape_ = np.array(shape_)
324
+ trend_ = np.array(trend_)
325
+ mle_ = np.array(mle_)
326
+ c2st_ = np.array(c2st_)
327
+
328
+ shape_error = (1 - shape_)*100
329
+ trend_error = (1 - trend_)*100
330
+ c2st_percent = c2st_ * 100
331
+
332
+ all_results = pd.DataFrame({
333
+ "shape": shape_error,
334
+ "trend": trend_error,
335
+ "mle": mle_,
336
+ "c2st": c2st_percent,
337
+ })
338
+ avg = all_results.mean(axis=0).round(3)
339
+ std = all_results.std(axis=0).round(3)
340
+ avg_std = pd.concat([avg, std], axis=1, ignore_index=True)
341
+ avg_std.columns = ["avg", "std"]
342
+ avg_std.index = [
343
+ "shape",
344
+ "trend",
345
+ "mle",
346
+ "c2st",
347
+ ]
348
+
349
+ # Savings
350
+ all_results.to_csv(f"{save_dir}/all_results.csv", index=True)
351
+ avg_std.to_csv(f"{save_dir}/avg_std.csv", index=True)
352
+ print_with_bar(f"The AVG over {num_runs} runs are: \n{avg_std}")
353
+
354
+ def report_test_dcr(self, num_runs):
355
+ save_dir = self.result_save_path
356
+
357
+ dcr_ = []
358
+ dcr_real_ = []
359
+ dcr_test_ = []
360
+ for i in range(num_runs):
361
+ print_with_bar(f"DCR Evaluation Run {i}")
362
+ out_metrics, extras, syn_df = self.evaluate_generation()
363
+ print(f"Results of Run {i} are: \n{out_metrics}")
364
+ dcr_.append(out_metrics["dcr"])
365
+ dcr_real_.append(extras["dcr_real"])
366
+ dcr_test_.append(extras["dcr_test"])
367
+ save_path = os.path.join(save_dir, "all_samples")
368
+ if not os.path.exists(save_path):
369
+ os.makedirs(save_path)
370
+ syn_df.to_csv(os.path.join(save_path, f"samples_{i}.csv"), index=False)
371
+
372
+ dcr_ = np.array(dcr_)
373
+
374
+ dcr_percent = dcr_ * 100
375
+
376
+ all_results = pd.DataFrame({
377
+ "dcr": dcr_percent,
378
+ })
379
+ avg = all_results.mean(axis=0).round(3)
380
+ std = all_results.std(axis=0).round(3)
381
+ avg_std = pd.concat([avg, std], axis=1, ignore_index=True)
382
+ avg_std.columns = ["avg", "std"]
383
+ avg_std.index = [
384
+ "dcr",
385
+ ]
386
+
387
+ # Savings
388
+ all_results.to_csv(f"{save_dir}/all_results.csv", index=True)
389
+ avg_std.to_csv(f"{save_dir}/avg_std.csv", index=True)
390
+ dcr_real = np.concatenate(dcr_real_, axis=0)
391
+ dcr_test = np.concatenate(dcr_test_, axis=0)
392
+ dcr_df = pd.DataFrame({
393
+ "dcr_real": dcr_real,
394
+ "dcr_test": dcr_test
395
+ })
396
+ dcr_df.to_csv(f"{save_dir}/dcr.csv", index=False)
397
+
398
+ print_with_bar(f"The AVG over {num_runs} runs are: \n{avg_std}")
399
+
400
+ def test(self):
401
+ _plot_density = os.environ.get("TABDIFF_ADAPTER_TRAIN", "").strip().lower() not in ("1", "true", "yes")
402
+ out_metrics, _, _ = self.evaluate_generation(save_metric_details=True, plot_density=_plot_density)
403
+ print_with_bar(f"Results of the test are: \n{out_metrics}")
404
+ self.logger.log(out_metrics)
405
+ print(out_metrics)
406
+
407
+ def evaluate_generation(self, save_metric_details=False, plot_density=False, ema=False):
408
+ self.diffusion.eval()
409
+
410
+ # Sample a synthetic table
411
+ num_samples = self.num_samples_to_generate if self.num_samples_to_generate else self.metrics.real_data_size # By default, num_samples_to_generate is not specified. In this case, we generate the same number of samples as the real dataset. This approach is consistently used across all experiments in the paper.
412
+ syn_df = self.sample_synthetic(num_samples, ema=ema)
413
+
414
+ # Save the sample
415
+ save_path = os.path.join(self.result_save_path, str(self.curr_epoch), "ema" if ema else "")
416
+ if not os.path.exists(save_path):
417
+ os.makedirs(save_path)
418
+ path = os.path.join(save_path, "samples.csv")
419
+ syn_df.to_csv(path, index=False)
420
+ print(
421
+ f"Samples are saved at {path}"
422
+ )
423
+
424
+ # 流水线仅需要 CSV:跳过 MLE/C2ST 等(合成表为字符串类别时 MLE 会报错)
425
+ if os.environ.get("TABDIFF_ADAPTER_SAMPLE_ONLY", "").strip().lower() in ("1", "true", "yes"):
426
+ return {}, {}, syn_df
427
+
428
+ # Compute evaluation metrics on the sample
429
+ syn_df_loaded = pd.read_csv(os.path.join(save_path, "samples.csv")) # In the original tabsyn code, syn_data is implicitly casted into float.64 when it gets loaded with pd.read_csv in the evaluation script. If we don't cast, the density evluation for some columns (especially those with tailed and peaked distribution) will collapse.
430
+ out_metrics, extras = self.metrics.evaluate(syn_df_loaded)
431
+
432
+ # Save metrics and metric details
433
+ path = os.path.join(save_path, "all_results.json")
434
+ with open(path, "w") as json_file:
435
+ json.dump(out_metrics, json_file, indent=4, separators=(", ", ": ")) # always locally save the output metrics
436
+ if save_metric_details:
437
+ for name, extra in extras.items():
438
+ if isinstance(extra, pd.DataFrame):
439
+ extra.to_csv(os.path.join(save_path, f"{name}.csv"))
440
+ elif isinstance(extra, dict):
441
+ with open(os.path.join(save_path, f"{name}.json"), "w") as json_file:
442
+ json.dump(extra, json_file, indent=4, separators=(", ", ": "))
443
+ else:
444
+ raise NotImplementedError(f"Extra file generated during evaluations has type {type(extra)}, and code to save this type of file is not implemented")
445
+
446
+ # Plot density figures
447
+ if plot_density:
448
+ img = self.metrics.plot_density(syn_df_loaded)
449
+ path = os.path.join(save_path, "density_plots.png")
450
+ img.save(path)
451
+ print(
452
+ f"The density plots are saved at {path}"
453
+ )
454
+ return out_metrics, extras, syn_df
455
+
456
+
457
+ def sample_synthetic(self, num_samples, keep_nan_samples=True, ema=False):
458
+ if ema:
459
+ curr_model, curr_num_schedule, curr_cat_schedule = self.to_ema_model()
460
+ info = self.metrics.info
461
+
462
+ print_with_bar(f"Starting Sampling, total samples to generate = {num_samples}")
463
+ start_time = time.time()
464
+
465
+ syn_data = self.diffusion.sample_all(num_samples, self.sample_batch_size, keep_nan_samples=keep_nan_samples)
466
+ print(f"Shape of the generated sample = {syn_data.shape}")
467
+
468
+ if keep_nan_samples:
469
+ num_all_zero_row = (syn_data.sum(dim=1) == 0).sum()
470
+ if num_all_zero_row:
471
+ print(f"The generated samples contain {num_all_zero_row} Nan instances!!!")
472
+ self.logger.log({
473
+ 'num_Nan_sample': num_all_zero_row
474
+ })
475
+
476
+ # Recover tables
477
+ num_inverse = self.dataset.num_inverse
478
+ int_inverse = self.dataset.int_inverse
479
+ cat_inverse = self.dataset.cat_inverse
480
+
481
+ if self.y_only:
482
+ if info['task_type'] == 'binclass':
483
+ syn_data = cat_inverse(syn_data)
484
+ else:
485
+ syn_data = num_inverse(syn_data)
486
+ syn_df = pd.DataFrame()
487
+ syn_df[info['column_names'][info['target_col_idx'][0]]] = syn_data[:, 0]
488
+ else:
489
+ syn_num, syn_cat, syn_target = split_num_cat_target(syn_data, info, num_inverse, int_inverse, cat_inverse)
490
+ syn_df = recover_data(syn_num, syn_cat, syn_target, info)
491
+
492
+
493
+ idx_name_mapping = info['idx_name_mapping']
494
+ idx_name_mapping = {int(key): value for key, value in idx_name_mapping.items()}
495
+
496
+ syn_df.rename(columns = idx_name_mapping, inplace=True)
497
+
498
+ end_time = time.time()
499
+ print_with_bar(f"Ending Sampling, totoal sampling time = {end_time - start_time}")
500
+
501
+ if ema:
502
+ self.to_model(curr_model, curr_num_schedule, curr_cat_schedule)
503
+
504
+ return syn_df
505
+
506
+ def to_ema_model(self):
507
+ curr_model = self.diffusion._denoise_fn
508
+ curr_num_schedule = self.diffusion.num_schedule
509
+ curr_cat_schedule = self.diffusion.cat_schedule
510
+ self.diffusion._denoise_fn = self.ema_model # temporarily install the ema parameters into the model
511
+ self.diffusion.num_schedule = self.ema_num_schedule
512
+ self.diffusion.cat_schedule = self.ema_cat_schedule
513
+
514
+ return curr_model, curr_num_schedule, curr_cat_schedule
515
+
516
+ def to_model(self, curr_model, curr_num_schedule, curr_cat_schedule):
517
+ self.diffusion._denoise_fn = curr_model # give back the parameters
518
+ self.diffusion.num_schedule = curr_num_schedule
519
+ self.diffusion.cat_schedule = curr_cat_schedule
520
+
521
+ def test_impute(self, trail_start, trial_size, resample_rounds, impute_condition, imputed_sample_save_dir, w_num, w_cat):
522
+ self.diffusion.eval()
523
+
524
+ info = self.metrics.info
525
+ task_type = info['task_type']
526
+ d_numerical, categories = self.dataset.d_numerical, self.dataset.categories
527
+ num_mask_idx, cat_mask_idx = [], []
528
+ X_train = self.dataset.X
529
+ X_train = X_train
530
+ x_num_train, x_cat_train = X_train[:,:d_numerical], X_train[:,d_numerical:]
531
+
532
+ if task_type == 'binclass': # for cat cols, push the masked col to [MASK]
533
+ cat_mask_idx += [0]
534
+ else: # for num cols, set the masked col to the col mean
535
+ num_mask_idx += [0]
536
+ avg = x_num_train[:, num_mask_idx].mean(0).to(self.device)
537
+
538
+ with torch.no_grad():
539
+
540
+ for trial in range(trail_start, trail_start+trial_size):
541
+ print_with_bar(f"Imputing trial {trial}")
542
+ X_test = self.test_dataset.X
543
+ X_test = deepcopy(X_test).to(self.device)
544
+ x_num_test, x_cat_test = X_test[:, :d_numerical], X_test[:, d_numerical:].long()
545
+
546
+ # Apply mask to x_0
547
+ if num_mask_idx:
548
+ x_num_test[:, num_mask_idx] = avg
549
+ if cat_mask_idx:
550
+ x_cat_test[:, cat_mask_idx] = torch.tensor(categories, dtype=x_cat_test.dtype, device=x_cat_test.device)[cat_mask_idx]
551
+
552
+ # Sample imputed tables
553
+ syn_data = self.diffusion.sample_impute(x_num_test, x_cat_test, num_mask_idx, cat_mask_idx, resample_rounds, impute_condition, w_num, w_cat)
554
+ print(f"Shape of the imputed sample = {syn_data.shape}")
555
+
556
+ # Recover tables
557
+ num_inverse = self.dataset.num_inverse
558
+ int_inverse = self.dataset.int_inverse
559
+ cat_inverse = self.dataset.cat_inverse
560
+
561
+ if torch.any((syn_data[:, d_numerical+1:]).max(dim=0).values > (x_cat_train[:,1:]).max(dim=0).values): # if the test set contains categories not presented in the train set, we can not do cat_inverse. So we implement a patch that set those columns to the same as the train set
562
+ print("Test set contains extra categories, and so does imputed syn data. We cannot do cat_inverse. So we set the cat columns as the same as the train set")
563
+ syn_data[:, d_numerical+1:] = x_cat_train[:syn_data.shape[0],1:]
564
+
565
+
566
+ syn_num, syn_cat, syn_target = split_num_cat_target(syn_data, info, num_inverse, int_inverse, cat_inverse)
567
+ syn_df = recover_data(syn_num, syn_cat, syn_target, info)
568
+
569
+ idx_name_mapping = info['idx_name_mapping']
570
+ idx_name_mapping = {int(key): value for key, value in idx_name_mapping.items()}
571
+
572
+ syn_df.rename(columns = idx_name_mapping, inplace=True)
573
+
574
+ # Save imputed samples
575
+ os.makedirs(imputed_sample_save_dir) if not os.path.exists(imputed_sample_save_dir) else None
576
+ print(f"Imputed samples are saved to {imputed_sample_save_dir}/{trial}.csv")
577
+ syn_df.to_csv(f'{imputed_sample_save_dir}/{trial}.csv', index = False)
578
+
579
+ def _as_numpy_float32(x):
580
+ """Inverse 变换可能返回 Tensor;统一为 numpy float32(含 0 列)。"""
581
+ if x is None:
582
+ return np.array([], dtype=np.float32)
583
+ if isinstance(x, torch.Tensor):
584
+ x = x.detach().cpu().numpy()
585
+ return np.asarray(x, dtype=np.float32)
586
+
587
+
588
+ @torch.no_grad()
589
+ def split_num_cat_target(syn_data, info, num_inverse, int_inverse, cat_inverse):
590
+ task_type = info['task_type']
591
+
592
+ num_col_idx = info['num_col_idx']
593
+ cat_col_idx = info['cat_col_idx']
594
+ target_col_idx = info['target_col_idx']
595
+
596
+ n_num_feat = len(num_col_idx)
597
+ n_cat_feat = len(cat_col_idx)
598
+
599
+ if task_type == 'regression':
600
+ n_num_feat += len(target_col_idx)
601
+ else:
602
+ n_cat_feat += len(target_col_idx)
603
+
604
+ syn_num = syn_data[:, :n_num_feat]
605
+ syn_cat = syn_data[:, n_num_feat:]
606
+
607
+ if n_num_feat > 0:
608
+ syn_num = _as_numpy_float32(num_inverse(syn_num))
609
+ syn_num = _as_numpy_float32(int_inverse(syn_num))
610
+ else:
611
+ syn_num = np.zeros((syn_data.shape[0], 0), dtype=np.float32)
612
+ syn_cat = cat_inverse(syn_cat)
613
+
614
+
615
+ if info['task_type'] == 'regression':
616
+ syn_target = syn_num[:, :len(target_col_idx)]
617
+ syn_num = syn_num[:, len(target_col_idx):]
618
+
619
+ else:
620
+ print(syn_cat.shape)
621
+ syn_target = syn_cat[:, :len(target_col_idx)]
622
+ syn_cat = syn_cat[:, len(target_col_idx):]
623
+
624
+ return syn_num, syn_cat, syn_target
625
+
626
+ def recover_data(syn_num, syn_cat, syn_target, info):
627
+
628
+ num_col_idx = info['num_col_idx']
629
+ cat_col_idx = info['cat_col_idx']
630
+ target_col_idx = info['target_col_idx']
631
+
632
+
633
+ idx_mapping = info['idx_mapping']
634
+ idx_mapping = {int(key): value for key, value in idx_mapping.items()}
635
+
636
+ syn_df = pd.DataFrame()
637
+
638
+ if info['task_type'] == 'regression':
639
+ for i in range(len(num_col_idx) + len(cat_col_idx) + len(target_col_idx)):
640
+ if i in set(num_col_idx):
641
+ syn_df[i] = syn_num[:, idx_mapping[i]]
642
+ elif i in set(cat_col_idx):
643
+ syn_df[i] = syn_cat[:, idx_mapping[i] - len(num_col_idx)]
644
+ else:
645
+ syn_df[i] = syn_target[:, idx_mapping[i] - len(num_col_idx) - len(cat_col_idx)]
646
+
647
+
648
+ else:
649
+ for i in range(len(num_col_idx) + len(cat_col_idx) + len(target_col_idx)):
650
+ if i in set(num_col_idx):
651
+ syn_df[i] = syn_num[:, idx_mapping[i]]
652
+ elif i in set(cat_col_idx):
653
+ syn_df[i] = syn_cat[:, idx_mapping[i] - len(num_col_idx)]
654
+ else:
655
+ syn_df[i] = syn_target[:, idx_mapping[i] - len(num_col_idx) - len(cat_col_idx)]
656
+
657
+ return syn_df
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/_tabdiff_runtime/utils_train.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import os
3
+
4
+ import src
5
+ from torch.utils.data import Dataset
6
+
7
+ import torch
8
+
9
+
10
+ class TabularDataset(Dataset):
11
+ def __init__(self, X_num, X_cat):
12
+ self.X_num = X_num
13
+ self.X_cat = X_cat
14
+
15
+ def __getitem__(self, index):
16
+ this_num = self.X_num[index]
17
+ this_cat = self.X_cat[index]
18
+
19
+ sample = (this_num, this_cat)
20
+
21
+ return sample
22
+
23
+ def __len__(self):
24
+ return self.X_num.shape[0]
25
+
26
+ class TabDiffDataset(Dataset):
27
+ def __init__(self, dataname, data_dir, info, isTrain=True, y_only=False, dequant_dist='none', int_dequant_factor=0.0):
28
+ self.dataname = dataname
29
+ self.data_dir = data_dir
30
+ self.info = info
31
+ self.isTrain = isTrain
32
+
33
+ X_num, X_cat, categories, d_numerical, num_inverse, int_inverse, cat_inverse = preprocess(data_dir, y_only, dequant_dist, int_dequant_factor, task_type = info['task_type'], inverse=True)
34
+ categories = np.array(categories)
35
+
36
+ X_train_num, _ = X_num
37
+ X_train_cat, _ = X_cat
38
+
39
+ X_train_num, X_test_num = X_num
40
+ X_train_cat, X_test_cat = X_cat
41
+
42
+ X_train_num, X_test_num = torch.tensor(X_train_num).float(), torch.tensor(X_test_num).float()
43
+ X_train_cat, X_test_cat = torch.tensor(X_train_cat), torch.tensor(X_test_cat)
44
+
45
+ self.X = torch.cat((X_train_num, X_train_cat), dim=1) if isTrain else torch.cat((X_test_num, X_test_cat), dim=1)
46
+ self.num_inverse = num_inverse
47
+ self.int_inverse = int_inverse
48
+ self.cat_inverse = cat_inverse
49
+ self.d_numerical = d_numerical
50
+ self.categories = categories
51
+
52
+ def __getitem__(self, index):
53
+ return self.X[index]
54
+
55
+ def __len__(self):
56
+ return self.X.shape[0]
57
+
58
+ def preprocess(dataset_path, y_only=False, dequant_dist='none', int_dequant_factor=0.0, task_type = 'binclass', inverse = False, cat_encoding = None, concat = True):
59
+
60
+ T_dict = {}
61
+
62
+ T_dict['normalization'] = "quantile"
63
+ T_dict['num_nan_policy'] = 'mean'
64
+ T_dict['cat_nan_policy'] = None
65
+ T_dict['cat_min_frequency'] = None
66
+ T_dict['cat_encoding'] = cat_encoding
67
+ T_dict['y_policy'] = "default"
68
+ T_dict['dequant_dist'] = dequant_dist
69
+ T_dict['int_dequant_factor'] = int_dequant_factor
70
+
71
+ T = src.Transformations(**T_dict)
72
+
73
+ dataset = make_dataset(
74
+ data_path = dataset_path,
75
+ T = T,
76
+ task_type = task_type,
77
+ change_val = False,
78
+ concat = concat,
79
+ y_only = y_only,
80
+ )
81
+
82
+ if cat_encoding is None:
83
+ X_num = dataset.X_num
84
+ X_cat = dataset.X_cat
85
+
86
+ X_train_num, X_test_num = X_num['train'], X_num['test']
87
+ if X_cat is None:
88
+ X_train_cat = np.empty((X_train_num.shape[0], 0), dtype=np.int64)
89
+ X_test_cat = np.empty((X_test_num.shape[0], 0), dtype=np.int64)
90
+ categories = []
91
+ else:
92
+ X_train_cat, X_test_cat = X_cat['train'], X_cat['test']
93
+ categories = src.get_categories(X_train_cat)
94
+ d_numerical = X_train_num.shape[1]
95
+
96
+ X_num = (X_train_num, X_test_num)
97
+ X_cat = (X_train_cat, X_test_cat)
98
+
99
+
100
+ if inverse:
101
+ num_inverse = dataset.num_transform.inverse_transform if dataset.num_transform is not None else lambda x: x
102
+ int_inverse = dataset.int_transform.inverse_transform if dataset.int_transform is not None else lambda x: x
103
+ cat_inverse = dataset.cat_transform.inverse_transform if dataset.cat_transform is not None else lambda x: x
104
+
105
+ return X_num, X_cat, categories, d_numerical, num_inverse, int_inverse, cat_inverse
106
+ else:
107
+ return X_num, X_cat, categories, d_numerical
108
+ else:
109
+ return dataset
110
+
111
+
112
+ def update_ema(target_params, source_params, rate=0.999):
113
+ """
114
+ Update target parameters to be closer to those of source parameters using
115
+ an exponential moving average.
116
+ :param target_params: the target parameter sequence.
117
+ :param source_params: the source parameter sequence.
118
+ :param rate: the EMA rate (closer to 1 means slower).
119
+ """
120
+ for target, source in zip(target_params, source_params):
121
+ target.detach().mul_(rate).add_(source.detach(), alpha=1 - rate)
122
+
123
+
124
+
125
+ def concat_y_to_X(X, y):
126
+ if X is None:
127
+ return y.reshape(-1, 1)
128
+ return np.concatenate([y.reshape(-1, 1), X], axis=1)
129
+
130
+
131
+ def make_dataset(
132
+ data_path: str,
133
+ T: src.Transformations,
134
+ task_type,
135
+ change_val: bool,
136
+ concat = True,
137
+ y_only = False,
138
+ ):
139
+
140
+ # classification
141
+ if task_type == 'binclass' or task_type == 'multiclass':
142
+ has_cat = os.path.exists(os.path.join(data_path, 'X_cat_train.npy'))
143
+ X_cat = {} if (has_cat or concat) else None
144
+ X_num = {} if os.path.exists(os.path.join(data_path, 'X_num_train.npy')) else None
145
+ y = {} if os.path.exists(os.path.join(data_path, 'y_train.npy')) else None
146
+
147
+ for split in ['train', 'test']:
148
+ X_num_t, X_cat_t, y_t = src.read_pure_data(data_path, split)
149
+ if y_only:
150
+ X_num_t = X_num_t[:, :0]
151
+ X_cat_t = X_cat_t[:, :0]
152
+ if X_num is not None:
153
+ X_num[split] = X_num_t
154
+ if X_cat is not None:
155
+ if concat:
156
+ X_cat_t = concat_y_to_X(X_cat_t, y_t)
157
+ X_cat[split] = X_cat_t
158
+ if y is not None:
159
+ y[split] = y_t
160
+ else:
161
+ # regression
162
+ X_cat = {} if os.path.exists(os.path.join(data_path, 'X_cat_train.npy')) else None
163
+ X_num = {} if os.path.exists(os.path.join(data_path, 'X_num_train.npy')) else None
164
+ y = {} if os.path.exists(os.path.join(data_path, 'y_train.npy')) else None
165
+
166
+ for split in ['train', 'test']:
167
+ X_num_t, X_cat_t, y_t = src.read_pure_data(data_path, split)
168
+ if y_only:
169
+ X_num_t = X_num_t[:, :0]
170
+ X_cat_t = X_cat_t[:, :0]
171
+ if X_num is not None:
172
+ if concat:
173
+ X_num_t = concat_y_to_X(X_num_t, y_t)
174
+ X_num[split] = X_num_t
175
+ if X_cat is not None:
176
+ X_cat[split] = X_cat_t
177
+ if y is not None:
178
+ y[split] = y_t
179
+
180
+ info = src.load_json(os.path.join(data_path, 'info.json'))
181
+ int_col_idx_wrt_num = info['int_col_idx_wrt_num']
182
+
183
+ if y_only:
184
+ int_col_idx_wrt_num = []
185
+ D = src.Dataset(
186
+ X_num,
187
+ X_cat,
188
+ y,
189
+ int_col_idx_wrt_num,
190
+ y_info={},
191
+ task_type=src.TaskType(info['task_type']),
192
+ n_classes=info.get('n_classes')
193
+ )
194
+
195
+ if change_val:
196
+ D = src.change_val(D)
197
+
198
+ return src.transform_dataset(D, T, None)
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/_tabdiff_train.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os, shutil, subprocess, sys
3
+ td = r"/workspace/TabDiff"
4
+ name = r"pipeline_n11"
5
+ src = r"/work/output-Benchmark-trainonly-v1/n11/tabdiff/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11"
6
+ rt = r"/work/output-Benchmark-trainonly-v1/n11/tabdiff/tabdiff-n11-20260521_035804/_tabdiff_runtime"
7
+ shutil.rmtree(rt, ignore_errors=True)
8
+
9
+ def _ignore(_, names):
10
+ skip = {"__pycache__", "data", "synthetic", "result", "results", "ckpt"}
11
+ return [n for n in names if n in skip or n.endswith(".pyc")]
12
+
13
+ shutil.copytree(td, rt, ignore=_ignore)
14
+
15
+ def _replace_once(path, old, new):
16
+ text = open(path, "r", encoding="utf-8").read()
17
+ if old not in text:
18
+ raise RuntimeError(f"patch anchor not found in {path}")
19
+ text = text.replace(old, new, 1)
20
+ with open(path, "w", encoding="utf-8") as f:
21
+ f.write(text)
22
+
23
+ _replace_once(
24
+ os.path.join(rt, "utils_train.py"),
25
+ " X_train_num, X_test_num = X_num['train'], X_num['test']\n X_train_cat, X_test_cat = X_cat['train'], X_cat['test']\n \n categories = src.get_categories(X_train_cat)\n",
26
+ " X_train_num, X_test_num = X_num['train'], X_num['test']\n if X_cat is None:\n X_train_cat = np.empty((X_train_num.shape[0], 0), dtype=np.int64)\n X_test_cat = np.empty((X_test_num.shape[0], 0), dtype=np.int64)\n categories = []\n else:\n X_train_cat, X_test_cat = X_cat['train'], X_cat['test']\n categories = src.get_categories(X_train_cat)\n",
27
+ )
28
+ _replace_once(
29
+ os.path.join(rt, "utils_train.py"),
30
+ " X_cat = {} if os.path.exists(os.path.join(data_path, 'X_cat_train.npy')) else None\n X_num = {} if os.path.exists(os.path.join(data_path, 'X_num_train.npy')) else None\n y = {} if os.path.exists(os.path.join(data_path, 'y_train.npy')) else None\n",
31
+ " has_cat = os.path.exists(os.path.join(data_path, 'X_cat_train.npy'))\n X_cat = {} if (has_cat or concat) else None\n X_num = {} if os.path.exists(os.path.join(data_path, 'X_num_train.npy')) else None\n y = {} if os.path.exists(os.path.join(data_path, 'y_train.npy')) else None\n",
32
+ )
33
+ _replace_once(
34
+ os.path.join(rt, "src", "data.py"),
35
+ " num_workers=1,\n",
36
+ " num_workers=int(os.environ.get('TABDIFF_NUM_WORKERS', '0')),\n",
37
+ )
38
+ _replace_once(
39
+ os.path.join(rt, "src", "data.py"),
40
+ " loader = torch.utils.data.DataLoader(torch_dataset, batch_size=batch_size, shuffle=shuffle, num_workers=1)\n",
41
+ " loader = torch.utils.data.DataLoader(torch_dataset, batch_size=batch_size, shuffle=shuffle, num_workers=int(os.environ.get('TABDIFF_NUM_WORKERS', '0')))\n",
42
+ )
43
+ _replace_once(
44
+ os.path.join(rt, "tabdiff", "main.py"),
45
+ " if os.environ.get(\"TABDIFF_ADAPTER_TRAIN\", \"\").strip() and args.mode == \"train\":\n raw_config[\"train\"][\"main\"][\"check_val_every\"] = int(raw_config[\"train\"][\"main\"][\"steps\"])\n\n ## Load training data\n",
46
+ " if os.environ.get(\"TABDIFF_ADAPTER_TRAIN\", \"\").strip() and args.mode == \"train\":\n raw_config[\"train\"][\"main\"][\"check_val_every\"] = int(raw_config[\"train\"][\"main\"][\"steps\"])\n\n _train_batch = os.environ.get(\"TABDIFF_BATCH_SIZE\", \"\").strip() or os.environ.get(\"TABDIFF_TRAIN_BATCH_SIZE\", \"\").strip()\n if _train_batch:\n raw_config[\"train\"][\"main\"][\"batch_size\"] = max(1, int(_train_batch))\n _sample_batch = os.environ.get(\"TABDIFF_SAMPLE_BATCH_SIZE\", \"\").strip()\n if _sample_batch:\n raw_config[\"sample\"][\"batch_size\"] = max(1, int(_sample_batch))\n _train_lr = os.environ.get(\"TABDIFF_LR\", \"\").strip() or os.environ.get(\"TABDIFF_LEARNING_RATE\", \"\").strip()\n if _train_lr:\n raw_config[\"train\"][\"main\"][\"lr\"] = float(_train_lr)\n _num_timesteps = os.environ.get(\"TABDIFF_NUM_TIMESTEPS\", \"\").strip() or os.environ.get(\"TABDIFF_TIMESTEPS\", \"\").strip()\n if _num_timesteps:\n raw_config[\"diffusion_params\"][\"num_timesteps\"] = max(1, int(_num_timesteps))\n\n ## Load training data\n",
47
+ )
48
+ _replace_once(
49
+ os.path.join(rt, "tabdiff", "main.py"),
50
+ " num_workers = 4,\n",
51
+ " num_workers = int(os.environ.get('TABDIFF_NUM_WORKERS', '0')),\n",
52
+ )
53
+ dst_data = os.path.join(rt, "data", name)
54
+ dst_syn = os.path.join(rt, "synthetic", name)
55
+ shutil.rmtree(dst_data, ignore_errors=True)
56
+ os.makedirs(os.path.dirname(dst_data), exist_ok=True)
57
+ shutil.copytree(src, dst_data)
58
+ os.makedirs(dst_syn, exist_ok=True)
59
+ for fn in ("real.csv", "test.csv", "val.csv"):
60
+ shutil.copy(os.path.join(src, fn), os.path.join(dst_syn, fn))
61
+ os.chdir(rt)
62
+ os.environ["PYTHONPATH"] = rt + os.pathsep + os.environ.get("PYTHONPATH", "")
63
+ os.environ["TABDIFF_SMOKE_STEPS"] = "500"
64
+ os.environ["TABDIFF_STEPS"] = "500"
65
+ os.environ["TABDIFF_BATCH_SIZE"] = "512"
66
+ os.environ["TABDIFF_TRAIN_BATCH_SIZE"] = "512"
67
+ os.environ["TABDIFF_SAMPLE_BATCH_SIZE"] = "512"
68
+ os.environ["TABDIFF_LR"] = "0.0001"
69
+ os.environ["TABDIFF_LEARNING_RATE"] = "0.0001"
70
+ os.environ["TABDIFF_NUM_TIMESTEPS"] = "25"
71
+ os.environ["TABDIFF_TIMESTEPS"] = "25"
72
+ os.environ["TABDIFF_NUM_WORKERS"] = "0"
73
+ os.environ["TABDIFF_ADAPTER_TRAIN"] = "1"
74
+ subprocess.check_call([
75
+ sys.executable, "-m", "tabdiff.main",
76
+ "--dataname", name, "--mode", "train", "--gpu", "0",
77
+ "--no_wandb", "--exp_name", r"adapter_learnable",
78
+ ])
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/bo_combo.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3e56715bbf6e0cd4990b3e0d2b5b783d56afedb66bcb460b2d03f96869f47db1
3
+ size 125
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/gen_20260521_040729.log ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:36bcc05f889fca11bc6b43cee520ca9ac4821db94ec465de1873a83f7c5874f3
3
+ size 13069
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/input_snapshot.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d72149d5374a893bfa5c45ba770dafd723399f1e8e700b03f797a0cf5c65dbc4
3
+ size 1360
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/models_tabdiff/trained.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:306660b8aad4549267c68390b017e15ddb9bc06a02c80515eb72a97ae31a81eb
3
+ size 74
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/public_gate/normalized_schema_snapshot.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:68c3209b66f9891477ccb430a3d02e3a299eb9c1a2d045bbf528bdfeb8de4fb0
3
+ size 5283
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/public_gate/public_gate_report.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6336138aac04ffe8bd9b1596f9d11556e4417d85ddb950dd20c9532ef6b9fd80
3
+ size 915
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/public_gate/staged_input_manifest.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f2eb47ae72c0d6acc47a93b1c5f633ccab874e689ba024bc8ac52a309f327bd7
3
+ size 6099
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/run_config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d6c577a090c6e4594cba6aec7a31dc93f50ec1b9bd84e5b4e36692a3ef22615a
3
+ size 2433
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/runtime_result.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:98b245b4bc8a855caafbe1a97b721c5297187c029e257c539868359764a24d5f
3
+ size 916
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/staged/public/staged_features.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7ea5e7a5363e366f12e9794c57325c7f28e71ef584464c2f78fa67b80eca9a82
3
+ size 1025
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/staged/public/test.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bf4e935f84569b849b662718eaa19be605037d46a5f7391f164728d6d9c3bb50
3
+ size 148017
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/staged/public/train.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3ab621ac8239797506ce800c1409422452b8127da93add91dd9e6d63ddeec6f7
3
+ size 1182326
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/staged/public/val.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:374e44edf25e58ca37eabbef0485c98cecdbdfa9d24da738937f404840bfad44
3
+ size 147784
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/staged/tabdiff/adapter_report.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:da50dc27517dc399660733be2f25d0dbe6d06c7783faa512dabf97322dc9649b
3
+ size 323
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/staged/tabdiff/adapter_transforms_applied.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945
3
+ size 2
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/staged/tabdiff/model_input_manifest.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f6688cb9bcc21c08148b2f89f42cf34a950323b2c23a7f4ca9e44473f1a8487d
3
+ size 6298
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabdiff-n11-15215-20260521_040729.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d058fcfb199e48246485d996ae3d7376903c2aad72e41a6c0a7da0e86782ef11
3
+ size 1554244
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabdiff_train_meta.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c1e792c57347b045635e0602f9573610acdbf6cdc7ac6c94039a57503ef3cb12
3
+ size 534
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/X_num_test.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:25f5aa50a1a26a08e947c0d7e7b819cab744a982f03e91fc4aa148b107aa8ce8
3
+ size 76248
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/X_num_train.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e325cf01927e570f62f1a49f4bc2822dc29b1aafe3c8be5d3d89a01d2df6e5ec
3
+ size 608728
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/X_num_val.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:998d48896c06f1673a7af7e251054b45fab2ff2040dfe0a9206235e10f9001cb
3
+ size 76168
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/info.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:66ca6bdc5c40407a8049688a9e9f8ff98bdbd8d26499d907751f29c09607145b
3
+ size 2199
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/real.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3ab621ac8239797506ce800c1409422452b8127da93add91dd9e6d63ddeec6f7
3
+ size 1182326
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/staged_features.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7ea5e7a5363e366f12e9794c57325c7f28e71ef584464c2f78fa67b80eca9a82
3
+ size 1025
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/test.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bf4e935f84569b849b662718eaa19be605037d46a5f7391f164728d6d9c3bb50
3
+ size 148017
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/train.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3ab621ac8239797506ce800c1409422452b8127da93add91dd9e6d63ddeec6f7
3
+ size 1182326
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/val.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:374e44edf25e58ca37eabbef0485c98cecdbdfa9d24da738937f404840bfad44
3
+ size 147784
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/y_test.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:825ce3e2cdf78c6714903278473b81851367919d7f5810d9c1c71c9f02633540
3
+ size 15352
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/y_train.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:95905dd042874f4c4e7523f7525b2864e220ef3c6fcdc58877ca3944645899cf
3
+ size 121848
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/tabular_bundle/pipeline_n11/y_val.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:babb398ab19fc90389945862a1227d04f9aa48293af50c7091056137a6d2f2f5
3
+ size 15336
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_035804/train_20260521_035804.log ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3aec034ed7c63ee59cdb0b019837dc5aa3985f73918113d9fe1c1ae648564b06
3
+ size 3114503
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_gen.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os, shutil, subprocess, sys
3
+ td = r"/workspace/TabDiff"
4
+ name = r"pipeline_n11"
5
+ src = r"/work/output-Benchmark-trainonly-v1/n11/tabdiff/tabdiff-n11-20260521_040854/tabular_bundle/pipeline_n11"
6
+ rt = r"/work/output-Benchmark-trainonly-v1/n11/tabdiff/tabdiff-n11-20260521_040854/_tabdiff_runtime"
7
+ if not os.path.exists(rt):
8
+ def _ignore(_, names):
9
+ skip = {"__pycache__", "data", "synthetic", "result", "results", "ckpt"}
10
+ return [n for n in names if n in skip or n.endswith(".pyc")]
11
+ shutil.copytree(td, rt, ignore=_ignore)
12
+ dst_data = os.path.join(rt, "data", name)
13
+ dst_syn = os.path.join(rt, "synthetic", name)
14
+ shutil.rmtree(dst_data, ignore_errors=True)
15
+ os.makedirs(os.path.dirname(dst_data), exist_ok=True)
16
+ shutil.copytree(src, dst_data)
17
+ os.makedirs(dst_syn, exist_ok=True)
18
+ for fn in ("real.csv", "test.csv", "val.csv"):
19
+ shutil.copy(os.path.join(src, fn), os.path.join(dst_syn, fn))
20
+ os.chdir(rt)
21
+ os.environ["PYTHONPATH"] = rt + os.pathsep + os.environ.get("PYTHONPATH", "")
22
+ subprocess.check_call([
23
+ sys.executable, "-m", "tabdiff.main",
24
+ "--dataname", name, "--mode", "test", "--gpu", "0",
25
+ "--no_wandb", "--exp_name", r"adapter_learnable",
26
+ "--ckpt_path", r"/work/output-Benchmark-trainonly-v1/n11/tabdiff/tabdiff-n11-20260521_040854/_tabdiff_runtime/tabdiff/ckpt/pipeline_n11/adapter_learnable/model_500.pt",
27
+ "--num_samples_to_generate", str(int(15215)),
28
+ ])
29
+ # test() 写入 tabdiff/result/<dataname>/<exp>/<epoch>/samples.csv
30
+ base = os.path.join(rt, "tabdiff", "result", name, r"adapter_learnable")
31
+ best = None
32
+ best_t = -1.0
33
+ for root, _, files in os.walk(base):
34
+ if "samples.csv" in files:
35
+ p = os.path.join(root, "samples.csv")
36
+ t = os.path.getmtime(p)
37
+ if t > best_t:
38
+ best_t = t
39
+ best = p
40
+ if not best:
41
+ raise SystemExit("tabdiff: no samples.csv under " + base)
42
+ shutil.copy(best, r"/work/output-Benchmark-trainonly-v1/n11/tabdiff/tabdiff-n11-20260521_040854/tabdiff-n11-15215-20260521_041828.csv")
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_runtime/.gitignore ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ **/__pycache__/**
2
+ *.pyc
3
+
4
+ data/*
5
+ !/data/Info/
6
+
7
+ wandb/
8
+ eval/
9
+ synthetic/
10
+ impute/
11
+ workspace/
12
+ debug/
13
+ tabdiff/result/
14
+
15
+ **/ckpt/*
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_runtime/LICENSE ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ Copyright 2024 Minkai Xu
2
+
3
+ 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:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ 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.
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_runtime/README.md ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TabDiff: a Mixed-type Diffusion Model for Tabular Data Generation
2
+
3
+ <p align="center">
4
+ <a href="https://github.com/MinkaiXu/TabDiff/blob/main/LICENSE">
5
+ <img alt="MIT License" src="https://img.shields.io/badge/License-MIT-yellow.svg">
6
+ </a>
7
+ <a href="https://openreview.net/forum?id=swvURjrt8z">
8
+ <img alt="Openreview" src="https://img.shields.io/badge/review-OpenReview-blue">
9
+ </a>
10
+ <a href="https://arxiv.org/abs/2410.20626">
11
+ <img alt="Paper URL" src="https://img.shields.io/badge/cs.LG-2410.20626-B31B1B.svg">
12
+ </a>
13
+ </p>
14
+
15
+ <div align="center">
16
+ <img src="images/tabdiff_demo.gif" alt="Model Logo" width="800" style="margin-left:'auto' margin-right:'auto' display:'block'"/>
17
+ <p><em>Figure 1: Visualing the generative process of TabDiff. A high-quality version of this video can be found at <a href="images/tabdiff_demo.mp4" download>tabdiff_demo.mp4</a></em></p>
18
+ </div>
19
+
20
+ This repository provides the official implementation of TabDiff: a Mixed-type Diffusion Model for Tabular Data Generation (ICLR 2025).
21
+
22
+ ## Latest Update
23
+ - [2025.04]:The categorical-heavy dataset **[Diabetes](https://archive.ics.uci.edu/dataset/296/diabetes+130-us+hospitals+for+years+1999-2008)** evaluated in the paper has now been released!
24
+ - [2025.02]:Our code is finally released! We have released part of the tested datasets. The rest will be released soon!
25
+
26
+ ## Introduction
27
+
28
+ <div align="center">
29
+ <img src="images/tabdiff_flowchart.jpg" alt="Model Logo" width="800" style="margin-left:'auto' margin-right:'auto' display:'block'"/>
30
+ <p><em>Figure 2: The high-level schema of TabDiff</a></em></p>
31
+ </div>
32
+ TabDiff is a unified diffusion framework designed to model all muti-modal distributions of tabular data in a single model. Its key innovations include:
33
+
34
+ 1) Framing the joint diffusion process in continuous time,
35
+ 2) A feature-wised learnable diffusion process that offsets the heterogeneity across different feature distributions,
36
+ 3) Classifier-free guidance conditional generation for missing column value imputation.
37
+
38
+ The schema of TabDiff is presented in the figure above. For more details, please refer to [our paper](https://arxiv.org/abs/2410.20626).
39
+
40
+
41
+ ## Environment Setup
42
+
43
+ Create the main environment with [tabdiff.yaml](tabdiff.yaml). This environment will be used for all tasks except for the evaluation of additional data fidelity metrics (i.e., $\alpha$-precision and $\beta$-recall scores)
44
+
45
+ ```
46
+ conda env create -f tabdiff.yaml
47
+ ```
48
+
49
+ Create another environment with [synthcity.yaml](synthcity.yaml) to evaluate additional data fidelity metrics
50
+
51
+ ```
52
+ conda env create -f synthcity.yaml
53
+ ```
54
+
55
+ ## Datasets Preparation
56
+
57
+ ### Using the datasets experimented in the paper
58
+
59
+ Download raw datasets:
60
+
61
+ ```
62
+ python download_dataset.py
63
+ ```
64
+
65
+ Process datasets:
66
+
67
+ ```
68
+ python process_dataset.py
69
+ ```
70
+
71
+ ### Using your own dataset
72
+
73
+ First, create a directory for your dataset in [./data](./data):
74
+ ```
75
+ cd data
76
+ mkdir <NAME_OF_YOUR_DATASET>
77
+ ```
78
+
79
+ Compile your raw tabular data in .csv format. **The first row should be the header** indicating the name of each column, and the remaining rows are records. After finishing these steps, place you data's csv file in the directory you just created and name it as <NAME_OF_YOUR_DATASET>.csv.
80
+
81
+ Then, create <NAME_OF_YOUR_DATASET>.json in [./data/Info](./data/Info). Write this file with the metadata of your dataset, covering the following information:
82
+ ```
83
+ {
84
+ "name": "<NAME_OF_YOUR_DATASET>",
85
+ "task_type": "[NAME_OF_TASK]", # binclass or regression
86
+ "header": "infer",
87
+ "column_names": null,
88
+ "num_col_idx": [LIST], # list of indices of numerical columns
89
+ "cat_col_idx": [LIST], # list of indices of categorical columns
90
+ "target_col_idx": [list], # list of indices of the target columns (for MLE)
91
+ "file_type": "csv",
92
+ "data_path": "data/<NAME_OF_YOUR_DATASET>/<NAME_OF_YOUR_DATASET>.csv"
93
+ "test_path": null,
94
+ }
95
+ ```
96
+
97
+ ### Important Notes When Creating the Info File
98
+ - The MLE evaluation and the imputation task (see later sections for details) assume that one column of your data is the regression or classification target. To enable these tasks, you will need to specify `target_col_idx`. If you don't need to evalute MLE, you can comment out the following line: https://github.com/MinkaiXu/TabDiff/blob/0c4fc3bbfa19046d36c5dce64628df52d5c73d15/tabdiff/main.py#L152
99
+ - The fields `target_col_idx`, `num_col_idx` and `cat_col_idx` must be multually exclusive—no column should appear in more than one of these lists.
100
+ - Set the task_type to "regression" if the target column is numerical, or "binclass" if it is categorical.
101
+
102
+ Finally, run the following command to process your dataset:
103
+ ```
104
+ python process_dataset.py --dataname <NAME_OF_YOUR_DATASET>
105
+ ```
106
+
107
+ ## Training TabDiff
108
+
109
+ To train an unconditional TabDiff model across the entire table, run
110
+
111
+ ```
112
+ python main.py --dataname <NAME_OF_DATASET> --mode train
113
+ ```
114
+
115
+ Current Options of ```<NAME_OF_DATASET>``` are: adult, default, shoppers, magic, beijing, news
116
+
117
+ Wanb logging is enabled by default. To disable it and log locally, add the ```--no_wandb``` flag.
118
+
119
+ To disable the learnable noise schedules, add the ```--non_learnable_schedule```. Please note that in order for the code to test/sample from such model properly, you need to add this flag for all commands below.
120
+
121
+ To specify your own experiment name, which will be used for logging and saving files, add ```--exp_name <your experiment name>```. This flag overwrites the default experiment name (learnable_schedule/non_learnable_schedule), so, similar to ```--non_learnable_schedule```, once added to training, you need to add it to all following commands as well.
122
+
123
+ ## Sampling and Evaluating TabDiff (Density, MLE, C2ST)
124
+
125
+ To sample synthetic tables from trained TabDiff models and evaluate them, run
126
+ ```
127
+ python main.py --dataname <NAME_OF_DATASET> --mode test --report --no_wandb
128
+ ```
129
+
130
+ This will sample 20 synthetic tables randomly. Meanwhile, it will evaluate the density, mle, and c2st scores for each sample and report their average and standard deviation. The results will be printed out in the terminal, and the samples and detailed evaluation results will be placed in ./eval/report_runs/<EXP_NAME>/<NAME_OF_DATASET>/.
131
+
132
+ ## Evaluating on Additional Fidelity Metrics ($\alpha$-precision and $\beta$-recall scores)
133
+ To evaluate TabDiff on the additional fidelity metrics ($\alpha$-precision and $\beta$-recall scores), you need to first make sure that you have already generated some samples by the previous commands. Then, you need to switch to the `synthcity` environment (as the synthcity packet used to compute those metrics conflicts with the main environment), by running
134
+ ```
135
+ conda activate synthcity
136
+ ```
137
+ Then, evaluate the metrics by running
138
+ ```
139
+ python eval/eval_quality.py --dataname <NAME_OF_DATASET>
140
+ ```
141
+
142
+ Similarly, the results will be printed out in the terminal and added to ./eval/report_runs/<EXP_NAME>/<NAME_OF_DATASET>/
143
+
144
+ ## Evaluating Data Privacy (DCR score)
145
+ To evalute the privacy metric DCR score, you first need to retrain all the models, as the metric requires an equal split between the training and testing data (our initial splits employ a 90/10 ratio). To retrain with an equal split, run the training command but append `_dcr` to ```<NAME_OF_DATASET>```
146
+ ```
147
+ python main.py --dataname <NAME_OF_DATASET>_dcr --mode train
148
+ ```
149
+
150
+ Then, test the models on DCR with the same `_dcr` suffix
151
+ ```
152
+ python main.py --dataname <NAME_OF_DATASET>_dcr --mode test --report --no_wandb
153
+ ```
154
+
155
+
156
+
157
+ ## Missing Value Imputation with Classifier-free Guidance (CFG)
158
+ Our current experiments only include imputing the target column. However, our implementation, located at ```sample_impute()``` in [unified_ctime_diffusion.py](./tabdiff/models/unified_ctime_diffusion.py), should support imputing multiple columns with different data types.
159
+
160
+ ### Training Guidance Model
161
+ In order to enable classifier-free guidance (CFG), you need to first train an unconditional guidance model on the target column by running the training command with the `--y_only` flag
162
+ ```
163
+ python main.py --dataname <NAME_OF_DATASET> --mode train --y_only
164
+ ```
165
+
166
+ ### Sampling Imputed Tables
167
+ With the trained guidance model, you can then impute the missing target column by running the testing command with the `--impute` flag
168
+ ```
169
+ python main.py --dataname <NAME_OF_DATASET> --mode test --impute --no_wandb
170
+ ```
171
+ This will, by default, randomly produce 50 imputed tables and save them to ./impute/<NAME_OF_DATASET>/<EXP_NAME>.
172
+
173
+ ### Evaluating Imputation
174
+ You can then evaluate the imputation quality by running
175
+ ```
176
+ python eval_impute.py --dataname <NAME_OF_DATASET>
177
+ ```
178
+
179
+ ## License
180
+
181
+ This work is licensed undeer the MIT License.
182
+
183
+ ## Acknowledgement
184
+ This repo is built upon the previous work TabSyn's [[codebase]](https://github.com/amazon-science/tabsyn). Many thanks to Hengrui!
185
+
186
+ ## Citation
187
+ Please consider citing our work if you find it helpful in your research!
188
+ ```
189
+ @inproceedings{
190
+ shi2025tabdiff,
191
+ title={TabDiff: a Mixed-type Diffusion Model for Tabular Data Generation},
192
+ author={Juntong Shi and Minkai Xu and Harper Hua and Hengrui Zhang and Stefano Ermon and Jure Leskovec},
193
+ booktitle={The Thirteenth International Conference on Learning Representations},
194
+ year={2025},
195
+ url={https://openreview.net/forum?id=swvURjrt8z}
196
+ }
197
+ ```
198
+ ## Contact
199
+ If you encounter any problem, please file an issue on this GitHub repo.
200
+
201
+ If you have any question regarding the paper, please contact Minkai at [minkai@stanford.edu](minkai@stanford.edu) or Juntong at [shisteve@usc.edu](shisteve@usc.edu).
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_runtime/download_dataset.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from urllib import request
3
+ import zipfile
4
+
5
+ DATA_DIR = 'data'
6
+
7
+
8
+ NAME_URL_DICT_UCI = {
9
+ 'adult': 'https://archive.ics.uci.edu/static/public/2/adult.zip',
10
+ 'default': 'https://archive.ics.uci.edu/static/public/350/default+of+credit+card+clients.zip',
11
+ 'magic': 'https://archive.ics.uci.edu/static/public/159/magic+gamma+telescope.zip',
12
+ 'shoppers': 'https://archive.ics.uci.edu/static/public/468/online+shoppers+purchasing+intention+dataset.zip',
13
+ 'beijing': 'https://archive.ics.uci.edu/static/public/381/beijing+pm2+5+data.zip',
14
+ 'news': 'https://archive.ics.uci.edu/static/public/332/online+news+popularity.zip',
15
+ 'news_nocat': 'https://archive.ics.uci.edu/static/public/332/online+news+popularity.zip',
16
+ 'diabetes': 'https://archive.ics.uci.edu/static/public/296/diabetes+130-us+hospitals+for+years+1999-2008.zip',
17
+ 'adult_dcr': 'https://archive.ics.uci.edu/static/public/2/adult.zip',
18
+ 'default_dcr': 'https://archive.ics.uci.edu/static/public/350/default+of+credit+card+clients.zip',
19
+ 'magic_dcr': 'https://archive.ics.uci.edu/static/public/159/magic+gamma+telescope.zip',
20
+ 'shoppers_dcr': 'https://archive.ics.uci.edu/static/public/468/online+shoppers+purchasing+intention+dataset.zip',
21
+ 'beijing_dcr': 'https://archive.ics.uci.edu/static/public/381/beijing+pm2+5+data.zip',
22
+ 'news_dcr': 'https://archive.ics.uci.edu/static/public/332/online+news+popularity.zip',
23
+ 'diabetes_dcr': 'https://archive.ics.uci.edu/static/public/296/diabetes+130-us+hospitals+for+years+1999-2008.zip',
24
+ }
25
+
26
+ def unzip_file(zip_filepath, dest_path):
27
+ with zipfile.ZipFile(zip_filepath, 'r') as zip_ref:
28
+ zip_ref.extractall(dest_path)
29
+
30
+
31
+ def download_from_uci(name):
32
+
33
+ print(f'Start processing dataset {name} from UCI.')
34
+ save_dir = f'{DATA_DIR}/{name}'
35
+ if not os.path.exists(save_dir):
36
+ os.makedirs(save_dir)
37
+
38
+ url = NAME_URL_DICT_UCI[name]
39
+ request.urlretrieve(url, f'{save_dir}/{name}.zip')
40
+ print(f'Finish downloading dataset from {url}, data has been saved to {save_dir}.')
41
+
42
+ unzip_file(f'{save_dir}/{name}.zip', save_dir)
43
+ print(f'Finish unzipping {name}.')
44
+
45
+ else:
46
+ print('Aready downloaded.')
47
+
48
+ if __name__ == '__main__':
49
+ for name in NAME_URL_DICT_UCI.keys():
50
+ download_from_uci(name)
51
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_runtime/eval_impute.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ from sklearn.preprocessing import OneHotEncoder
4
+ from sklearn.metrics import f1_score, roc_auc_score
5
+ from sklearn.metrics import root_mean_squared_error
6
+ import argparse
7
+ import json
8
+
9
+
10
+ parser = argparse.ArgumentParser(description='Missing Value Imputation')
11
+
12
+ parser.add_argument('--dataname', type=str, default='adult', help='Name of dataset.')
13
+ parser.add_argument('--exp_name', type=str, default=None)
14
+ parser.add_argument('--col', type=int, default=0, help='Numerical Column to Impute')
15
+ parser.add_argument('--non_learnable_schedule', action='store_true')
16
+
17
+ args = parser.parse_args()
18
+
19
+ dataname = args.dataname
20
+ exp_name = args.exp_name
21
+ if exp_name is None:
22
+ exp_name = "non_learnable_schedule" if args.non_learnable_schedule else "learnable_schedule"
23
+ col = args.col
24
+
25
+ dataname = args.dataname
26
+
27
+ data_dir = f'data/{dataname}'
28
+
29
+ real_path = f'{data_dir}/test.csv'
30
+
31
+ info_path = f'data/{dataname}/info.json'
32
+ with open(info_path, 'r') as f:
33
+ info = json.load(f)
34
+ task_type = info['task_type']
35
+
36
+
37
+ encoder = OneHotEncoder()
38
+
39
+ real_data = pd.read_csv(real_path)
40
+ target_col = real_data.columns[info['target_col_idx'][0]]
41
+
42
+ if task_type == "binclass":
43
+ real_target = real_data[target_col].to_numpy().reshape(-1,1)
44
+ real_y = encoder.fit_transform(real_target).toarray()
45
+
46
+ syn_y = []
47
+ for i in range(50):
48
+ syn_path = f'impute/{dataname}/{exp_name}/{i}.csv'
49
+ syn_data = pd.read_csv(syn_path)
50
+ target = syn_data[target_col].to_numpy().reshape(-1, 1)
51
+ syn_y.append(encoder.transform(target).toarray())
52
+
53
+ syn_y_prob = np.stack(syn_y).mean(0)
54
+ syn_y_oh = np.argmax(syn_y_prob, axis=1)
55
+ num_classes = np.max(syn_y_oh) + 1
56
+ syn_y_oh = np.eye(num_classes)[syn_y_oh]
57
+
58
+
59
+
60
+
61
+ micro_f1 = f1_score(real_y.argmax(axis=1), syn_y_prob.argmax(axis=1), average='micro')
62
+ auc = roc_auc_score(real_y, syn_y_prob, average='micro')
63
+ auc_argmaxed = roc_auc_score(real_y, syn_y_oh, average='micro')
64
+ print("AUC: ", round(auc*100, 3))
65
+ else:
66
+ y_test = real_data[target_col].to_numpy()
67
+ y_test = np.log(np.clip(y_test, 1, 20000))
68
+
69
+ syn_y_ = []
70
+ error = []
71
+ for i in range(50):
72
+ syn_path = f'impute/{dataname}/{exp_name}/{i}.csv'
73
+ syn_data = pd.read_csv(syn_path)
74
+ syn_y = syn_data[target_col].to_numpy()
75
+ syn_y = np.log(np.clip(syn_y, 1, 20000))
76
+ syn_y_.append(syn_y)
77
+
78
+ pred = np.stack(syn_y_).mean(0)
79
+ root_mean_squared = root_mean_squared_error(y_test, pred) # mean_squared_error with squared=False is deprecated
80
+
81
+ print("RMSE:", round(root_mean_squared, 4))
82
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_runtime/images/tabdiff_demo.gif ADDED

Git LFS Details

  • SHA256: 8b3f9c4819c4ef4abf8ade862da25915b826212f3d3ef9e4774ddde19db88bf2
  • Pointer size: 132 Bytes
  • Size of remote file: 3.26 MB
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_runtime/images/tabdiff_demo.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:90c8072ab9a7dcc73d7bc3ea32b0e961cae5fcd7d73b6ffc2ffb44e6c291962f
3
+ size 1108599
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_runtime/images/tabdiff_flowchart.jpg ADDED

Git LFS Details

  • SHA256: 34e4115e21b32199dd6cc0a0664f924907fcf1f66e2063616c50025f597b7409
  • Pointer size: 131 Bytes
  • Size of remote file: 383 kB
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_runtime/main.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from tabdiff.main import main as tabdiff_main
3
+ import argparse
4
+
5
+ if __name__ == '__main__':
6
+ parser = argparse.ArgumentParser(description='Training of TabDiff')
7
+
8
+ # General configs
9
+ parser.add_argument('--dataname', type=str, default='adult', help='Name dataset, one of those in data/ dir')
10
+ parser.add_argument('--mode', type=str, default='train', help='train or test')
11
+ parser.add_argument('--method', type=str, default='tabdiff', help='Currently we only release our model TabDiff. Baselines will be released soon.')
12
+ parser.add_argument('--gpu', type=int, default=0, help='GPU index')
13
+ parser.add_argument('--debug', action='store_true', help='Enable debug mode')
14
+ parser.add_argument('--no_wandb', action='store_true', help='disable wandb')
15
+ parser.add_argument('--exp_name', type=str, default=None, help='Experiment name, used to name log directories and the wandb run name')
16
+ parser.add_argument('--deterministic', action='store_true', help='Whether to make the entire process deterministic, i.e., fix global random seeds')
17
+
18
+ # Configs for tabdiff
19
+ parser.add_argument('--y_only', action='store_true', help='Train guidance model that only model the target column')
20
+ parser.add_argument('--non_learnable_schedule', action='store_true', help='disable learnable noise schedule')
21
+
22
+ # Configs for testing tabdiff
23
+ parser.add_argument('--num_samples_to_generate', type=int, default=None, help='Number of samples to be generated while testing')
24
+ parser.add_argument('--ckpt_path', type=str, default=None, help='Path to the model checkpoint to be tested')
25
+ parser.add_argument('--report', action='store_true', help="Report testing mode: this mode sequentially runs <num_runs> test runs and report the avg and std")
26
+ parser.add_argument('--num_runs', type=int, default=20, help="Number of runs to be averaged in the report testing mode")
27
+
28
+ # Configs for imputation
29
+ parser.add_argument('--impute', action='store_true')
30
+ parser.add_argument('--trial_start', type=int, default=0)
31
+ parser.add_argument('--trial_size', type=int, default=50)
32
+ parser.add_argument('--resample_rounds', type=int, default=1)
33
+ parser.add_argument('--impute_condition', type=str, default="x_t")
34
+ parser.add_argument('--y_only_model_path', type=str, default=None, help="Path to the y_only model checkpoint that will be used as the unconditional guidance model")
35
+ parser.add_argument('--w_num', type=float, default=0.6)
36
+ parser.add_argument('--w_cat', type=float, default=0.6)
37
+
38
+ args = parser.parse_args()
39
+
40
+ # check cuda
41
+ if args.gpu != -1 and torch.cuda.is_available():
42
+ args.device = f'cuda:{args.gpu}'
43
+ else:
44
+ args.device = 'cpu'
45
+
46
+ tabdiff_main(args)
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_runtime/process_dataset.py ADDED
@@ -0,0 +1,646 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ import os
4
+ import sys
5
+ import json
6
+ import argparse
7
+
8
+ from sklearn.preprocessing import OrdinalEncoder
9
+ from sklearn import model_selection
10
+
11
+ TYPE_TRANSFORM ={
12
+ 'float', np.float32,
13
+ 'str', str,
14
+ 'int', int
15
+ }
16
+
17
+ INFO_PATH = 'data/Info'
18
+
19
+ parser = argparse.ArgumentParser(description='process dataset')
20
+
21
+ # General configs
22
+ parser.add_argument('--dataname', type=str, default=None, help='Name of dataset.')
23
+ args = parser.parse_args()
24
+
25
+ def preprocess_beijing():
26
+ with open(f'{INFO_PATH}/beijing.json', 'r') as f:
27
+ info = json.load(f)
28
+
29
+ data_path = info['raw_data_path']
30
+
31
+ data_df = pd.read_csv(data_path)
32
+ columns = data_df.columns
33
+
34
+ data_df = data_df[columns[1:]]
35
+
36
+
37
+ df_cleaned = data_df.dropna()
38
+ df_cleaned.to_csv(info['data_path'], index = False)
39
+
40
+ def preprocess_beijing_dcr():
41
+ with open(f'{INFO_PATH}/beijing_dcr.json', 'r') as f:
42
+ info = json.load(f)
43
+
44
+ data_path = info['raw_data_path']
45
+
46
+ data_df = pd.read_csv(data_path)
47
+ columns = data_df.columns
48
+
49
+ data_df = data_df[columns[1:]]
50
+
51
+
52
+ df_cleaned = data_df.dropna()
53
+ df_cleaned.to_csv(info['data_path'], index = False)
54
+
55
+ def preprocess_news(remove_cat=False):
56
+ name = 'news' if not remove_cat else 'news_nocat'
57
+ with open(f'{INFO_PATH}/{name}.json', 'r') as f:
58
+ info = json.load(f)
59
+
60
+ data_path = info['raw_data_path']
61
+ data_df = pd.read_csv(data_path)
62
+ data_df = data_df.drop('url', axis=1)
63
+
64
+ columns = np.array(data_df.columns.tolist())
65
+
66
+ cat_columns1 = columns[list(range(12,18))]
67
+ cat_columns2 = columns[list(range(30,38))]
68
+
69
+ if not remove_cat:
70
+ cat_col1 = data_df[cat_columns1].astype(int).to_numpy().argmax(axis = 1)
71
+ cat_col2 = data_df[cat_columns2].astype(int).to_numpy().argmax(axis = 1)
72
+
73
+ data_df = data_df.drop(cat_columns2, axis=1)
74
+ data_df = data_df.drop(cat_columns1, axis=1)
75
+
76
+ if not remove_cat:
77
+ data_df['data_channel'] = cat_col1
78
+ data_df['weekday'] = cat_col2
79
+
80
+ data_save_path = f'data/{name}/{name}.csv'
81
+ data_df.to_csv(f'{data_save_path}', index = False)
82
+
83
+ columns = np.array(data_df.columns.tolist())
84
+ num_columns = columns[list(range(45))]
85
+ cat_columns = ['data_channel', 'weekday'] if not remove_cat else []
86
+ target_columns = columns[[45]]
87
+
88
+ info['num_col_idx'] = list(range(45))
89
+ info['cat_col_idx'] = [46, 47] if not remove_cat else []
90
+ info['target_col_idx'] = [45]
91
+ info['data_path'] = data_save_path
92
+
93
+ with open(f'{INFO_PATH}/{name}.json', 'w') as file:
94
+ json.dump(info, file, indent=4)
95
+
96
+ def preprocess_news_dcr(remove_cat=False):
97
+ name = 'news_dcr' if not remove_cat else 'news_nocat_dcr'
98
+ with open(f'{INFO_PATH}/{name}.json', 'r') as f:
99
+ info = json.load(f)
100
+
101
+ data_path = info['raw_data_path']
102
+ data_df = pd.read_csv(data_path)
103
+ data_df = data_df.drop('url', axis=1)
104
+
105
+ columns = np.array(data_df.columns.tolist())
106
+
107
+ cat_columns1 = columns[list(range(12,18))]
108
+ cat_columns2 = columns[list(range(30,38))]
109
+
110
+ if not remove_cat:
111
+ cat_col1 = data_df[cat_columns1].astype(int).to_numpy().argmax(axis = 1)
112
+ cat_col2 = data_df[cat_columns2].astype(int).to_numpy().argmax(axis = 1)
113
+
114
+ data_df = data_df.drop(cat_columns2, axis=1)
115
+ data_df = data_df.drop(cat_columns1, axis=1)
116
+
117
+ if not remove_cat:
118
+ data_df['data_channel'] = cat_col1
119
+ data_df['weekday'] = cat_col2
120
+
121
+ data_save_path = f'data/{name}/{name}.csv'
122
+ data_df.to_csv(f'{data_save_path}', index = False)
123
+
124
+ columns = np.array(data_df.columns.tolist())
125
+ num_columns = columns[list(range(45))]
126
+ cat_columns = ['data_channel', 'weekday'] if not remove_cat else []
127
+ target_columns = columns[[45]]
128
+
129
+ info['num_col_idx'] = list(range(45))
130
+ info['cat_col_idx'] = [46, 47] if not remove_cat else []
131
+ info['target_col_idx'] = [45]
132
+ info['data_path'] = data_save_path
133
+
134
+ with open(f'{INFO_PATH}/{name}.json', 'w') as file:
135
+ json.dump(info, file, indent=4)
136
+
137
+ def preprocess_diabetes():
138
+ """
139
+ Preprocesses the diabetes dataset is aligned with the concurrent work
140
+ Continuous Diffusion for Mixed-Type Tabular Data (CDTD):
141
+ https://github.com/muellermarkus/cdtd
142
+ """
143
+ with open(f'{INFO_PATH}/diabetes.json', 'r') as f:
144
+ info = json.load(f)
145
+
146
+ info['num_col_idx'] = list(range(9))
147
+ info['cat_col_idx'] = list(range(9, 36))
148
+ info['target_col_idx'] = [36]
149
+
150
+ data_path = info['raw_data_path']
151
+ df = pd.read_csv(data_path, sep=',')
152
+ df = df[info['column_names']]
153
+ df = df.replace(r' ', np.nan)
154
+ df = df.replace(r'?', np.nan)
155
+ df = df.replace(r'', np.nan)
156
+
157
+ num_features = [info['column_names'][idx] for idx in info['num_col_idx']]
158
+ cat_features = [info['column_names'][idx] for idx in info['cat_col_idx']]
159
+ target = info['column_names'][info['target_col_idx'][0]]
160
+ df[target] = np.where(df[target] == 'NO', 0, 1)
161
+ enc = OrdinalEncoder()
162
+ df['age'] = enc.fit_transform(df['age'].to_numpy().reshape(-1,1))
163
+
164
+ # remove rows with missings in targets
165
+ idx_target_nan = df[target].isna().to_numpy().nonzero()[0]
166
+ df.drop(labels = idx_target_nan, axis = 0, inplace = True)
167
+
168
+ # for categorical features, replace missings with 'empty', which will be counted as a new category
169
+ df[cat_features] = df[cat_features].fillna('empty')
170
+
171
+ # for continuous data, drop missing
172
+ df.dropna(inplace = True)
173
+
174
+ # ensure correct types
175
+ X_cat = df[cat_features].to_numpy().astype('str')
176
+ X_cont = df[num_features].to_numpy().astype('float')
177
+ y = df[[target]].to_numpy()
178
+
179
+ val_prop, test_prop = 0.2, 0.2
180
+ prop = val_prop / (1 - test_prop)
181
+
182
+ stratify = None if info['task_type'] == 'regression' else y
183
+ X_cat_train, X_cat_test, X_cont_train, X_cont_test, y_train, y_test = \
184
+ model_selection.train_test_split(X_cat, X_cont, y, test_size = test_prop,
185
+ stratify = stratify, random_state = 42)
186
+ if val_prop > 0:
187
+ stratify = None if info['task_type'] == 'regression' else y_train
188
+ X_cat_train, X_cat_val, X_cont_train, X_cont_val, y_train, y_val = \
189
+ model_selection.train_test_split(X_cat_train, X_cont_train, y_train,
190
+ stratify = stratify, test_size = prop,
191
+ random_state = 42)
192
+
193
+ train_df = pd.DataFrame(np.concatenate([X_cont_train, X_cat_train, y_train], axis = 1), columns = num_features + cat_features + [target])
194
+ val_df = pd.DataFrame(np.concatenate([X_cont_val, X_cat_val, y_val], axis = 1), columns = num_features + cat_features + [target])
195
+ test_df = pd.DataFrame(np.concatenate([X_cont_test, X_cat_test, y_test], axis = 1), columns = num_features + cat_features + [target])
196
+
197
+ # Save the splited data
198
+ train_df.to_csv(info['data_path'], index = False)
199
+ val_df.to_csv(info['val_path'], index = False)
200
+ test_df.to_csv(info['test_path'], index = False)
201
+ # Save updated info
202
+ with open(f'{INFO_PATH}/diabetes.json', 'w') as file:
203
+ json.dump(info, file, indent=4)
204
+
205
+ def preprocess_diabetes_dcr():
206
+ """
207
+ Preprocesses the diabetes dataset is aligned with the concurrent work
208
+ Continuous Diffusion for Mixed-Type Tabular Data (CDTD):
209
+ https://github.com/muellermarkus/cdtd
210
+ """
211
+ with open(f'{INFO_PATH}/diabetes_dcr.json', 'r') as f:
212
+ info = json.load(f)
213
+
214
+ info['num_col_idx'] = list(range(9))
215
+ info['cat_col_idx'] = list(range(9, 36))
216
+ info['target_col_idx'] = [36]
217
+
218
+ data_path = info['raw_data_path']
219
+ df = pd.read_csv(data_path, sep=',')
220
+ df = df[info['column_names']]
221
+ df = df.replace(r' ', np.nan)
222
+ df = df.replace(r'?', np.nan)
223
+ df = df.replace(r'', np.nan)
224
+
225
+ num_features = [info['column_names'][idx] for idx in info['num_col_idx']]
226
+ cat_features = [info['column_names'][idx] for idx in info['cat_col_idx']]
227
+ target = info['column_names'][info['target_col_idx'][0]]
228
+ df[target] = np.where(df[target] == 'NO', 0, 1)
229
+ enc = OrdinalEncoder()
230
+ df['age'] = enc.fit_transform(df['age'].to_numpy().reshape(-1,1))
231
+
232
+ # remove rows with missings in targets
233
+ idx_target_nan = df[target].isna().to_numpy().nonzero()[0]
234
+ df.drop(labels = idx_target_nan, axis = 0, inplace = True)
235
+
236
+ # for categorical features, replace missings with 'empty', which will be counted as a new category
237
+ df[cat_features] = df[cat_features].fillna('empty')
238
+
239
+ # for continuous data, drop missing
240
+ df.dropna(inplace = True)
241
+
242
+ # ensure correct types
243
+ X_cat = df[cat_features].to_numpy().astype('str')
244
+ X_cont = df[num_features].to_numpy().astype('float')
245
+ y = df[[target]].to_numpy()
246
+
247
+ val_prop, test_prop = 0.0, 0.5 # 50-50 split for dcr eval
248
+ prop = val_prop / (1 - test_prop)
249
+
250
+ stratify = None if info['task_type'] == 'regression' else y
251
+ X_cat_train, X_cat_test, X_cont_train, X_cont_test, y_train, y_test = \
252
+ model_selection.train_test_split(X_cat, X_cont, y, test_size = test_prop,
253
+ stratify = stratify, random_state = 42)
254
+ if val_prop > 0:
255
+ stratify = None if info['task_type'] == 'regression' else y_train
256
+ X_cat_train, X_cat_val, X_cont_train, X_cont_val, y_train, y_val = \
257
+ model_selection.train_test_split(X_cat_train, X_cont_train, y_train,
258
+ stratify = stratify, test_size = prop,
259
+ random_state = 42)
260
+
261
+ train_df = pd.DataFrame(np.concatenate([X_cont_train, X_cat_train, y_train], axis = 1), columns = num_features + cat_features + [target])
262
+ if val_prop > 0:
263
+ val_df = pd.DataFrame(np.concatenate([X_cont_val, X_cat_val, y_val], axis = 1), columns = num_features + cat_features + [target])
264
+ else:
265
+ val_df = pd.DataFrame(columns = num_features + cat_features + [target]).astype(train_df.dtypes)
266
+ test_df = pd.DataFrame(np.concatenate([X_cont_test, X_cat_test, y_test], axis = 1), columns = num_features + cat_features + [target])
267
+
268
+ # Save the splited data
269
+ train_df.to_csv(info['data_path'], index = False)
270
+ val_df.to_csv(info['val_path'], index = False)
271
+ test_df.to_csv(info['test_path'], index = False)
272
+ # Save updated info
273
+ with open(f'{INFO_PATH}/diabetes_dcr.json', 'w') as file:
274
+ json.dump(info, file, indent=4)
275
+
276
+
277
+
278
+ def get_column_name_mapping(data_df, num_col_idx, cat_col_idx, target_col_idx, column_names = None):
279
+
280
+ if not column_names:
281
+ column_names = np.array(data_df.columns.tolist())
282
+
283
+
284
+ idx_mapping = {}
285
+
286
+ curr_num_idx = 0
287
+ curr_cat_idx = len(num_col_idx)
288
+ curr_target_idx = curr_cat_idx + len(cat_col_idx)
289
+
290
+ for idx in range(len(column_names)):
291
+
292
+ if idx in num_col_idx:
293
+ idx_mapping[int(idx)] = curr_num_idx
294
+ curr_num_idx += 1
295
+ elif idx in cat_col_idx:
296
+ idx_mapping[int(idx)] = curr_cat_idx
297
+ curr_cat_idx += 1
298
+ else:
299
+ idx_mapping[int(idx)] = curr_target_idx
300
+ curr_target_idx += 1
301
+
302
+
303
+ inverse_idx_mapping = {}
304
+ for k, v in idx_mapping.items():
305
+ inverse_idx_mapping[int(v)] = k
306
+
307
+ idx_name_mapping = {}
308
+
309
+ for i in range(len(column_names)):
310
+ idx_name_mapping[int(i)] = column_names[i]
311
+
312
+ return idx_mapping, inverse_idx_mapping, idx_name_mapping
313
+
314
+
315
+ def train_val_test_split(data_df, cat_columns, num_train = 0, num_test = 0):
316
+ total_num = data_df.shape[0]
317
+ idx = np.arange(total_num)
318
+
319
+
320
+ seed = 1234
321
+
322
+ while True:
323
+ np.random.seed(seed)
324
+ np.random.shuffle(idx)
325
+
326
+ train_idx = idx[:num_train]
327
+ test_idx = idx[-num_test:]
328
+
329
+
330
+ train_df = data_df.loc[train_idx]
331
+ test_df = data_df.loc[test_idx]
332
+
333
+
334
+
335
+ flag = 0
336
+ for i in cat_columns:
337
+ if len(set(train_df[i])) != len(set(data_df[i])):
338
+ flag = 1
339
+ break
340
+
341
+ if flag == 0:
342
+ break
343
+ else:
344
+ seed += 1
345
+
346
+ return train_df, test_df, seed
347
+
348
+
349
+ def process_data(name):
350
+
351
+ if name == 'news':
352
+ preprocess_news()
353
+ elif name == 'news_nocat':
354
+ preprocess_news(remove_cat=True)
355
+ elif name == 'news_dcr':
356
+ preprocess_news_dcr()
357
+ elif name == 'beijing':
358
+ preprocess_beijing()
359
+ elif name == 'beijing_dcr':
360
+ preprocess_beijing_dcr()
361
+ elif name == 'diabetes':
362
+ preprocess_diabetes()
363
+ elif name == 'diabetes_dcr':
364
+ preprocess_diabetes_dcr()
365
+
366
+ with open(f'{INFO_PATH}/{name}.json', 'r') as f:
367
+ info = json.load(f)
368
+
369
+ data_path = info['data_path']
370
+ if info['file_type'] == 'csv':
371
+ data_df = pd.read_csv(data_path, header = info['header'])
372
+
373
+ elif info['file_type'] == 'xls':
374
+ data_df = pd.read_excel(data_path, sheet_name='Data', header=1)
375
+ data_df = data_df.drop('ID', axis=1)
376
+
377
+ num_data = data_df.shape[0]
378
+
379
+ column_names = info['column_names'] if info['column_names'] else data_df.columns.tolist()
380
+
381
+ num_col_idx = info['num_col_idx']
382
+ cat_col_idx = info['cat_col_idx']
383
+ target_col_idx = info['target_col_idx']
384
+
385
+ num_columns = [column_names[i] for i in num_col_idx]
386
+ cat_columns = [column_names[i] for i in cat_col_idx]
387
+ target_columns = [column_names[i] for i in target_col_idx]
388
+
389
+ idx_mapping, inverse_idx_mapping, idx_name_mapping = get_column_name_mapping(data_df, num_col_idx, cat_col_idx, target_col_idx, column_names)
390
+
391
+ has_val = bool(info['val_path'])
392
+ val_df = pd.DataFrame(columns=data_df.columns).astype(data_df.dtypes) # by default (val_path is not provided), set val_Df to be empty
393
+ if info['test_path']:
394
+
395
+ # if testing data is given
396
+ test_path = info['test_path']
397
+
398
+ if "adult" in name: # BUG: currently data saved at adult's test_path cannot be directly loaded. Consider integrate the following code to a preprocesing function for adult
399
+ with open(test_path, 'r') as f:
400
+ lines = f.readlines()[1:]
401
+ test_save_path = f'data/{name}/test.data'
402
+ if not os.path.exists(test_save_path):
403
+ with open(test_save_path, 'a') as f1:
404
+ for line in lines:
405
+ save_line = line.strip('\n').strip('.')
406
+ f1.write(f'{save_line}\n')
407
+
408
+ test_df = pd.read_csv(test_save_path, header = None)
409
+ else:
410
+ test_df = pd.read_csv(test_path, header = info['header'])
411
+
412
+ if has_val: # currently you cannot have a val path without a test path
413
+ val_path = info['val_path']
414
+ val_df = pd.read_csv(val_path, header = info['header'])
415
+
416
+ train_df = data_df
417
+
418
+ if "dcr" in name and "diabetes" not in name: # create 50/50 splits for dcr datasets; no need for this for diabetes dataset as it's done in preprocessing
419
+ complete_df = pd.concat([train_df, test_df, val_df], axis = 0, ignore_index=True)
420
+ num_data = complete_df.shape[0]
421
+ num_train = int(num_data*0.5)
422
+ num_test = num_data - num_train
423
+ complete_df.rename(columns = idx_name_mapping, inplace=True)
424
+ train_df, test_df, seed = train_val_test_split(complete_df, cat_columns, num_train, num_test)
425
+
426
+ else:
427
+ # Train/ Test Split, 90% Training (50% for dcr eval exclusively), 10% Testing (Validation set will be selected from Training set)
428
+ if "dcr" in name:
429
+ num_train = int(num_data*0.5)
430
+ else:
431
+ num_train = int(num_data*0.9)
432
+ num_test = num_data - num_train
433
+
434
+ train_df, test_df, seed = train_val_test_split(data_df, cat_columns, num_train, num_test)
435
+
436
+ complete_df = pd.concat([train_df, test_df, val_df], axis = 0)
437
+ name_idx_mapping = {val: key for key, val in idx_name_mapping.items()}
438
+ int_columns = []
439
+ int_col_idx = []
440
+ int_col_idx_wrt_num = []
441
+ for i, col_idx in enumerate(num_col_idx):
442
+ col = column_names[col_idx]
443
+ col_data = complete_df.iloc[:,col_idx]
444
+ is_int = (col_data%1 == 0).all()
445
+ if is_int:
446
+ int_columns.append(col)
447
+ int_col_idx.append(name_idx_mapping[col])
448
+ int_col_idx_wrt_num.append(i)
449
+ info['int_col_idx'] = int_col_idx
450
+ info['int_columns'] = int_columns
451
+ info['int_col_idx_wrt_num'] = int_col_idx_wrt_num
452
+
453
+ train_df.columns = range(len(train_df.columns))
454
+ test_df.columns = range(len(test_df.columns))
455
+ val_df.columns = range(len(val_df.columns))
456
+
457
+ print(name, train_df.shape, val_df.shape, test_df.shape, data_df.shape)
458
+
459
+ col_info = {}
460
+
461
+ for col_idx in num_col_idx:
462
+ col_info[col_idx] = {}
463
+ col_info['type'] = 'numerical'
464
+ col_info['max'] = float(train_df[col_idx].max())
465
+ col_info['min'] = float(train_df[col_idx].min())
466
+
467
+ for col_idx in cat_col_idx:
468
+ col_info[col_idx] = {}
469
+ col_info['type'] = 'categorical'
470
+ col_info['categorizes'] = list(set(train_df[col_idx]))
471
+
472
+ for col_idx in target_col_idx:
473
+ if info['task_type'] == 'regression':
474
+ col_info[col_idx] = {}
475
+ col_info['type'] = 'numerical'
476
+ col_info['max'] = float(train_df[col_idx].max())
477
+ col_info['min'] = float(train_df[col_idx].min())
478
+ else:
479
+ col_info[col_idx] = {}
480
+ col_info['type'] = 'categorical'
481
+ col_info['categorizes'] = list(set(train_df[col_idx]))
482
+
483
+ info['column_info'] = col_info
484
+
485
+ train_df.rename(columns = idx_name_mapping, inplace=True)
486
+ test_df.rename(columns = idx_name_mapping, inplace=True)
487
+ val_df.rename(columns = idx_name_mapping, inplace=True)
488
+
489
+ for col in num_columns:
490
+ if (train_df[col] == ' ?').sum() > 0:
491
+ print(col)
492
+ import pdb; pdb.set_trace()
493
+ if (train_df[col] == '?').sum() > 0:
494
+ print(col)
495
+ import pdb; pdb.set_trace()
496
+ train_df.loc[train_df[col] == '?', col] = np.nan
497
+ for col in cat_columns:
498
+ train_df.loc[train_df[col] == '?', col] = 'nan'
499
+ for col in num_columns:
500
+ if (test_df[col] == ' ?').sum() > 0:
501
+ print(col)
502
+ import pdb; pdb.set_trace()
503
+ if (test_df[col] == '?').sum() > 0:
504
+ print(col)
505
+ import pdb; pdb.set_trace()
506
+ test_df.loc[test_df[col] == '?', col] = np.nan
507
+ for col in cat_columns:
508
+ test_df.loc[test_df[col] == '?', col] = 'nan'
509
+ for col in num_columns:
510
+ val_df.loc[val_df[col] == '?', col] = np.nan
511
+ for col in cat_columns:
512
+ val_df.loc[val_df[col] == '?', col] = 'nan'
513
+
514
+ if train_df.isna().any().any():
515
+ print("Training data contains nan in the numerical cols")
516
+ import pdb; pdb.set_trace()
517
+
518
+
519
+
520
+ X_num_train = train_df[num_columns].to_numpy().astype(np.float32)
521
+ X_cat_train = train_df[cat_columns].to_numpy()
522
+ y_train = train_df[target_columns].to_numpy()
523
+
524
+
525
+ X_num_test = test_df[num_columns].to_numpy().astype(np.float32)
526
+ X_cat_test = test_df[cat_columns].to_numpy()
527
+ y_test = test_df[target_columns].to_numpy()
528
+
529
+ X_num_val = val_df[num_columns].to_numpy().astype(np.float32)
530
+ X_cat_val = val_df[cat_columns].to_numpy()
531
+ y_val = val_df[target_columns].to_numpy()
532
+
533
+ save_dir = f'data/{name}'
534
+ np.save(f'{save_dir}/X_num_train.npy', X_num_train)
535
+ np.save(f'{save_dir}/X_cat_train.npy', X_cat_train)
536
+ np.save(f'{save_dir}/y_train.npy', y_train)
537
+
538
+ np.save(f'{save_dir}/X_num_test.npy', X_num_test)
539
+ np.save(f'{save_dir}/X_cat_test.npy', X_cat_test)
540
+ np.save(f'{save_dir}/y_test.npy', y_test)
541
+
542
+ if has_val:
543
+ np.save(f'{save_dir}/X_num_val.npy', X_num_val)
544
+ np.save(f'{save_dir}/X_cat_val.npy', X_cat_val)
545
+ np.save(f'{save_dir}/y_val.npy', y_val)
546
+
547
+ train_df[num_columns] = train_df[num_columns].astype(np.float32)
548
+ test_df[num_columns] = test_df[num_columns].astype(np.float32)
549
+ val_df[num_columns] = val_df[num_columns].astype(np.float32)
550
+
551
+
552
+ train_df.to_csv(f'{save_dir}/train.csv', index = False)
553
+ test_df.to_csv(f'{save_dir}/test.csv', index = False)
554
+ if has_val:
555
+ val_df.to_csv(f'{save_dir}/val.csv', index = False)
556
+
557
+ if not os.path.exists(f'synthetic/{name}'):
558
+ os.makedirs(f'synthetic/{name}')
559
+
560
+ train_df.to_csv(f'synthetic/{name}/real.csv', index = False)
561
+ test_df.to_csv(f'synthetic/{name}/test.csv', index = False)
562
+
563
+ if has_val:
564
+ val_df.to_csv(f'synthetic/{name}/val.csv', index = False)
565
+
566
+ print('Numerical', X_num_train.shape)
567
+ print('Categorical', X_cat_train.shape)
568
+
569
+ info['column_names'] = column_names
570
+ info['train_num'] = train_df.shape[0]
571
+ info['test_num'] = test_df.shape[0]
572
+ info['val_num'] = val_df.shape[0]
573
+
574
+ info['idx_mapping'] = idx_mapping
575
+ info['inverse_idx_mapping'] = inverse_idx_mapping
576
+ info['idx_name_mapping'] = idx_name_mapping
577
+
578
+ metadata = {'columns': {}}
579
+ task_type = info['task_type']
580
+ num_col_idx = info['num_col_idx']
581
+ cat_col_idx = info['cat_col_idx']
582
+ target_col_idx = info['target_col_idx']
583
+
584
+ for i in num_col_idx:
585
+ metadata['columns'][i] = {}
586
+ metadata['columns'][i]['sdtype'] = 'numerical'
587
+ metadata['columns'][i]['computer_representation'] = 'Float'
588
+
589
+ for i in cat_col_idx:
590
+ metadata['columns'][i] = {}
591
+ metadata['columns'][i]['sdtype'] = 'categorical'
592
+
593
+
594
+ if task_type == 'regression':
595
+
596
+ for i in target_col_idx:
597
+ metadata['columns'][i] = {}
598
+ metadata['columns'][i]['sdtype'] = 'numerical'
599
+ metadata['columns'][i]['computer_representation'] = 'Float'
600
+
601
+ else:
602
+ for i in target_col_idx:
603
+ metadata['columns'][i] = {}
604
+ metadata['columns'][i]['sdtype'] = 'categorical'
605
+
606
+ info['metadata'] = metadata
607
+
608
+ with open(f'{save_dir}/info.json', 'w') as file:
609
+ json.dump(info, file, indent=4)
610
+
611
+ print(f'Processing and Saving {name} Successfully!')
612
+
613
+ print(name)
614
+ print('Total', info['train_num'] + info['test_num'])
615
+ print('Train', info['train_num'])
616
+ print('Val', info['val_num'])
617
+ print('Test', info['test_num'])
618
+ if info['task_type'] == 'regression':
619
+ num = len(info['num_col_idx'] + info['target_col_idx'])
620
+ cat = len(info['cat_col_idx'])
621
+ else:
622
+ cat = len(info['cat_col_idx'] + info['target_col_idx'])
623
+ num = len(info['num_col_idx'])
624
+ print('Num', num)
625
+ print('Int', len(info['int_col_idx']))
626
+ print('Cat', cat)
627
+
628
+
629
+ if __name__ == "__main__":
630
+
631
+ if args.dataname:
632
+ process_data(args.dataname)
633
+ else:
634
+ for name in [
635
+ 'adult', 'default', 'shoppers', 'magic', 'beijing', 'news', 'news_nocat', 'diabetes',
636
+ 'adult_dcr',
637
+ 'default_dcr',
638
+ 'shoppers_dcr',
639
+ 'beijing_dcr',
640
+ 'news_dcr',
641
+ 'diabetes_dcr'
642
+ ]:
643
+ process_data(name)
644
+
645
+
646
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_runtime/src/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from icecream import install
3
+
4
+ torch.set_num_threads(1)
5
+ install()
6
+
7
+ from . import env # noqa
8
+ from .data import * # noqa
9
+ from .env import * # noqa
10
+ from .metrics import * # noqa
11
+ from .util import * # noqa
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_runtime/src/data.py ADDED
@@ -0,0 +1,780 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ from collections import Counter
3
+ from copy import deepcopy
4
+ from dataclasses import astuple, dataclass, replace
5
+ from importlib.resources import path
6
+ from pathlib import Path
7
+ from typing import Any, Literal, Optional, Union, cast, Tuple, Dict, List
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+ from sklearn.model_selection import train_test_split
12
+ from sklearn.pipeline import make_pipeline
13
+ import sklearn.preprocessing
14
+ import torch
15
+ import os
16
+ from category_encoders import LeaveOneOutEncoder
17
+ from sklearn.impute import SimpleImputer
18
+ from sklearn.preprocessing import StandardScaler
19
+ from scipy.spatial.distance import cdist
20
+
21
+ from . import env, util
22
+ from .metrics import calculate_metrics as calculate_metrics_
23
+ from .util import TaskType, load_json
24
+
25
+ ArrayDict = Dict[str, np.ndarray]
26
+ TensorDict = Dict[str, torch.Tensor]
27
+
28
+
29
+ CAT_MISSING_VALUE = 'nan'
30
+ CAT_RARE_VALUE = '__rare__'
31
+ Normalization = Literal['standard', 'quantile', 'minmax']
32
+ NumNanPolicy = Literal['drop-rows', 'mean']
33
+ CatNanPolicy = Literal['most_frequent']
34
+ CatEncoding = Literal['one-hot', 'counter']
35
+ YPolicy = Literal['default']
36
+ DEQUANT_DIST = Literal['uniform', 'beta', 'round', 'none']
37
+
38
+
39
+ class StandardScaler1d(StandardScaler):
40
+ def partial_fit(self, X, *args, **kwargs):
41
+ assert X.ndim == 1
42
+ return super().partial_fit(X[:, None], *args, **kwargs)
43
+
44
+ def transform(self, X, *args, **kwargs):
45
+ assert X.ndim == 1
46
+ return super().transform(X[:, None], *args, **kwargs).squeeze(1)
47
+
48
+ def inverse_transform(self, X, *args, **kwargs):
49
+ assert X.ndim == 1
50
+ return super().inverse_transform(X[:, None], *args, **kwargs).squeeze(1)
51
+
52
+
53
+ def get_category_sizes(X: Union[torch.Tensor, np.ndarray]) -> List[int]:
54
+ XT = X.T.cpu().tolist() if isinstance(X, torch.Tensor) else X.T.tolist()
55
+ return [len(set(x)) for x in XT]
56
+
57
+
58
+ @dataclass(frozen=False)
59
+ class Dataset:
60
+ X_num: Optional[ArrayDict]
61
+ X_cat: Optional[ArrayDict]
62
+ y: ArrayDict
63
+ int_col_idx_wrt_num: list
64
+ y_info: Dict[str, Any]
65
+ task_type: TaskType
66
+ n_classes: Optional[int]
67
+
68
+ @classmethod
69
+ def from_dir(cls, dir_: Union[Path, str]) -> 'Dataset':
70
+ dir_ = Path(dir_)
71
+ splits = [k for k in ['train', 'test'] if dir_.joinpath(f'y_{k}.npy').exists()]
72
+
73
+ def load(item) -> ArrayDict:
74
+ return {
75
+ x: cast(np.ndarray, np.load(dir_ / f'{item}_{x}.npy', allow_pickle=True)) # type: ignore[code]
76
+ for x in splits
77
+ }
78
+
79
+ if Path(dir_ / 'info.json').exists():
80
+ info = util.load_json(dir_ / 'info.json')
81
+ else:
82
+ info = None
83
+ return Dataset(
84
+ load('X_num') if dir_.joinpath('X_num_train.npy').exists() else None,
85
+ load('X_cat') if dir_.joinpath('X_cat_train.npy').exists() else None,
86
+ load('y'),
87
+ {},
88
+ TaskType(info['task_type']),
89
+ info.get('n_classes'),
90
+ )
91
+
92
+ @property
93
+ def is_binclass(self) -> bool:
94
+ return self.task_type == TaskType.BINCLASS
95
+
96
+ @property
97
+ def is_multiclass(self) -> bool:
98
+ return self.task_type == TaskType.MULTICLASS
99
+
100
+ @property
101
+ def is_regression(self) -> bool:
102
+ return self.task_type == TaskType.REGRESSION
103
+
104
+ @property
105
+ def n_num_features(self) -> int:
106
+ return 0 if self.X_num is None else self.X_num['train'].shape[1]
107
+
108
+ @property
109
+ def n_cat_features(self) -> int:
110
+ return 0 if self.X_cat is None else self.X_cat['train'].shape[1]
111
+
112
+ @property
113
+ def n_features(self) -> int:
114
+ return self.n_num_features + self.n_cat_features
115
+
116
+ def size(self, part: Optional[str]) -> int:
117
+ return sum(map(len, self.y.values())) if part is None else len(self.y[part])
118
+
119
+ @property
120
+ def nn_output_dim(self) -> int:
121
+ if self.is_multiclass:
122
+ assert self.n_classes is not None
123
+ return self.n_classes
124
+ else:
125
+ return 1
126
+
127
+ def get_category_sizes(self, part: str) -> List[int]:
128
+ return [] if self.X_cat is None else get_category_sizes(self.X_cat[part])
129
+
130
+ def calculate_metrics(
131
+ self,
132
+ predictions: Dict[str, np.ndarray],
133
+ prediction_type: Optional[str],
134
+ ) -> Dict[str, Any]:
135
+ metrics = {
136
+ x: calculate_metrics_(
137
+ self.y[x], predictions[x], self.task_type, prediction_type, self.y_info
138
+ )
139
+ for x in predictions
140
+ }
141
+ if self.task_type == TaskType.REGRESSION:
142
+ score_key = 'rmse'
143
+ score_sign = -1
144
+ else:
145
+ score_key = 'accuracy'
146
+ score_sign = 1
147
+ for part_metrics in metrics.values():
148
+ part_metrics['score'] = score_sign * part_metrics[score_key]
149
+ return metrics
150
+
151
+ def change_val(dataset: Dataset, val_size: float = 0.2):
152
+ # should be done before transformations
153
+
154
+ y = np.concatenate([dataset.y['train'], dataset.y['val']], axis=0)
155
+
156
+ ixs = np.arange(y.shape[0])
157
+ if dataset.is_regression:
158
+ train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777)
159
+ else:
160
+ train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777, stratify=y)
161
+
162
+ dataset.y['train'] = y[train_ixs]
163
+ dataset.y['val'] = y[val_ixs]
164
+
165
+ if dataset.X_num is not None:
166
+ X_num = np.concatenate([dataset.X_num['train'], dataset.X_num['val']], axis=0)
167
+ dataset.X_num['train'] = X_num[train_ixs]
168
+ dataset.X_num['val'] = X_num[val_ixs]
169
+
170
+ if dataset.X_cat is not None:
171
+ X_cat = np.concatenate([dataset.X_cat['train'], dataset.X_cat['val']], axis=0)
172
+ dataset.X_cat['train'] = X_cat[train_ixs]
173
+ dataset.X_cat['val'] = X_cat[val_ixs]
174
+
175
+ return dataset
176
+
177
+ def num_process_nans(dataset: Dataset, policy: Optional[NumNanPolicy]) -> Dataset:
178
+
179
+ assert dataset.X_num is not None
180
+ nan_masks = {k: np.isnan(v) for k, v in dataset.X_num.items()}
181
+ if not any(x.any() for x in nan_masks.values()): # type: ignore[code]
182
+ # assert policy is None
183
+ print('No NaNs in numerical features, skipping')
184
+ return dataset
185
+
186
+ assert policy is not None
187
+ if policy == 'drop-rows':
188
+ valid_masks = {k: ~v.any(1) for k, v in nan_masks.items()}
189
+ assert valid_masks[
190
+ 'test'
191
+ ].all(), 'Cannot drop test rows, since this will affect the final metrics.'
192
+ new_data = {}
193
+ for data_name in ['X_num', 'X_cat', 'y']:
194
+ data_dict = getattr(dataset, data_name)
195
+ if data_dict is not None:
196
+ new_data[data_name] = {
197
+ k: v[valid_masks[k]] for k, v in data_dict.items()
198
+ }
199
+ dataset = replace(dataset, **new_data)
200
+ elif policy == 'mean':
201
+ new_values = np.nanmean(dataset.X_num['train'], axis=0)
202
+ X_num = deepcopy(dataset.X_num)
203
+ for k, v in X_num.items():
204
+ num_nan_indices = np.where(nan_masks[k])
205
+ v[num_nan_indices] = np.take(new_values, num_nan_indices[1])
206
+ dataset = replace(dataset, X_num=X_num)
207
+ else:
208
+ assert util.raise_unknown('policy', policy)
209
+ return dataset
210
+
211
+
212
+ # Inspired by: https://github.com/yandex-research/rtdl/blob/a4c93a32b334ef55d2a0559a4407c8306ffeeaee/lib/data.py#L20
213
+ def normalize(
214
+ X: ArrayDict, normalization: Normalization, seed: Optional[int], return_normalizer : bool = False
215
+ ) -> ArrayDict:
216
+ X_train = X['train']
217
+ if normalization == 'standard':
218
+ normalizer = sklearn.preprocessing.StandardScaler()
219
+ elif normalization == 'minmax':
220
+ normalizer = sklearn.preprocessing.MinMaxScaler()
221
+ elif normalization == 'quantile':
222
+ normalizer = sklearn.preprocessing.QuantileTransformer(
223
+ output_distribution='normal',
224
+ n_quantiles=max(min(X['train'].shape[0] // 30, 1000), 10),
225
+ subsample=int(1e9),
226
+ random_state=seed,
227
+ )
228
+ # noise = 1e-3
229
+ # if noise > 0:
230
+ # assert seed is not None
231
+ # stds = np.std(X_train, axis=0, keepdims=True)
232
+ # noise_std = noise / np.maximum(stds, noise) # type: ignore[code]
233
+ # X_train = X_train + noise_std * np.random.default_rng(seed).standard_normal(
234
+ # X_train.shape
235
+ # )
236
+ else:
237
+ util.raise_unknown('normalization', normalization)
238
+
239
+ normalizer.fit(X_train)
240
+ if return_normalizer:
241
+ return {k: normalizer.transform(v) for k, v in X.items()}, normalizer
242
+ return {k: normalizer.transform(v) for k, v in X.items()}
243
+
244
+ class dequantizer:
245
+ def __init__(
246
+ self,
247
+ dequant_dist: DEQUANT_DIST,
248
+ int_col_idx_wrt_num: list,
249
+ int_dequant_factor: float,
250
+ # return_dequantizer: bool = False
251
+ ):
252
+ self.dequant_dist = dequant_dist
253
+ self.int_col_idx_wrt_num = int_col_idx_wrt_num
254
+ self.int_dequant_factor = int_dequant_factor
255
+ def transform(self, X):
256
+ X_int = X[:, self.int_col_idx_wrt_num]
257
+ if self.dequant_dist == 'uniform':
258
+ X[:, self.int_col_idx_wrt_num] = X_int+ np.random.uniform(size=X_int.shape) * self.int_dequant_factor
259
+ elif self.dequant_dist == 'beta':
260
+ X[:, self.int_col_idx_wrt_num] = X_int + np.random.beta(self.int_dequant_factor, self.int_dequant_factor, size=X_int.shape) - 0.5
261
+ elif self.dequant_dist in ['round', 'none']:
262
+ pass
263
+ return X
264
+ def inverse_transform(self, X):
265
+ X_int = X[:, self.int_col_idx_wrt_num]
266
+ if self.dequant_dist == 'uniform':
267
+ X[:, self.int_col_idx_wrt_num] = np.floor(X_int)
268
+ elif self.dequant_dist == 'beta':
269
+ X[:, self.int_col_idx_wrt_num] = np.rint(X_int)
270
+ elif self.dequant_dist == 'round':
271
+ X[:, self.int_col_idx_wrt_num] = np.rint(X_int)
272
+ elif self.dequant_dist == 'none':
273
+ pass
274
+ return X
275
+
276
+
277
+ # if return_dequantizer:
278
+ # return {k: transform(v) for k, v in X.items()}, inverse_transform
279
+ # return {k: transform(v) for k, v in X.items()}
280
+
281
+ def cat_process_nans(X: ArrayDict, policy: Optional[CatNanPolicy]) -> ArrayDict:
282
+ assert X is not None
283
+ nan_masks = {k: v == CAT_MISSING_VALUE for k, v in X.items()}
284
+ if any(x.any() for x in nan_masks.values()): # type: ignore[code]
285
+ if policy is None:
286
+ X_new = X
287
+ elif policy == 'most_frequent':
288
+ imputer = SimpleImputer(missing_values=CAT_MISSING_VALUE, strategy=policy) # type: ignore[code]
289
+ imputer.fit(X['train'])
290
+ X_new = {k: cast(np.ndarray, imputer.transform(v)) for k, v in X.items()}
291
+ else:
292
+ util.raise_unknown('categorical NaN policy', policy)
293
+ else:
294
+ assert policy is None
295
+ X_new = X
296
+ return X_new
297
+
298
+
299
+ def cat_drop_rare(X: ArrayDict, min_frequency: float) -> ArrayDict:
300
+ assert 0.0 < min_frequency < 1.0
301
+ min_count = round(len(X['train']) * min_frequency)
302
+ X_new = {x: [] for x in X}
303
+ for column_idx in range(X['train'].shape[1]):
304
+ counter = Counter(X['train'][:, column_idx].tolist())
305
+ popular_categories = {k for k, v in counter.items() if v >= min_count}
306
+ for part in X_new:
307
+ X_new[part].append(
308
+ [
309
+ (x if x in popular_categories else CAT_RARE_VALUE)
310
+ for x in X[part][:, column_idx].tolist()
311
+ ]
312
+ )
313
+ return {k: np.array(v).T for k, v in X_new.items()}
314
+
315
+
316
+ def cat_encode(
317
+ X: ArrayDict,
318
+ encoding: Optional[CatEncoding],
319
+ y_train: Optional[np.ndarray],
320
+ seed: Optional[int],
321
+ return_encoder : bool = False
322
+ ) -> Tuple[ArrayDict, bool, Optional[Any]]: # (X, is_converted_to_numerical)
323
+ if encoding != 'counter':
324
+ y_train = None
325
+
326
+ # Step 1. Map strings to 0-based ranges
327
+
328
+ if encoding is None:
329
+ unknown_value = np.iinfo('int64').max - 3
330
+ oe = sklearn.preprocessing.OrdinalEncoder(
331
+ handle_unknown='use_encoded_value', # type: ignore[code]
332
+ unknown_value=unknown_value, # type: ignore[code]
333
+ dtype='int64', # type: ignore[code]
334
+ ).fit(X['train'])
335
+ encoder = make_pipeline(oe)
336
+ encoder.fit(X['train'])
337
+ X = {k: encoder.transform(v) for k, v in X.items()}
338
+ max_values = X['train'].max(axis=0)
339
+ for part in X.keys():
340
+ if part == 'train': continue
341
+ for column_idx in range(X[part].shape[1]):
342
+ X[part][X[part][:, column_idx] == unknown_value, column_idx] = (
343
+ max_values[column_idx] + 1
344
+ )
345
+ if return_encoder:
346
+ return (X, False, encoder)
347
+ return (X, False)
348
+
349
+ # Step 2. Encode.
350
+
351
+ elif encoding == 'one-hot':
352
+ ohe = sklearn.preprocessing.OneHotEncoder(
353
+ handle_unknown='ignore', sparse_output=False, dtype=np.float32 # type: ignore[code]
354
+ )
355
+ encoder = make_pipeline(ohe)
356
+
357
+ # encoder.steps.append(('ohe', ohe))
358
+ encoder.fit(X['train'])
359
+ X = {k: encoder.transform(v) for k, v in X.items()}
360
+
361
+ elif encoding == 'counter':
362
+ assert y_train is not None
363
+ assert seed is not None
364
+ loe = LeaveOneOutEncoder(sigma=0.1, random_state=seed, return_df=False)
365
+ encoder.steps.append(('loe', loe))
366
+ encoder.fit(X['train'], y_train)
367
+ X = {k: encoder.transform(v).astype('float32') for k, v in X.items()} # type: ignore[code]
368
+ if not isinstance(X['train'], pd.DataFrame):
369
+ X = {k: v.values for k, v in X.items()} # type: ignore[code]
370
+ else:
371
+ util.raise_unknown('encoding', encoding)
372
+
373
+ if return_encoder:
374
+ return X, True, encoder # type: ignore[code]
375
+ return (X, True)
376
+
377
+
378
+ def build_target(
379
+ y: ArrayDict, policy: Optional[YPolicy], task_type: TaskType
380
+ ) -> Tuple[ArrayDict, Dict[str, Any]]:
381
+ info: Dict[str, Any] = {'policy': policy}
382
+ if policy is None:
383
+ pass
384
+ elif policy == 'default':
385
+ if task_type == TaskType.REGRESSION:
386
+ mean, std = float(y['train'].mean()), float(y['train'].std())
387
+ y = {k: (v - mean) / std for k, v in y.items()}
388
+ info['mean'] = mean
389
+ info['std'] = std
390
+ else:
391
+ util.raise_unknown('policy', policy)
392
+ return y, info
393
+
394
+
395
+ @dataclass(frozen=True)
396
+ class Transformations:
397
+ seed: int = 0
398
+ normalization: Optional[Normalization] = None
399
+ num_nan_policy: Optional[NumNanPolicy] = None
400
+ cat_nan_policy: Optional[CatNanPolicy] = None
401
+ cat_min_frequency: Optional[float] = None
402
+ cat_encoding: Optional[CatEncoding] = None
403
+ y_policy: Optional[YPolicy] = 'default'
404
+ dequant_dist: Optional[DEQUANT_DIST] = None
405
+ int_dequant_factor: Optional[float] = 0.0
406
+
407
+
408
+ def transform_dataset(
409
+ dataset: Dataset,
410
+ transformations: Transformations,
411
+ cache_dir: Optional[Path],
412
+ return_transforms: bool = False
413
+ ) -> Dataset:
414
+ # WARNING: the order of transformations matters. Moreover, the current
415
+ # implementation is not ideal in that sense.
416
+ if cache_dir is not None:
417
+ transformations_md5 = hashlib.md5(
418
+ str(transformations).encode('utf-8')
419
+ ).hexdigest()
420
+ transformations_str = '__'.join(map(str, astuple(transformations)))
421
+ cache_path = (
422
+ cache_dir / f'cache__{transformations_str}__{transformations_md5}.pickle'
423
+ )
424
+ if cache_path.exists():
425
+ cache_transformations, value = util.load_pickle(cache_path)
426
+ if transformations == cache_transformations:
427
+ print(
428
+ f"Using cached features: {cache_dir.name + '/' + cache_path.name}"
429
+ )
430
+ return value
431
+ else:
432
+ raise RuntimeError(f'Hash collision for {cache_path}')
433
+ else:
434
+ cache_path = None
435
+
436
+ if dataset.X_num is not None:
437
+ dataset = num_process_nans(dataset, transformations.num_nan_policy)
438
+
439
+ num_transform = None
440
+ int_transform = None
441
+ cat_transform = None
442
+ X_num = dataset.X_num
443
+
444
+ int_col_idx_wrt_num = dataset.int_col_idx_wrt_num
445
+ if X_num is not None and int_col_idx_wrt_num and transformations.dequant_dist is not None:
446
+ int_transform = dequantizer(
447
+ transformations.dequant_dist,
448
+ int_col_idx_wrt_num,
449
+ transformations.int_dequant_factor,
450
+ )
451
+ X_num = {k: int_transform.transform(v) for k, v in X_num.items()}
452
+
453
+ if X_num is not None and transformations.normalization is not None:
454
+ has_num = all([x.shape[1]>0 for x in dataset.X_num.values()])
455
+ if has_num:
456
+ X_num, num_transform = normalize(
457
+ X_num,
458
+ transformations.normalization,
459
+ transformations.seed,
460
+ return_normalizer=True
461
+ )
462
+ num_transform = num_transform
463
+
464
+ if dataset.X_cat is None:
465
+ assert transformations.cat_nan_policy is None
466
+ assert transformations.cat_min_frequency is None
467
+ # assert transformations.cat_encoding is None
468
+ X_cat = None
469
+ else:
470
+ has_cat = all([x.shape[1]>0 for x in dataset.X_cat.values()])
471
+ if not has_cat:
472
+ assert transformations.cat_nan_policy is None
473
+ assert transformations.cat_min_frequency is None
474
+ X_cat = dataset.X_cat
475
+ for split in X_cat.keys(): # a patch to make sure that the empty array is transformed into int dtype
476
+ X_cat[split] = X_cat[split].astype(np.int64)
477
+ else:
478
+ X_cat = cat_process_nans(dataset.X_cat, transformations.cat_nan_policy)
479
+
480
+ if transformations.cat_min_frequency is not None:
481
+ X_cat = cat_drop_rare(X_cat, transformations.cat_min_frequency)
482
+ X_cat, is_num, cat_transform = cat_encode(
483
+ X_cat,
484
+ transformations.cat_encoding,
485
+ dataset.y['train'],
486
+ transformations.seed,
487
+ return_encoder=True
488
+ )
489
+
490
+ if is_num:
491
+ X_num = (
492
+ X_cat
493
+ if X_num is None
494
+ else {x: np.hstack([X_num[x], X_cat[x]]) for x in X_num}
495
+ )
496
+ X_cat = None
497
+
498
+
499
+ y, y_info = build_target(dataset.y, transformations.y_policy, dataset.task_type)
500
+
501
+ dataset = replace(dataset, X_num=X_num, X_cat=X_cat, y=y, y_info=y_info)
502
+ dataset.num_transform = num_transform
503
+ dataset.int_transform = int_transform
504
+ dataset.cat_transform = cat_transform
505
+
506
+ if cache_path is not None:
507
+ util.dump_pickle((transformations, dataset), cache_path)
508
+ # if return_transforms:
509
+ # return dataset, num_transform, cat_transform
510
+ return dataset
511
+
512
+
513
+ def build_dataset(
514
+ path: Union[str, Path],
515
+ transformations: Transformations,
516
+ cache: bool
517
+ ) -> Dataset:
518
+ path = Path(path)
519
+ dataset = Dataset.from_dir(path)
520
+ return transform_dataset(dataset, transformations, path if cache else None)
521
+
522
+
523
+ def prepare_tensors(
524
+ dataset: Dataset, device: Union[str, torch.device]
525
+ ) -> Tuple[Optional[TensorDict], Optional[TensorDict], TensorDict]:
526
+ X_num, X_cat, Y = (
527
+ None if x is None else {k: torch.as_tensor(v) for k, v in x.items()}
528
+ for x in [dataset.X_num, dataset.X_cat, dataset.y]
529
+ )
530
+ if device.type != 'cpu':
531
+ X_num, X_cat, Y = (
532
+ None if x is None else {k: v.to(device) for k, v in x.items()}
533
+ for x in [X_num, X_cat, Y]
534
+ )
535
+ assert X_num is not None
536
+ assert Y is not None
537
+ if not dataset.is_multiclass:
538
+ Y = {k: v.float() for k, v in Y.items()}
539
+ return X_num, X_cat, Y
540
+
541
+ ###############
542
+ ## DataLoader##
543
+ ###############
544
+
545
+ class TabDataset(torch.utils.data.Dataset):
546
+ def __init__(
547
+ self, dataset : Dataset, split : Literal['train', 'val', 'test']
548
+ ):
549
+ super().__init__()
550
+
551
+ self.X_num = torch.from_numpy(dataset.X_num[split]) if dataset.X_num is not None else None
552
+ self.X_cat = torch.from_numpy(dataset.X_cat[split]) if dataset.X_cat is not None else None
553
+ self.y = torch.from_numpy(dataset.y[split])
554
+
555
+ assert self.y is not None
556
+ assert self.X_num is not None or self.X_cat is not None
557
+
558
+ def __len__(self):
559
+ return len(self.y)
560
+
561
+ def __getitem__(self, idx):
562
+ out_dict = {
563
+ 'y': self.y[idx].long() if self.y is not None else None,
564
+ }
565
+
566
+ x = np.empty((0,))
567
+ if self.X_num is not None:
568
+ x = self.X_num[idx]
569
+ if self.X_cat is not None:
570
+ x = torch.cat([x, self.X_cat[idx]], dim=0)
571
+ return x.float(), out_dict
572
+
573
+ def prepare_dataloader(
574
+ dataset : Dataset,
575
+ split : str,
576
+ batch_size: int,
577
+ ):
578
+
579
+ torch_dataset = TabDataset(dataset, split)
580
+ loader = torch.utils.data.DataLoader(
581
+ torch_dataset,
582
+ batch_size=batch_size,
583
+ shuffle=(split == 'train'),
584
+ num_workers=int(os.environ.get('TABDIFF_NUM_WORKERS', '0')),
585
+ )
586
+ while True:
587
+ yield from loader
588
+
589
+ def prepare_torch_dataloader(
590
+ dataset : Dataset,
591
+ split : str,
592
+ shuffle : bool,
593
+ batch_size: int,
594
+ ) -> torch.utils.data.DataLoader:
595
+
596
+ torch_dataset = TabDataset(dataset, split)
597
+ loader = torch.utils.data.DataLoader(torch_dataset, batch_size=batch_size, shuffle=shuffle, num_workers=int(os.environ.get('TABDIFF_NUM_WORKERS', '0')))
598
+
599
+ return loader
600
+
601
+ def dataset_from_csv(paths : Dict[str, str], cat_features, target, T):
602
+ assert 'train' in paths
603
+ y = {}
604
+ X_num = {}
605
+ X_cat = {} if len(cat_features) else None
606
+ for split in paths.keys():
607
+ df = pd.read_csv(paths[split])
608
+ y[split] = df[target].to_numpy().astype(float)
609
+ if X_cat is not None:
610
+ X_cat[split] = df[cat_features].to_numpy().astype(str)
611
+ X_num[split] = df.drop(cat_features + [target], axis=1).to_numpy().astype(float)
612
+
613
+ dataset = Dataset(X_num, X_cat, y, {}, None, len(np.unique(y['train'])))
614
+ return transform_dataset(dataset, T, None)
615
+
616
+ class FastTensorDataLoader:
617
+ """
618
+ A DataLoader-like object for a set of tensors that can be much faster than
619
+ TensorDataset + DataLoader because dataloader grabs individual indices of
620
+ the dataset and calls cat (slow).
621
+ Source: https://discuss.pytorch.org/t/dataloader-much-slower-than-manual-batching/27014/6
622
+ """
623
+ def __init__(self, *tensors, batch_size=32, shuffle=False):
624
+ """
625
+ Initialize a FastTensorDataLoader.
626
+ :param *tensors: tensors to store. Must have the same length @ dim 0.
627
+ :param batch_size: batch size to load.
628
+ :param shuffle: if True, shuffle the data *in-place* whenever an
629
+ iterator is created out of this object.
630
+ :returns: A FastTensorDataLoader.
631
+ """
632
+ assert all(t.shape[0] == tensors[0].shape[0] for t in tensors)
633
+ self.tensors = tensors
634
+
635
+ self.dataset_len = self.tensors[0].shape[0]
636
+ self.batch_size = batch_size
637
+ self.shuffle = shuffle
638
+
639
+ # Calculate # batches
640
+ n_batches, remainder = divmod(self.dataset_len, self.batch_size)
641
+ if remainder > 0:
642
+ n_batches += 1
643
+ self.n_batches = n_batches
644
+ def __iter__(self):
645
+ if self.shuffle:
646
+ r = torch.randperm(self.dataset_len)
647
+ self.tensors = [t[r] for t in self.tensors]
648
+ self.i = 0
649
+ return self
650
+
651
+ def __next__(self):
652
+ if self.i >= self.dataset_len:
653
+ raise StopIteration
654
+ batch = tuple(t[self.i:self.i+self.batch_size] for t in self.tensors)
655
+ self.i += self.batch_size
656
+ return batch
657
+
658
+ def __len__(self):
659
+ return self.n_batches
660
+
661
+ def prepare_fast_dataloader(
662
+ D : Dataset,
663
+ split : str,
664
+ batch_size: int
665
+ ):
666
+
667
+ X = torch.from_numpy(np.concatenate([D.X_num[split], D.X_cat[split]], axis=1)).float()
668
+ dataloader = FastTensorDataLoader(X, batch_size=batch_size, shuffle=(split=='train'))
669
+ while True:
670
+ yield from dataloader
671
+
672
+ def prepare_fast_torch_dataloader(
673
+ D : Dataset,
674
+ split : str,
675
+ batch_size: int
676
+ ):
677
+ if D.X_cat is not None:
678
+ X = torch.from_numpy(np.concatenate([D.X_num[split], D.X_cat[split]], axis=1)).float()
679
+ else:
680
+ X = torch.from_numpy(D.X_num[split]).float()
681
+ y = torch.from_numpy(D.y[split])
682
+ dataloader = FastTensorDataLoader(X, y, batch_size=batch_size, shuffle=(split=='train'))
683
+ return dataloader
684
+
685
+ def round_columns(X_real, X_synth, columns):
686
+ for col in columns:
687
+ uniq = np.unique(X_real[:,col])
688
+ dist = cdist(X_synth[:, col][:, np.newaxis].astype(float), uniq[:, np.newaxis].astype(float))
689
+ X_synth[:, col] = uniq[dist.argmin(axis=1)]
690
+ return X_synth
691
+
692
+ def concat_features(D : Dataset):
693
+ if D.X_num is None:
694
+ assert D.X_cat is not None
695
+ X = {k: pd.DataFrame(v, columns=range(D.n_features)) for k, v in D.X_cat.items()}
696
+ elif D.X_cat is None:
697
+ assert D.X_num is not None
698
+ X = {k: pd.DataFrame(v, columns=range(D.n_features)) for k, v in D.X_num.items()}
699
+ else:
700
+ X = {
701
+ part: pd.concat(
702
+ [
703
+ pd.DataFrame(D.X_num[part], columns=range(D.n_num_features)),
704
+ pd.DataFrame(
705
+ D.X_cat[part],
706
+ columns=range(D.n_num_features, D.n_features),
707
+ ),
708
+ ],
709
+ axis=1,
710
+ )
711
+ for part in D.y.keys()
712
+ }
713
+
714
+ return X
715
+
716
+ def concat_to_pd(X_num, X_cat, y):
717
+ if X_num is None:
718
+ return pd.concat([
719
+ pd.DataFrame(X_cat, columns=list(range(X_cat.shape[1]))),
720
+ pd.DataFrame(y, columns=['y'])
721
+ ], axis=1)
722
+ if X_cat is not None:
723
+ return pd.concat([
724
+ pd.DataFrame(X_num, columns=list(range(X_num.shape[1]))),
725
+ pd.DataFrame(X_cat, columns=list(range(X_num.shape[1], X_num.shape[1] + X_cat.shape[1]))),
726
+ pd.DataFrame(y, columns=['y'])
727
+ ], axis=1)
728
+ return pd.concat([
729
+ pd.DataFrame(X_num, columns=list(range(X_num.shape[1]))),
730
+ pd.DataFrame(y, columns=['y'])
731
+ ], axis=1)
732
+
733
+ def read_pure_data(path, split='train'):
734
+ y = np.load(os.path.join(path, f'y_{split}.npy'), allow_pickle=True)
735
+ X_num = None
736
+ X_cat = None
737
+ if os.path.exists(os.path.join(path, f'X_num_{split}.npy')):
738
+ X_num = np.load(os.path.join(path, f'X_num_{split}.npy'), allow_pickle=True)
739
+ if os.path.exists(os.path.join(path, f'X_cat_{split}.npy')):
740
+ X_cat = np.load(os.path.join(path, f'X_cat_{split}.npy'), allow_pickle=True)
741
+
742
+ return X_num, X_cat, y
743
+
744
+ def read_changed_val(path, val_size=0.2):
745
+ path = Path(path)
746
+ X_num_train, X_cat_train, y_train = read_pure_data(path, 'train')
747
+ X_num_val, X_cat_val, y_val = read_pure_data(path, 'val')
748
+ is_regression = load_json(path / 'info.json')['task_type'] == 'regression'
749
+
750
+ y = np.concatenate([y_train, y_val], axis=0)
751
+
752
+ ixs = np.arange(y.shape[0])
753
+ if is_regression:
754
+ train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777)
755
+ else:
756
+ train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777, stratify=y)
757
+ y_train = y[train_ixs]
758
+ y_val = y[val_ixs]
759
+
760
+ if X_num_train is not None:
761
+ X_num = np.concatenate([X_num_train, X_num_val], axis=0)
762
+ X_num_train = X_num[train_ixs]
763
+ X_num_val = X_num[val_ixs]
764
+
765
+ if X_cat_train is not None:
766
+ X_cat = np.concatenate([X_cat_train, X_cat_val], axis=0)
767
+ X_cat_train = X_cat[train_ixs]
768
+ X_cat_val = X_cat[val_ixs]
769
+
770
+ return X_num_train, X_cat_train, y_train, X_num_val, X_cat_val, y_val
771
+
772
+ #############
773
+
774
+ def load_dataset_info(dataset_dir_name: str) -> Dict[str, Any]:
775
+ path = Path("data/" + dataset_dir_name)
776
+ info = util.load_json(path / 'info.json')
777
+ info['size'] = info['train_size'] + info['val_size'] + info['test_size']
778
+ info['n_features'] = info['n_num_features'] + info['n_cat_features']
779
+ info['path'] = path
780
+ return info
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_040854/_tabdiff_runtime/src/env.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Have not used in TabDDPM project.
3
+ """
4
+
5
+ import datetime
6
+ import os
7
+ import shutil
8
+ import typing as ty
9
+ from pathlib import Path
10
+
11
+ PROJ = Path('tab-ddpm/').absolute().resolve()
12
+ EXP = PROJ / 'exp'
13
+ DATA = PROJ / 'data'
14
+
15
+
16
+ def get_path(path: ty.Union[str, Path]) -> Path:
17
+ if isinstance(path, str):
18
+ path = Path(path)
19
+ if not path.is_absolute():
20
+ path = PROJ / path
21
+ return path.resolve()
22
+
23
+
24
+ def get_relative_path(path: ty.Union[str, Path]) -> Path:
25
+ return get_path(path).relative_to(PROJ)
26
+
27
+
28
+ def duplicate_path(
29
+ src: ty.Union[str, Path], alternative_project_dir: ty.Union[str, Path]
30
+ ) -> None:
31
+ src = get_path(src)
32
+ alternative_project_dir = get_path(alternative_project_dir)
33
+ dst = alternative_project_dir / src.relative_to(PROJ)
34
+ dst.parent.mkdir(parents=True, exist_ok=True)
35
+ if dst.exists():
36
+ dst = dst.with_name(
37
+ dst.name + '_' + datetime.datetime.now().strftime('%Y%m%dT%H%M%S')
38
+ )
39
+ (shutil.copytree if src.is_dir() else shutil.copyfile)(src, dst)