Resume SynthData0523 hyper_parameter_tuning/n11/tabdiff batch 4
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +66 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_tabdiff_runtime/src/__init__.py +11 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_tabdiff_runtime/src/data.py +780 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_tabdiff_runtime/src/env.py +39 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_tabdiff_runtime/src/metrics.py +157 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_tabdiff_runtime/src/util.py +347 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_tabdiff_runtime/synthcity.yaml +11 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_tabdiff_runtime/tabdiff.yaml +35 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_tabdiff_runtime/tabdiff/configs/tabdiff_configs.toml +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_tabdiff_runtime/tabdiff/main.py +344 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_tabdiff_runtime/tabdiff/metrics.py +306 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_tabdiff_runtime/tabdiff/models/noise_schedule.py +157 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_tabdiff_runtime/tabdiff/models/unified_ctime_diffusion.py +597 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_tabdiff_runtime/tabdiff/modules/main_modules.py +167 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_tabdiff_runtime/tabdiff/modules/transformer.py +258 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_tabdiff_runtime/tabdiff/trainer.py +657 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_tabdiff_runtime/utils_train.py +198 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_tabdiff_train.py +78 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/bo_combo.json +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/gen_20260521_053144.log +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/input_snapshot.json +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/models_tabdiff/trained.pt +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/public_gate/normalized_schema_snapshot.json +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/public_gate/public_gate_report.json +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/public_gate/staged_input_manifest.json +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/run_config.json +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/runtime_result.json +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/staged/public/staged_features.json +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/staged/public/test.csv +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/staged/public/train.csv +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/staged/public/val.csv +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/staged/tabdiff/adapter_report.json +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/staged/tabdiff/adapter_transforms_applied.json +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/staged/tabdiff/model_input_manifest.json +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/tabdiff-n11-15215-20260521_053144.csv +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/tabdiff_train_meta.json +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/tabular_bundle/pipeline_n11/X_num_test.npy +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/tabular_bundle/pipeline_n11/X_num_train.npy +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/tabular_bundle/pipeline_n11/X_num_val.npy +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/tabular_bundle/pipeline_n11/info.json +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/tabular_bundle/pipeline_n11/real.csv +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/tabular_bundle/pipeline_n11/staged_features.json +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/tabular_bundle/pipeline_n11/test.csv +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/tabular_bundle/pipeline_n11/train.csv +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/tabular_bundle/pipeline_n11/val.csv +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/tabular_bundle/pipeline_n11/y_test.npy +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/tabular_bundle/pipeline_n11/y_train.npy +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/tabular_bundle/pipeline_n11/y_val.npy +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/train_20260521_051643.log +3 -0
- SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/_tabdiff_gen.py +42 -0
.gitattributes
CHANGED
|
@@ -18065,3 +18065,69 @@ SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_04595
|
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 18068 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_tabdiff_runtime/tabdiff/configs/tabdiff_configs.toml filter=lfs diff=lfs merge=lfs -text
|
| 18069 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/bo_combo.json filter=lfs diff=lfs merge=lfs -text
|
| 18070 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/gen_20260521_053144.log filter=lfs diff=lfs merge=lfs -text
|
| 18071 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/input_snapshot.json filter=lfs diff=lfs merge=lfs -text
|
| 18072 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/models_tabdiff/trained.pt filter=lfs diff=lfs merge=lfs -text
|
| 18073 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/public_gate/normalized_schema_snapshot.json filter=lfs diff=lfs merge=lfs -text
|
| 18074 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/public_gate/public_gate_report.json filter=lfs diff=lfs merge=lfs -text
|
| 18075 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/public_gate/staged_input_manifest.json filter=lfs diff=lfs merge=lfs -text
|
| 18076 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/run_config.json filter=lfs diff=lfs merge=lfs -text
|
| 18077 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/runtime_result.json filter=lfs diff=lfs merge=lfs -text
|
| 18078 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/staged/public/staged_features.json filter=lfs diff=lfs merge=lfs -text
|
| 18079 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/staged/public/test.csv filter=lfs diff=lfs merge=lfs -text
|
| 18080 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/staged/public/train.csv filter=lfs diff=lfs merge=lfs -text
|
| 18081 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/staged/public/val.csv filter=lfs diff=lfs merge=lfs -text
|
| 18082 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/staged/tabdiff/adapter_report.json filter=lfs diff=lfs merge=lfs -text
|
| 18083 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/staged/tabdiff/adapter_transforms_applied.json filter=lfs diff=lfs merge=lfs -text
|
| 18084 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/staged/tabdiff/model_input_manifest.json filter=lfs diff=lfs merge=lfs -text
|
| 18085 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/tabdiff-n11-15215-20260521_053144.csv filter=lfs diff=lfs merge=lfs -text
|
| 18086 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/tabdiff_train_meta.json filter=lfs diff=lfs merge=lfs -text
|
| 18087 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/tabular_bundle/pipeline_n11/X_num_test.npy filter=lfs diff=lfs merge=lfs -text
|
| 18088 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/tabular_bundle/pipeline_n11/X_num_train.npy filter=lfs diff=lfs merge=lfs -text
|
| 18089 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/tabular_bundle/pipeline_n11/X_num_val.npy filter=lfs diff=lfs merge=lfs -text
|
| 18090 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/tabular_bundle/pipeline_n11/info.json filter=lfs diff=lfs merge=lfs -text
|
| 18091 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/tabular_bundle/pipeline_n11/real.csv filter=lfs diff=lfs merge=lfs -text
|
| 18092 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/tabular_bundle/pipeline_n11/staged_features.json filter=lfs diff=lfs merge=lfs -text
|
| 18093 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/tabular_bundle/pipeline_n11/test.csv filter=lfs diff=lfs merge=lfs -text
|
| 18094 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/tabular_bundle/pipeline_n11/train.csv filter=lfs diff=lfs merge=lfs -text
|
| 18095 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/tabular_bundle/pipeline_n11/val.csv filter=lfs diff=lfs merge=lfs -text
|
| 18096 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/tabular_bundle/pipeline_n11/y_test.npy filter=lfs diff=lfs merge=lfs -text
|
| 18097 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/tabular_bundle/pipeline_n11/y_train.npy filter=lfs diff=lfs merge=lfs -text
|
| 18098 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/tabular_bundle/pipeline_n11/y_val.npy filter=lfs diff=lfs merge=lfs -text
|
| 18099 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/train_20260521_051643.log filter=lfs diff=lfs merge=lfs -text
|
| 18100 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/_tabdiff_runtime/images/tabdiff_demo.gif filter=lfs diff=lfs merge=lfs -text
|
| 18101 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/_tabdiff_runtime/images/tabdiff_demo.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 18102 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/_tabdiff_runtime/tabdiff/configs/tabdiff_configs.toml filter=lfs diff=lfs merge=lfs -text
|
| 18103 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/bo_combo.json filter=lfs diff=lfs merge=lfs -text
|
| 18104 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/gen_20260521_054153.log filter=lfs diff=lfs merge=lfs -text
|
| 18105 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/input_snapshot.json filter=lfs diff=lfs merge=lfs -text
|
| 18106 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/models_tabdiff/trained.pt filter=lfs diff=lfs merge=lfs -text
|
| 18107 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/public_gate/normalized_schema_snapshot.json filter=lfs diff=lfs merge=lfs -text
|
| 18108 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/public_gate/public_gate_report.json filter=lfs diff=lfs merge=lfs -text
|
| 18109 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/public_gate/staged_input_manifest.json filter=lfs diff=lfs merge=lfs -text
|
| 18110 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/run_config.json filter=lfs diff=lfs merge=lfs -text
|
| 18111 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/runtime_result.json filter=lfs diff=lfs merge=lfs -text
|
| 18112 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/staged/public/staged_features.json filter=lfs diff=lfs merge=lfs -text
|
| 18113 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/staged/public/test.csv filter=lfs diff=lfs merge=lfs -text
|
| 18114 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/staged/public/train.csv filter=lfs diff=lfs merge=lfs -text
|
| 18115 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/staged/public/val.csv filter=lfs diff=lfs merge=lfs -text
|
| 18116 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/staged/tabdiff/adapter_report.json filter=lfs diff=lfs merge=lfs -text
|
| 18117 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/staged/tabdiff/adapter_transforms_applied.json filter=lfs diff=lfs merge=lfs -text
|
| 18118 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/staged/tabdiff/model_input_manifest.json filter=lfs diff=lfs merge=lfs -text
|
| 18119 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/tabdiff-n11-15215-20260521_054153.csv filter=lfs diff=lfs merge=lfs -text
|
| 18120 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/tabdiff_train_meta.json filter=lfs diff=lfs merge=lfs -text
|
| 18121 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/tabular_bundle/pipeline_n11/X_num_test.npy filter=lfs diff=lfs merge=lfs -text
|
| 18122 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/tabular_bundle/pipeline_n11/X_num_train.npy filter=lfs diff=lfs merge=lfs -text
|
| 18123 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/tabular_bundle/pipeline_n11/X_num_val.npy filter=lfs diff=lfs merge=lfs -text
|
| 18124 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/tabular_bundle/pipeline_n11/info.json filter=lfs diff=lfs merge=lfs -text
|
| 18125 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/tabular_bundle/pipeline_n11/real.csv filter=lfs diff=lfs merge=lfs -text
|
| 18126 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/tabular_bundle/pipeline_n11/staged_features.json filter=lfs diff=lfs merge=lfs -text
|
| 18127 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/tabular_bundle/pipeline_n11/test.csv filter=lfs diff=lfs merge=lfs -text
|
| 18128 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/tabular_bundle/pipeline_n11/train.csv filter=lfs diff=lfs merge=lfs -text
|
| 18129 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/tabular_bundle/pipeline_n11/val.csv filter=lfs diff=lfs merge=lfs -text
|
| 18130 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/tabular_bundle/pipeline_n11/y_test.npy filter=lfs diff=lfs merge=lfs -text
|
| 18131 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/tabular_bundle/pipeline_n11/y_train.npy filter=lfs diff=lfs merge=lfs -text
|
| 18132 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/tabular_bundle/pipeline_n11/y_val.npy filter=lfs diff=lfs merge=lfs -text
|
| 18133 |
+
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/train_20260521_053348.log filter=lfs diff=lfs merge=lfs -text
|
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_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_051642/_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_051642/_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)
|
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_tabdiff_runtime/src/metrics.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import enum
|
| 2 |
+
from typing import Any, Optional, Tuple, Dict, Union, cast
|
| 3 |
+
from functools import partial
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import scipy.special
|
| 7 |
+
import sklearn.metrics as skm
|
| 8 |
+
|
| 9 |
+
from . import util
|
| 10 |
+
from .util import TaskType
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class PredictionType(enum.Enum):
|
| 14 |
+
LOGITS = 'logits'
|
| 15 |
+
PROBS = 'probs'
|
| 16 |
+
|
| 17 |
+
class MetricsReport:
|
| 18 |
+
def __init__(self, report: dict, task_type: TaskType):
|
| 19 |
+
self._res = {k: {} for k in report.keys()}
|
| 20 |
+
if task_type in (TaskType.BINCLASS, TaskType.MULTICLASS):
|
| 21 |
+
self._metrics_names = ["acc", "f1"]
|
| 22 |
+
for k in report.keys():
|
| 23 |
+
self._res[k]["acc"] = report[k]["accuracy"]
|
| 24 |
+
self._res[k]["f1"] = report[k]["macro avg"]["f1-score"]
|
| 25 |
+
if task_type == TaskType.BINCLASS:
|
| 26 |
+
self._res[k]["roc_auc"] = report[k]["roc_auc"]
|
| 27 |
+
self._metrics_names.append("roc_auc")
|
| 28 |
+
|
| 29 |
+
elif task_type == TaskType.REGRESSION:
|
| 30 |
+
self._metrics_names = ["r2", "rmse"]
|
| 31 |
+
for k in report.keys():
|
| 32 |
+
self._res[k]["r2"] = report[k]["r2"]
|
| 33 |
+
self._res[k]["rmse"] = report[k]["rmse"]
|
| 34 |
+
else:
|
| 35 |
+
raise "Unknown TaskType!"
|
| 36 |
+
|
| 37 |
+
def get_splits_names(self) -> list[str]:
|
| 38 |
+
return self._res.keys()
|
| 39 |
+
|
| 40 |
+
def get_metrics_names(self) -> list[str]:
|
| 41 |
+
return self._metrics_names
|
| 42 |
+
|
| 43 |
+
def get_metric(self, split: str, metric: str) -> float:
|
| 44 |
+
return self._res[split][metric]
|
| 45 |
+
|
| 46 |
+
def get_val_score(self) -> float:
|
| 47 |
+
return self._res["val"]["r2"] if "r2" in self._res["val"] else self._res["val"]["f1"]
|
| 48 |
+
|
| 49 |
+
def get_test_score(self) -> float:
|
| 50 |
+
return self._res["test"]["r2"] if "r2" in self._res["test"] else self._res["test"]["f1"]
|
| 51 |
+
|
| 52 |
+
def print_metrics(self) -> None:
|
| 53 |
+
res = {
|
| 54 |
+
"val": {k: np.around(self._res["val"][k], 4) for k in self._res["val"]},
|
| 55 |
+
"test": {k: np.around(self._res["test"][k], 4) for k in self._res["test"]}
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
print("*"*100)
|
| 59 |
+
print("[val]")
|
| 60 |
+
print(res["val"])
|
| 61 |
+
print("[test]")
|
| 62 |
+
print(res["test"])
|
| 63 |
+
|
| 64 |
+
return res
|
| 65 |
+
|
| 66 |
+
class SeedsMetricsReport:
|
| 67 |
+
def __init__(self):
|
| 68 |
+
self._reports = []
|
| 69 |
+
|
| 70 |
+
def add_report(self, report: MetricsReport) -> None:
|
| 71 |
+
self._reports.append(report)
|
| 72 |
+
|
| 73 |
+
def get_mean_std(self) -> dict:
|
| 74 |
+
res = {k: {} for k in ["train", "val", "test"]}
|
| 75 |
+
for split in self._reports[0].get_splits_names():
|
| 76 |
+
for metric in self._reports[0].get_metrics_names():
|
| 77 |
+
res[split][metric] = [x.get_metric(split, metric) for x in self._reports]
|
| 78 |
+
|
| 79 |
+
agg_res = {k: {} for k in ["train", "val", "test"]}
|
| 80 |
+
for split in self._reports[0].get_splits_names():
|
| 81 |
+
for metric in self._reports[0].get_metrics_names():
|
| 82 |
+
for k, f in [("count", len), ("mean", np.mean), ("std", np.std)]:
|
| 83 |
+
agg_res[split][f"{metric}-{k}"] = f(res[split][metric])
|
| 84 |
+
self._res = res
|
| 85 |
+
self._agg_res = agg_res
|
| 86 |
+
|
| 87 |
+
return agg_res
|
| 88 |
+
|
| 89 |
+
def print_result(self) -> dict:
|
| 90 |
+
res = {split: {k: float(np.around(self._agg_res[split][k], 4)) for k in self._agg_res[split]} for split in ["val", "test"]}
|
| 91 |
+
print("="*100)
|
| 92 |
+
print("EVAL RESULTS:")
|
| 93 |
+
print("[val]")
|
| 94 |
+
print(res["val"])
|
| 95 |
+
print("[test]")
|
| 96 |
+
print(res["test"])
|
| 97 |
+
print("="*100)
|
| 98 |
+
return res
|
| 99 |
+
|
| 100 |
+
def calculate_rmse(
|
| 101 |
+
y_true: np.ndarray, y_pred: np.ndarray, std = None) -> float:
|
| 102 |
+
rmse = skm.mean_squared_error(y_true, y_pred) ** 0.5
|
| 103 |
+
if std is not None:
|
| 104 |
+
rmse *= std
|
| 105 |
+
return rmse
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _get_labels_and_probs(
|
| 109 |
+
y_pred: np.ndarray, task_type: TaskType, prediction_type: Optional[PredictionType]
|
| 110 |
+
) -> Tuple[np.ndarray, Optional[np.ndarray]]:
|
| 111 |
+
assert task_type in (TaskType.BINCLASS, TaskType.MULTICLASS)
|
| 112 |
+
|
| 113 |
+
if prediction_type is None:
|
| 114 |
+
return y_pred, None
|
| 115 |
+
|
| 116 |
+
if prediction_type == PredictionType.LOGITS:
|
| 117 |
+
probs = (
|
| 118 |
+
scipy.special.expit(y_pred)
|
| 119 |
+
if task_type == TaskType.BINCLASS
|
| 120 |
+
else scipy.special.softmax(y_pred, axis=1)
|
| 121 |
+
)
|
| 122 |
+
elif prediction_type == PredictionType.PROBS:
|
| 123 |
+
probs = y_pred
|
| 124 |
+
else:
|
| 125 |
+
util.raise_unknown('prediction_type', prediction_type)
|
| 126 |
+
|
| 127 |
+
assert probs is not None
|
| 128 |
+
labels = np.round(probs) if task_type == TaskType.BINCLASS else probs.argmax(axis=1)
|
| 129 |
+
return labels.astype('int64'), probs
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def calculate_metrics(
|
| 133 |
+
y_true: np.ndarray,
|
| 134 |
+
y_pred: np.ndarray,
|
| 135 |
+
task_type: Union[str, TaskType],
|
| 136 |
+
prediction_type: Optional[Union[str, PredictionType]],
|
| 137 |
+
y_info: Dict[str, Any],
|
| 138 |
+
) -> Dict[str, Any]:
|
| 139 |
+
# Example: calculate_metrics(y_true, y_pred, 'binclass', 'logits', {})
|
| 140 |
+
task_type = TaskType(task_type)
|
| 141 |
+
if prediction_type is not None:
|
| 142 |
+
prediction_type = PredictionType(prediction_type)
|
| 143 |
+
|
| 144 |
+
if task_type == TaskType.REGRESSION:
|
| 145 |
+
assert prediction_type is None
|
| 146 |
+
assert 'std' in y_info
|
| 147 |
+
rmse = calculate_rmse(y_true, y_pred, y_info['std'])
|
| 148 |
+
r2 = skm.r2_score(y_true, y_pred)
|
| 149 |
+
result = {'rmse': rmse, 'r2': r2}
|
| 150 |
+
else:
|
| 151 |
+
labels, probs = _get_labels_and_probs(y_pred, task_type, prediction_type)
|
| 152 |
+
result = cast(
|
| 153 |
+
Dict[str, Any], skm.classification_report(y_true, labels, output_dict=True)
|
| 154 |
+
)
|
| 155 |
+
if task_type == TaskType.BINCLASS:
|
| 156 |
+
result['roc_auc'] = skm.roc_auc_score(y_true, probs)
|
| 157 |
+
return result
|
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_tabdiff_runtime/src/util.py
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import atexit
|
| 3 |
+
import enum
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import pickle
|
| 7 |
+
import shutil
|
| 8 |
+
import sys
|
| 9 |
+
import time
|
| 10 |
+
import uuid
|
| 11 |
+
from copy import deepcopy
|
| 12 |
+
from dataclasses import asdict, fields, is_dataclass
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from pprint import pprint
|
| 15 |
+
from typing import Any, Callable, List, Dict, Type, Optional, Tuple, TypeVar, Union, cast, get_args, get_origin
|
| 16 |
+
|
| 17 |
+
import __main__
|
| 18 |
+
import numpy as np
|
| 19 |
+
import tomli
|
| 20 |
+
import tomli_w
|
| 21 |
+
import torch
|
| 22 |
+
import typing as ty
|
| 23 |
+
|
| 24 |
+
from . import env
|
| 25 |
+
|
| 26 |
+
RawConfig = Dict[str, Any]
|
| 27 |
+
Report = Dict[str, Any]
|
| 28 |
+
T = TypeVar('T')
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class Part(enum.Enum):
|
| 32 |
+
TRAIN = 'train'
|
| 33 |
+
VAL = 'val'
|
| 34 |
+
TEST = 'test'
|
| 35 |
+
|
| 36 |
+
def __str__(self) -> str:
|
| 37 |
+
return self.value
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class TaskType(enum.Enum):
|
| 41 |
+
BINCLASS = 'binclass'
|
| 42 |
+
MULTICLASS = 'multiclass'
|
| 43 |
+
REGRESSION = 'regression'
|
| 44 |
+
|
| 45 |
+
def __str__(self) -> str:
|
| 46 |
+
return self.value
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def update_training_log(training_log, data, metrics):
|
| 51 |
+
def _update(log_part, data_part):
|
| 52 |
+
for k, v in data_part.items():
|
| 53 |
+
if isinstance(v, dict):
|
| 54 |
+
_update(log_part.setdefault(k, {}), v)
|
| 55 |
+
elif isinstance(v, list):
|
| 56 |
+
log_part.setdefault(k, []).extend(v)
|
| 57 |
+
else:
|
| 58 |
+
log_part.setdefault(k, []).append(v)
|
| 59 |
+
|
| 60 |
+
_update(training_log, data)
|
| 61 |
+
transposed_metrics = {}
|
| 62 |
+
for part, part_metrics in metrics.items():
|
| 63 |
+
for metric_name, value in part_metrics.items():
|
| 64 |
+
transposed_metrics.setdefault(metric_name, {})[part] = value
|
| 65 |
+
_update(training_log, transposed_metrics)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def raise_unknown(unknown_what: str, unknown_value: Any):
|
| 69 |
+
raise ValueError(f'Unknown {unknown_what}: {unknown_value}')
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _replace(data, condition, value):
|
| 73 |
+
def do(x):
|
| 74 |
+
if isinstance(x, dict):
|
| 75 |
+
return {k: do(v) for k, v in x.items()}
|
| 76 |
+
elif isinstance(x, list):
|
| 77 |
+
return [do(y) for y in x]
|
| 78 |
+
else:
|
| 79 |
+
return value if condition(x) else x
|
| 80 |
+
|
| 81 |
+
return do(data)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
_CONFIG_NONE = '__none__'
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def unpack_config(config: RawConfig) -> RawConfig:
|
| 88 |
+
config = cast(RawConfig, _replace(config, lambda x: x == _CONFIG_NONE, None))
|
| 89 |
+
return config
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def pack_config(config: RawConfig) -> RawConfig:
|
| 93 |
+
config = cast(RawConfig, _replace(config, lambda x: x is None, _CONFIG_NONE))
|
| 94 |
+
return config
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def load_config(path: Union[Path, str]) -> Any:
|
| 98 |
+
with open(path, 'rb') as f:
|
| 99 |
+
return unpack_config(tomli.load(f))
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def dump_config(config: Any, path: Union[Path, str]) -> None:
|
| 103 |
+
with open(path, 'wb') as f:
|
| 104 |
+
tomli_w.dump(pack_config(config), f)
|
| 105 |
+
# check that there are no bugs in all these "pack/unpack" things
|
| 106 |
+
assert config == load_config(path)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def load_json(path: Union[Path, str], **kwargs) -> Any:
|
| 110 |
+
return json.loads(Path(path).read_text(), **kwargs)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def dump_json(x: Any, path: Union[Path, str], **kwargs) -> None:
|
| 114 |
+
kwargs.setdefault('indent', 4)
|
| 115 |
+
Path(path).write_text(json.dumps(x, **kwargs) + '\n')
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def load_pickle(path: Union[Path, str], **kwargs) -> Any:
|
| 119 |
+
return pickle.loads(Path(path).read_bytes(), **kwargs)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def dump_pickle(x: Any, path: Union[Path, str], **kwargs) -> None:
|
| 123 |
+
Path(path).write_bytes(pickle.dumps(x, **kwargs))
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def load(path: Union[Path, str], **kwargs) -> Any:
|
| 127 |
+
return globals()[f'load_{Path(path).suffix[1:]}'](Path(path), **kwargs)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def dump(x: Any, path: Union[Path, str], **kwargs) -> Any:
|
| 131 |
+
return globals()[f'dump_{Path(path).suffix[1:]}'](x, Path(path), **kwargs)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _get_output_item_path(
|
| 135 |
+
path: Union[str, Path], filename: str, must_exist: bool
|
| 136 |
+
) -> Path:
|
| 137 |
+
path = env.get_path(path)
|
| 138 |
+
if path.suffix == '.toml':
|
| 139 |
+
path = path.with_suffix('')
|
| 140 |
+
if path.is_dir():
|
| 141 |
+
path = path / filename
|
| 142 |
+
else:
|
| 143 |
+
assert path.name == filename
|
| 144 |
+
assert path.parent.exists()
|
| 145 |
+
if must_exist:
|
| 146 |
+
assert path.exists()
|
| 147 |
+
return path
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def load_report(path: Path) -> Report:
|
| 151 |
+
return load_json(_get_output_item_path(path, 'report.json', True))
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def dump_report(report: dict, path: Path) -> None:
|
| 155 |
+
dump_json(report, _get_output_item_path(path, 'report.json', False))
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def load_predictions(path: Path) -> Dict[str, np.ndarray]:
|
| 159 |
+
with np.load(_get_output_item_path(path, 'predictions.npz', True)) as predictions:
|
| 160 |
+
return {x: predictions[x] for x in predictions}
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def dump_predictions(predictions: Dict[str, np.ndarray], path: Path) -> None:
|
| 164 |
+
np.savez(_get_output_item_path(path, 'predictions.npz', False), **predictions)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def dump_metrics(metrics: Dict[str, Any], path: Path) -> None:
|
| 168 |
+
dump_json(metrics, _get_output_item_path(path, 'metrics.json', False))
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def load_checkpoint(path: Path, *args, **kwargs) -> Dict[str, np.ndarray]:
|
| 172 |
+
return torch.load(
|
| 173 |
+
_get_output_item_path(path, 'checkpoint.pt', True), *args, **kwargs
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def get_device() -> torch.device:
|
| 178 |
+
if torch.cuda.is_available():
|
| 179 |
+
assert os.environ.get('CUDA_VISIBLE_DEVICES') is not None
|
| 180 |
+
return torch.device('cuda:0')
|
| 181 |
+
else:
|
| 182 |
+
return torch.device('cpu')
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def _print_sep(c, size=100):
|
| 186 |
+
print(c * size)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
_LAST_SNAPSHOT_TIME = None
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def backup_output(output_dir: Path) -> None:
|
| 193 |
+
backup_dir = os.environ.get('TMP_OUTPUT_PATH')
|
| 194 |
+
snapshot_dir = os.environ.get('SNAPSHOT_PATH')
|
| 195 |
+
if backup_dir is None:
|
| 196 |
+
assert snapshot_dir is None
|
| 197 |
+
return
|
| 198 |
+
assert snapshot_dir is not None
|
| 199 |
+
|
| 200 |
+
try:
|
| 201 |
+
relative_output_dir = output_dir.relative_to(env.PROJ)
|
| 202 |
+
except ValueError:
|
| 203 |
+
return
|
| 204 |
+
|
| 205 |
+
for dir_ in [backup_dir, snapshot_dir]:
|
| 206 |
+
new_output_dir = dir_ / relative_output_dir
|
| 207 |
+
prev_backup_output_dir = new_output_dir.with_name(new_output_dir.name + '_prev')
|
| 208 |
+
new_output_dir.parent.mkdir(exist_ok=True, parents=True)
|
| 209 |
+
if new_output_dir.exists():
|
| 210 |
+
new_output_dir.rename(prev_backup_output_dir)
|
| 211 |
+
shutil.copytree(output_dir, new_output_dir)
|
| 212 |
+
# the case for evaluate.py which automatically creates configs
|
| 213 |
+
if output_dir.with_suffix('.toml').exists():
|
| 214 |
+
shutil.copyfile(
|
| 215 |
+
output_dir.with_suffix('.toml'), new_output_dir.with_suffix('.toml')
|
| 216 |
+
)
|
| 217 |
+
if prev_backup_output_dir.exists():
|
| 218 |
+
shutil.rmtree(prev_backup_output_dir)
|
| 219 |
+
|
| 220 |
+
global _LAST_SNAPSHOT_TIME
|
| 221 |
+
if _LAST_SNAPSHOT_TIME is None or time.time() - _LAST_SNAPSHOT_TIME > 10 * 60:
|
| 222 |
+
import nirvana_dl.snapshot # type: ignore[code]
|
| 223 |
+
|
| 224 |
+
nirvana_dl.snapshot.dump_snapshot()
|
| 225 |
+
_LAST_SNAPSHOT_TIME = time.time()
|
| 226 |
+
print('The snapshot was saved!')
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def _get_scores(metrics: Dict[str, Dict[str, Any]]) -> Optional[Dict[str, float]]:
|
| 230 |
+
return (
|
| 231 |
+
{k: v['score'] for k, v in metrics.items()}
|
| 232 |
+
if 'score' in next(iter(metrics.values()))
|
| 233 |
+
else None
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def format_scores(metrics: Dict[str, Dict[str, Any]]) -> str:
|
| 238 |
+
return ' '.join(
|
| 239 |
+
f"[{x}] {metrics[x]['score']:.3f}"
|
| 240 |
+
for x in ['test', 'val', 'train']
|
| 241 |
+
if x in metrics
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def finish(output_dir: Path, report: dict) -> None:
|
| 246 |
+
print()
|
| 247 |
+
_print_sep('=')
|
| 248 |
+
|
| 249 |
+
metrics = report.get('metrics')
|
| 250 |
+
if metrics is not None:
|
| 251 |
+
scores = _get_scores(metrics)
|
| 252 |
+
if scores is not None:
|
| 253 |
+
dump_json(scores, output_dir / 'scores.json')
|
| 254 |
+
print(format_scores(metrics))
|
| 255 |
+
_print_sep('-')
|
| 256 |
+
|
| 257 |
+
dump_report(report, output_dir)
|
| 258 |
+
json_output_path = os.environ.get('JSON_OUTPUT_FILE')
|
| 259 |
+
if json_output_path:
|
| 260 |
+
try:
|
| 261 |
+
key = str(output_dir.relative_to(env.PROJ))
|
| 262 |
+
except ValueError:
|
| 263 |
+
pass
|
| 264 |
+
else:
|
| 265 |
+
json_output_path = Path(json_output_path)
|
| 266 |
+
try:
|
| 267 |
+
json_data = json.loads(json_output_path.read_text())
|
| 268 |
+
except (FileNotFoundError, json.decoder.JSONDecodeError):
|
| 269 |
+
json_data = {}
|
| 270 |
+
json_data[key] = load_json(output_dir / 'report.json')
|
| 271 |
+
json_output_path.write_text(json.dumps(json_data, indent=4))
|
| 272 |
+
shutil.copyfile(
|
| 273 |
+
json_output_path,
|
| 274 |
+
os.path.join(os.environ['SNAPSHOT_PATH'], 'json_output.json'),
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
output_dir.joinpath('DONE').touch()
|
| 278 |
+
backup_output(output_dir)
|
| 279 |
+
print(f'Done! | {report.get("time")} | {output_dir}')
|
| 280 |
+
_print_sep('=')
|
| 281 |
+
print()
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def from_dict(datacls: Type[T], data: dict) -> T:
|
| 285 |
+
assert is_dataclass(datacls)
|
| 286 |
+
data = deepcopy(data)
|
| 287 |
+
for field in fields(datacls):
|
| 288 |
+
if field.name not in data:
|
| 289 |
+
continue
|
| 290 |
+
if is_dataclass(field.type):
|
| 291 |
+
data[field.name] = from_dict(field.type, data[field.name])
|
| 292 |
+
elif (
|
| 293 |
+
get_origin(field.type) is Union
|
| 294 |
+
and len(get_args(field.type)) == 2
|
| 295 |
+
and get_args(field.type)[1] is type(None)
|
| 296 |
+
and is_dataclass(get_args(field.type)[0])
|
| 297 |
+
):
|
| 298 |
+
if data[field.name] is not None:
|
| 299 |
+
data[field.name] = from_dict(get_args(field.type)[0], data[field.name])
|
| 300 |
+
return datacls(**data)
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def replace_factor_with_value(
|
| 304 |
+
config: RawConfig,
|
| 305 |
+
key: str,
|
| 306 |
+
reference_value: int,
|
| 307 |
+
bounds: Tuple[float, float],
|
| 308 |
+
) -> None:
|
| 309 |
+
factor_key = key + '_factor'
|
| 310 |
+
if factor_key not in config:
|
| 311 |
+
assert key in config
|
| 312 |
+
else:
|
| 313 |
+
assert key not in config
|
| 314 |
+
factor = config.pop(factor_key)
|
| 315 |
+
assert bounds[0] <= factor <= bounds[1]
|
| 316 |
+
config[key] = int(factor * reference_value)
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def get_temporary_copy(path: Union[str, Path]) -> Path:
|
| 320 |
+
path = env.get_path(path)
|
| 321 |
+
assert not path.is_dir() and not path.is_symlink()
|
| 322 |
+
tmp_path = path.with_name(
|
| 323 |
+
path.stem + '___' + str(uuid.uuid4()).replace('-', '') + path.suffix
|
| 324 |
+
)
|
| 325 |
+
shutil.copyfile(path, tmp_path)
|
| 326 |
+
atexit.register(lambda: tmp_path.unlink())
|
| 327 |
+
return tmp_path
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def get_python():
|
| 331 |
+
python = Path('python3.9')
|
| 332 |
+
return str(python) if python.exists() else 'python'
|
| 333 |
+
|
| 334 |
+
def get_catboost_config(real_data_path, is_cv=False):
|
| 335 |
+
ds_name = Path(real_data_path).name
|
| 336 |
+
C = load_json(f'tuned_models/catboost/{ds_name}_cv.json')
|
| 337 |
+
return C
|
| 338 |
+
|
| 339 |
+
def get_categories(X_train_cat):
|
| 340 |
+
return (
|
| 341 |
+
None
|
| 342 |
+
if X_train_cat is None
|
| 343 |
+
else [
|
| 344 |
+
len(set(X_train_cat[:, i]))
|
| 345 |
+
for i in range(X_train_cat.shape[1])
|
| 346 |
+
]
|
| 347 |
+
)
|
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_tabdiff_runtime/synthcity.yaml
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: synthcity
|
| 2 |
+
channels:
|
| 3 |
+
- pytorch
|
| 4 |
+
- nvidia
|
| 5 |
+
- defaults
|
| 6 |
+
dependencies:
|
| 7 |
+
- python=3.10
|
| 8 |
+
- pip
|
| 9 |
+
- pip:
|
| 10 |
+
- synthcity
|
| 11 |
+
- category_encoders
|
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_tabdiff_runtime/tabdiff.yaml
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: tabdiff
|
| 2 |
+
channels:
|
| 3 |
+
- pytorch
|
| 4 |
+
- nvidia
|
| 5 |
+
- defaults
|
| 6 |
+
dependencies:
|
| 7 |
+
- python=3.10
|
| 8 |
+
- pytorch=2.0.1
|
| 9 |
+
- torchvision==0.15.2
|
| 10 |
+
- torchaudio==2.0.2
|
| 11 |
+
- pytorch-cuda=11.7
|
| 12 |
+
- numpy<2
|
| 13 |
+
- pip
|
| 14 |
+
- pip:
|
| 15 |
+
- pandas
|
| 16 |
+
- scikit-learn
|
| 17 |
+
- scipy
|
| 18 |
+
- icecream
|
| 19 |
+
- xlrd
|
| 20 |
+
- tomli-w
|
| 21 |
+
- tomli==2.0.1
|
| 22 |
+
- category_encoders
|
| 23 |
+
- imbalanced-learn
|
| 24 |
+
- kaggle
|
| 25 |
+
- transformers
|
| 26 |
+
- datasets
|
| 27 |
+
- peft==0.9.0
|
| 28 |
+
- ml_collections
|
| 29 |
+
- sdmetrics
|
| 30 |
+
- prdc
|
| 31 |
+
- rdt
|
| 32 |
+
- openpyxl
|
| 33 |
+
- xgboost
|
| 34 |
+
- wandb==0.17.3
|
| 35 |
+
- kaleido
|
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_tabdiff_runtime/tabdiff/configs/tabdiff_configs.toml
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:38eff74ecb572c9baafc5e912f8b5421cae686ddb4df6e3bc2a9b69c6ec69cd6
|
| 3 |
+
size 1234
|
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_tabdiff_runtime/tabdiff/main.py
ADDED
|
@@ -0,0 +1,344 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import glob
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import pickle
|
| 5 |
+
import random
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
from tabdiff.metrics import TabMetrics
|
| 9 |
+
from tabdiff.modules.main_modules import UniModMLP
|
| 10 |
+
from tabdiff.modules.main_modules import Model
|
| 11 |
+
from tabdiff.models.unified_ctime_diffusion import UnifiedCtimeDiffusion
|
| 12 |
+
from tabdiff.trainer import Trainer
|
| 13 |
+
import src
|
| 14 |
+
import torch
|
| 15 |
+
|
| 16 |
+
from torch.utils.data import DataLoader
|
| 17 |
+
import argparse
|
| 18 |
+
import warnings
|
| 19 |
+
|
| 20 |
+
import wandb
|
| 21 |
+
|
| 22 |
+
from copy import deepcopy
|
| 23 |
+
|
| 24 |
+
from utils_train import TabDiffDataset
|
| 25 |
+
|
| 26 |
+
warnings.filterwarnings('ignore')
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def main(args):
|
| 30 |
+
device = args.device
|
| 31 |
+
|
| 32 |
+
## Disable scientific numerical format
|
| 33 |
+
np.set_printoptions(suppress=True)
|
| 34 |
+
torch.set_printoptions(sci_mode=False)
|
| 35 |
+
|
| 36 |
+
## Get data info
|
| 37 |
+
dataname = args.dataname
|
| 38 |
+
data_dir = f'data/{dataname}'
|
| 39 |
+
info_path = f'data/{dataname}/info.json'
|
| 40 |
+
with open(info_path, 'r') as f:
|
| 41 |
+
info = json.load(f)
|
| 42 |
+
|
| 43 |
+
## Set up flags
|
| 44 |
+
is_dcr = 'dcr' in dataname
|
| 45 |
+
|
| 46 |
+
## Set experiment name
|
| 47 |
+
exp_name = args.exp_name
|
| 48 |
+
if args.exp_name is None:
|
| 49 |
+
exp_name = 'non_learnable_schedule' if args.non_learnable_schedule else 'learnable_schedule'
|
| 50 |
+
exp_name += '_y_only' if args.y_only else ''
|
| 51 |
+
|
| 52 |
+
## Load configs
|
| 53 |
+
curr_dir = os.path.dirname(os.path.abspath(__file__))
|
| 54 |
+
config_path = f'{curr_dir}/configs/tabdiff_configs.toml'
|
| 55 |
+
raw_config = src.load_config(config_path)
|
| 56 |
+
|
| 57 |
+
print(f"{args.mode.capitalize()} Mode is Enabled")
|
| 58 |
+
num_samples_to_generate = None
|
| 59 |
+
ckpt_path = None
|
| 60 |
+
if args.mode == 'train':
|
| 61 |
+
print("NEW training is started")
|
| 62 |
+
elif args.mode == 'test':
|
| 63 |
+
num_samples_to_generate = args.num_samples_to_generate
|
| 64 |
+
ckpt_path = args.ckpt_path
|
| 65 |
+
if ckpt_path is None:
|
| 66 |
+
ckpt_parent_path = f"{curr_dir}/ckpt/{dataname}/{exp_name}"
|
| 67 |
+
ckpt_path_arr = glob.glob(f"{ckpt_parent_path}/best_ema_model*")
|
| 68 |
+
assert ckpt_path_arr, f"Cannot not infer ckpt_path from {ckpt_parent_path}, please make sure that you first train a model before testing!"
|
| 69 |
+
ckpt_path = ckpt_path_arr[0]
|
| 70 |
+
config_path = os.path.join(os.path.dirname(ckpt_path), 'config.pkl')
|
| 71 |
+
if os.path.exists(config_path):
|
| 72 |
+
with open(config_path, 'rb') as f:
|
| 73 |
+
cached_raw_config = pickle.load(f)
|
| 74 |
+
print(f"Found cached config at {config_path}")
|
| 75 |
+
raw_config = cached_raw_config
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
## Creat model_save and result paths
|
| 79 |
+
model_save_path, result_save_path = None, None
|
| 80 |
+
if args.mode == 'train':
|
| 81 |
+
model_save_path = 'debug/ckpt' if args.debug else f'{curr_dir}/ckpt/{dataname}/{exp_name}'
|
| 82 |
+
result_save_path = model_save_path.replace('ckpt', 'result') #i.e., f'{curr_dir}/results/{dataname}/{exp_name}'
|
| 83 |
+
elif args.mode == 'test':
|
| 84 |
+
if args.report:
|
| 85 |
+
result_save_path = f"eval/report_runs/{exp_name}/{dataname}"
|
| 86 |
+
else:
|
| 87 |
+
result_save_path = os.path.dirname(ckpt_path).replace('ckpt', 'result') # infer the exp_name from the ckpt_name
|
| 88 |
+
raw_config['model_save_path'] = model_save_path
|
| 89 |
+
raw_config['result_save_path'] = result_save_path
|
| 90 |
+
if model_save_path is not None:
|
| 91 |
+
if not os.path.exists(model_save_path):
|
| 92 |
+
os.makedirs(model_save_path)
|
| 93 |
+
if result_save_path is not None:
|
| 94 |
+
if not os.path.exists(result_save_path):
|
| 95 |
+
os.makedirs(result_save_path)
|
| 96 |
+
|
| 97 |
+
## Make everything determinstic if needed
|
| 98 |
+
raw_config['deterministic'] = args.deterministic
|
| 99 |
+
if args.deterministic:
|
| 100 |
+
print("DETERMINISTIC MODE is enabled!!!")
|
| 101 |
+
## Set global random seeds
|
| 102 |
+
torch.manual_seed(0)
|
| 103 |
+
random.seed(0)
|
| 104 |
+
np.random.seed(0)
|
| 105 |
+
|
| 106 |
+
## Ensure deterministic CUDA operations
|
| 107 |
+
os.environ['PYTHONHASHSEED'] = '0'
|
| 108 |
+
os.environ['CUBLAS_WORKSPACE_CONFIG'] = ':4096:8' # or ':16:8'
|
| 109 |
+
torch.use_deterministic_algorithms(True)
|
| 110 |
+
if torch.cuda.is_available():
|
| 111 |
+
torch.cuda.manual_seed(0)
|
| 112 |
+
torch.cuda.manual_seed_all(0)
|
| 113 |
+
torch.backends.cudnn.deterministic = True
|
| 114 |
+
torch.backends.cudnn.benchmark = False
|
| 115 |
+
|
| 116 |
+
## Set debug mode parameters
|
| 117 |
+
if args.debug: # fast eval for DEBUG mode
|
| 118 |
+
raw_config['train']['main']['check_val_every'] = 2
|
| 119 |
+
raw_config['diffusion_params']['num_timesteps'] = 4
|
| 120 |
+
raw_config['train']['main']['batch_size'] = 4096
|
| 121 |
+
raw_config['sample']['batch_size'] = 10000
|
| 122 |
+
|
| 123 |
+
# CI /镜像冒烟:覆盖训练步数(默认不设置)
|
| 124 |
+
_smoke_steps = os.environ.get("TABDIFF_SMOKE_STEPS", "").strip()
|
| 125 |
+
if _smoke_steps and args.mode == "train":
|
| 126 |
+
n = max(1, int(_smoke_steps))
|
| 127 |
+
raw_config["train"]["main"]["steps"] = n
|
| 128 |
+
raw_config["train"]["main"]["check_val_every"] = max(1, min(n, raw_config["train"]["main"]["check_val_every"]))
|
| 129 |
+
# Pipeline 适配器:避免小步数训练时在中途频繁做生成评测;仅在最后一轮 checkpoint
|
| 130 |
+
if os.environ.get("TABDIFF_ADAPTER_TRAIN", "").strip() and args.mode == "train":
|
| 131 |
+
raw_config["train"]["main"]["check_val_every"] = int(raw_config["train"]["main"]["steps"])
|
| 132 |
+
|
| 133 |
+
_train_batch = os.environ.get("TABDIFF_BATCH_SIZE", "").strip() or os.environ.get("TABDIFF_TRAIN_BATCH_SIZE", "").strip()
|
| 134 |
+
if _train_batch:
|
| 135 |
+
raw_config["train"]["main"]["batch_size"] = max(1, int(_train_batch))
|
| 136 |
+
_sample_batch = os.environ.get("TABDIFF_SAMPLE_BATCH_SIZE", "").strip()
|
| 137 |
+
if _sample_batch:
|
| 138 |
+
raw_config["sample"]["batch_size"] = max(1, int(_sample_batch))
|
| 139 |
+
_train_lr = os.environ.get("TABDIFF_LR", "").strip() or os.environ.get("TABDIFF_LEARNING_RATE", "").strip()
|
| 140 |
+
if _train_lr:
|
| 141 |
+
raw_config["train"]["main"]["lr"] = float(_train_lr)
|
| 142 |
+
_num_timesteps = os.environ.get("TABDIFF_NUM_TIMESTEPS", "").strip() or os.environ.get("TABDIFF_TIMESTEPS", "").strip()
|
| 143 |
+
if _num_timesteps:
|
| 144 |
+
raw_config["diffusion_params"]["num_timesteps"] = max(1, int(_num_timesteps))
|
| 145 |
+
|
| 146 |
+
## Load training data
|
| 147 |
+
batch_size = raw_config['train']['main']['batch_size']
|
| 148 |
+
|
| 149 |
+
train_data = TabDiffDataset(dataname, data_dir, info, y_only=args.y_only, isTrain=True, dequant_dist=raw_config['data']['dequant_dist'], int_dequant_factor=raw_config['data']['int_dequant_factor'])
|
| 150 |
+
train_loader = DataLoader(
|
| 151 |
+
train_data,
|
| 152 |
+
batch_size = batch_size,
|
| 153 |
+
shuffle = True,
|
| 154 |
+
num_workers = int(os.environ.get('TABDIFF_NUM_WORKERS', '0')),
|
| 155 |
+
)
|
| 156 |
+
d_numerical, categories = train_data.d_numerical, train_data.categories
|
| 157 |
+
|
| 158 |
+
val_data = TabDiffDataset(dataname, data_dir, info, y_only=args.y_only, isTrain=False, dequant_dist=raw_config['data']['dequant_dist'], int_dequant_factor=raw_config['data']['int_dequant_factor'])
|
| 159 |
+
|
| 160 |
+
## Load Metrics
|
| 161 |
+
real_data_path = f'synthetic/{dataname}/real.csv'
|
| 162 |
+
test_data_path = f'synthetic/{dataname}/test.csv'
|
| 163 |
+
val_data_path = f'synthetic/{dataname}/val.csv'
|
| 164 |
+
if not os.path.exists(val_data_path):
|
| 165 |
+
print(f"{args.dataname} does not have its validation set. During MLE evaluation, a validation set will be splitted from the training set!")
|
| 166 |
+
val_data_path = None
|
| 167 |
+
if args.mode == 'train':
|
| 168 |
+
metric_list = ["density"]
|
| 169 |
+
else:
|
| 170 |
+
if is_dcr:
|
| 171 |
+
metric_list = ["dcr"]
|
| 172 |
+
else:
|
| 173 |
+
metric_list = [
|
| 174 |
+
"density",
|
| 175 |
+
"mle",
|
| 176 |
+
"c2st",
|
| 177 |
+
]
|
| 178 |
+
metrics = TabMetrics(real_data_path, test_data_path, val_data_path, info, device, metric_list=metric_list)
|
| 179 |
+
|
| 180 |
+
## Load the module and models
|
| 181 |
+
raw_config['unimodmlp_params']['d_numerical'] = d_numerical
|
| 182 |
+
raw_config['unimodmlp_params']['categories'] = (categories+1).tolist() # add one for the mask category
|
| 183 |
+
if args.y_only:
|
| 184 |
+
raw_config['unimodmlp_params']['use_mlp'] = False # drop the mlp when training the unconditional model
|
| 185 |
+
raw_config['unimodmlp_params']['dim_t'] = 128 #reduce the size of the mlp
|
| 186 |
+
main_model_path = args.ckpt_path
|
| 187 |
+
if main_model_path is None:
|
| 188 |
+
main_model_parent_path = f"{curr_dir}/ckpt/{dataname}/{exp_name.replace('_y_only', '')}"
|
| 189 |
+
main_model_path_arr = glob.glob(f"{main_model_parent_path}/best_ema_model*")
|
| 190 |
+
assert main_model_path_arr, f"Cannot not infer the main model's ckpt_path from {main_model_parent_path}, please make sure that you first train a main model before training the y_only model!"
|
| 191 |
+
main_model_path = main_model_path_arr[0]
|
| 192 |
+
main_model_configs = pickle.load(open(os.path.join(os.path.dirname(main_model_path), 'config.pkl'), 'rb'))
|
| 193 |
+
if main_model_configs['diffusion_params']['scheduler'] == "power_mean_per_column": # if learnable schedule is enabled in the main model, we need to infer noise params of the target column from the main model ckpt and train the y_only model with those params
|
| 194 |
+
from tabdiff.models.noise_schedule import PowerMeanNoise_PerColumn, LogLinearNoise_PerColumn
|
| 195 |
+
if info['task_type'] == 'regression':
|
| 196 |
+
noise_schedule = PowerMeanNoise_PerColumn(
|
| 197 |
+
num_numerical=main_model_configs['unimodmlp_params']['d_numerical'],
|
| 198 |
+
**main_model_configs['diffusion_params']['noise_schedule_params']
|
| 199 |
+
)
|
| 200 |
+
raw_config['diffusion_params']['noise_schedule_params']['rho'] = noise_schedule.rho()[0].item() # the target col is placed at the first position
|
| 201 |
+
else:
|
| 202 |
+
noise_schedule = LogLinearNoise_PerColumn(
|
| 203 |
+
num_categories=len(main_model_configs['unimodmlp_params']['categories']),
|
| 204 |
+
**main_model_configs['diffusion_params']['noise_schedule_params']
|
| 205 |
+
)
|
| 206 |
+
raw_config['diffusion_params']['noise_schedule_params']['k'] = noise_schedule.k()[0].item() # the target col is placed at the first position
|
| 207 |
+
|
| 208 |
+
backbone = UniModMLP(
|
| 209 |
+
**raw_config['unimodmlp_params']
|
| 210 |
+
)
|
| 211 |
+
model = Model(backbone, **raw_config['diffusion_params']['edm_params'])
|
| 212 |
+
model.to(device)
|
| 213 |
+
|
| 214 |
+
## Create and load y_only_model for imputation
|
| 215 |
+
y_only_model = None
|
| 216 |
+
if args.impute:
|
| 217 |
+
y_only_model_path = args.y_only_model_path
|
| 218 |
+
if y_only_model_path is None:
|
| 219 |
+
y_only_model_parent_path = f"{curr_dir}/ckpt/{dataname}/{exp_name}_y_only"
|
| 220 |
+
y_only_model_path_arr = glob.glob(f"{y_only_model_parent_path}/best_ema_model*")
|
| 221 |
+
assert y_only_model_path_arr, f"Cannot not infer y_only model's ckpt_path from {y_only_model_parent_path}, please make sure that you first train a y_only model before testing imputation!"
|
| 222 |
+
y_only_model_path = y_only_model_path_arr[0]
|
| 223 |
+
y_only_model_config_path = os.path.join(os.path.dirname(y_only_model_path), 'config.pkl')
|
| 224 |
+
with open(y_only_model_config_path, 'rb') as f:
|
| 225 |
+
y_only_model_config = pickle.load(f)
|
| 226 |
+
y_only_model = UniModMLP(
|
| 227 |
+
**y_only_model_config['unimodmlp_params']
|
| 228 |
+
)
|
| 229 |
+
y_only_model = Model(y_only_model, **y_only_model_config['diffusion_params']['edm_params'])
|
| 230 |
+
y_only_model.to(device)
|
| 231 |
+
# load weights
|
| 232 |
+
state_dicts = torch.load(y_only_model_path, map_location=device)
|
| 233 |
+
y_only_model.load_state_dict(state_dicts['denoise_fn'])
|
| 234 |
+
|
| 235 |
+
if not args.y_only and not args.non_learnable_schedule:
|
| 236 |
+
raw_config['diffusion_params']['scheduler'] = 'power_mean_per_column'
|
| 237 |
+
raw_config['diffusion_params']['cat_scheduler'] = 'log_linear_per_column'
|
| 238 |
+
diffusion = UnifiedCtimeDiffusion(
|
| 239 |
+
num_classes=categories,
|
| 240 |
+
num_numerical_features=d_numerical,
|
| 241 |
+
denoise_fn=model,
|
| 242 |
+
y_only_model=y_only_model,
|
| 243 |
+
**raw_config['diffusion_params'],
|
| 244 |
+
device=device,
|
| 245 |
+
)
|
| 246 |
+
num_params = sum(p.numel() for p in diffusion.parameters())
|
| 247 |
+
print("The number of parameters = ", num_params)
|
| 248 |
+
diffusion.to(device)
|
| 249 |
+
diffusion.train()
|
| 250 |
+
|
| 251 |
+
## Print the configs
|
| 252 |
+
printed_configs = json.dumps(raw_config, default=lambda x: int(x) if isinstance(x, np.int64) else x, indent=4)
|
| 253 |
+
print(f"The config of the current run is : \n {printed_configs}")
|
| 254 |
+
|
| 255 |
+
## Enable Wandb
|
| 256 |
+
project_name = f"tabdiff_{dataname}"
|
| 257 |
+
raw_config['project_name'] = project_name
|
| 258 |
+
logger = wandb.init(
|
| 259 |
+
project=raw_config['project_name'],
|
| 260 |
+
name=exp_name,
|
| 261 |
+
config=raw_config,
|
| 262 |
+
mode='disabled' if args.debug or args.no_wandb else 'online',
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
## Load Trainer
|
| 266 |
+
sample_batch_size = raw_config['sample']['batch_size']
|
| 267 |
+
trainer = Trainer(
|
| 268 |
+
diffusion,
|
| 269 |
+
train_loader,
|
| 270 |
+
train_data,
|
| 271 |
+
val_data,
|
| 272 |
+
metrics,
|
| 273 |
+
logger,
|
| 274 |
+
**raw_config['train']['main'],
|
| 275 |
+
sample_batch_size=sample_batch_size,
|
| 276 |
+
num_samples_to_generate=num_samples_to_generate,
|
| 277 |
+
model_save_path=raw_config['model_save_path'],
|
| 278 |
+
result_save_path=raw_config['result_save_path'],
|
| 279 |
+
device=device,
|
| 280 |
+
ckpt_path=ckpt_path,
|
| 281 |
+
y_only=args.y_only
|
| 282 |
+
)
|
| 283 |
+
if args.mode == 'test':
|
| 284 |
+
if args.report:
|
| 285 |
+
if is_dcr:
|
| 286 |
+
trainer.report_test_dcr(args.num_runs)
|
| 287 |
+
else:
|
| 288 |
+
trainer.report_test(args.num_runs)
|
| 289 |
+
elif args.impute:
|
| 290 |
+
imputed_sample_save_dir = f"impute/{dataname}/{exp_name}"
|
| 291 |
+
trainer.test_impute(
|
| 292 |
+
args.trial_start, args.trial_size,
|
| 293 |
+
args.resample_rounds,
|
| 294 |
+
args.impute_condition,
|
| 295 |
+
imputed_sample_save_dir,
|
| 296 |
+
args.w_num,
|
| 297 |
+
args.w_cat,
|
| 298 |
+
)
|
| 299 |
+
else:
|
| 300 |
+
trainer.test()
|
| 301 |
+
else:
|
| 302 |
+
## Save config
|
| 303 |
+
config_save_path = raw_config['model_save_path']
|
| 304 |
+
with open (os.path.join(config_save_path, 'config.pkl'), 'wb') as f:
|
| 305 |
+
pickle.dump(raw_config, f)
|
| 306 |
+
trainer.run_loop()
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
if __name__ == '__main__':
|
| 311 |
+
|
| 312 |
+
parser = argparse.ArgumentParser(description='Training of TabDiff')
|
| 313 |
+
|
| 314 |
+
parser.add_argument('--dataname', type=str, default='adult', help='Name of dataset.')
|
| 315 |
+
parser.add_argument('--gpu', type=int, default=0, help='GPU index.')
|
| 316 |
+
parser.add_argument('--mode', type=str, default='train', choices=['train', 'test'])
|
| 317 |
+
parser.add_argument('--debug', action='store_true')
|
| 318 |
+
parser.add_argument('--no_wandb', action='store_true')
|
| 319 |
+
parser.add_argument('--deterministic', action='store_true')
|
| 320 |
+
parser.add_argument('--exp_name', type=str, default=None)
|
| 321 |
+
parser.add_argument('--non_learnable_schedule', action='store_true')
|
| 322 |
+
parser.add_argument('--y_only', action='store_true')
|
| 323 |
+
parser.add_argument('--ckpt_path', type=str, default=None)
|
| 324 |
+
parser.add_argument('--num_samples_to_generate', type=int, default=None)
|
| 325 |
+
parser.add_argument('--report', action='store_true')
|
| 326 |
+
parser.add_argument('--num_runs', type=int, default=20)
|
| 327 |
+
parser.add_argument('--impute', action='store_true')
|
| 328 |
+
parser.add_argument('--trial_start', type=int, default=0)
|
| 329 |
+
parser.add_argument('--trial_size', type=int, default=100)
|
| 330 |
+
parser.add_argument('--resample_rounds', type=int, default=1)
|
| 331 |
+
parser.add_argument('--impute_condition', type=str, default='')
|
| 332 |
+
parser.add_argument('--w_num', type=float, default=1.0)
|
| 333 |
+
parser.add_argument('--w_cat', type=float, default=1.0)
|
| 334 |
+
parser.add_argument('--y_only_model_path', type=str, default=None)
|
| 335 |
+
|
| 336 |
+
args = parser.parse_args()
|
| 337 |
+
|
| 338 |
+
# check cuda
|
| 339 |
+
if args.gpu != -1 and torch.cuda.is_available():
|
| 340 |
+
args.device = f'cuda:{args.gpu}'
|
| 341 |
+
else:
|
| 342 |
+
args.device = 'cpu'
|
| 343 |
+
|
| 344 |
+
main(args)
|
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_tabdiff_runtime/tabdiff/metrics.py
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from copy import deepcopy
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch
|
| 4 |
+
import pandas as pd
|
| 5 |
+
# Metrics
|
| 6 |
+
from eval.mle.mle import get_evaluator
|
| 7 |
+
from eval.visualize_density import plot_density
|
| 8 |
+
from sdmetrics.reports.single_table import QualityReport, DiagnosticReport
|
| 9 |
+
from sdmetrics.single_table import LogisticDetection
|
| 10 |
+
from sklearn.preprocessing import OneHotEncoder
|
| 11 |
+
|
| 12 |
+
from tqdm import tqdm
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class TabMetrics(object):
|
| 16 |
+
def __init__(self, real_data_path, test_data_path, val_data_path, info, device, metric_list) -> None:
|
| 17 |
+
self.real_data_path = real_data_path
|
| 18 |
+
self.test_data_path = test_data_path
|
| 19 |
+
self.val_data_path = val_data_path
|
| 20 |
+
self.info = info
|
| 21 |
+
self.device = device
|
| 22 |
+
self.real_data_size = len(pd.read_csv(real_data_path))
|
| 23 |
+
self.metric_list = metric_list
|
| 24 |
+
|
| 25 |
+
def evaluate(self, syn_data):
|
| 26 |
+
metrics, extras = {}, {}
|
| 27 |
+
syn_data_cp = deepcopy(syn_data)
|
| 28 |
+
for metric in self.metric_list:
|
| 29 |
+
func = eval(f"self.evaluate_{metric}")
|
| 30 |
+
print(f"Evaluating {metric}")
|
| 31 |
+
out_metrics, out_extras = func(syn_data_cp)
|
| 32 |
+
metrics.update(out_metrics)
|
| 33 |
+
extras.update(out_extras)
|
| 34 |
+
return metrics, extras
|
| 35 |
+
|
| 36 |
+
def evaluate_density(self, syn_data):
|
| 37 |
+
real_data = pd.read_csv(self.real_data_path)
|
| 38 |
+
real_data.columns = range(len(real_data.columns))
|
| 39 |
+
syn_data.columns = range(len(syn_data.columns))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
info = deepcopy(self.info)
|
| 43 |
+
|
| 44 |
+
y_only = len(syn_data.columns)==1
|
| 45 |
+
if y_only:
|
| 46 |
+
target_col_idx = info['target_col_idx'][0]
|
| 47 |
+
syn_data = self.complete_y_only_data(syn_data, real_data, target_col_idx)
|
| 48 |
+
|
| 49 |
+
metadata = info['metadata']
|
| 50 |
+
metadata['columns'] = {int(key): value for key, value in metadata['columns'].items()} # ensure that keys are all integers?
|
| 51 |
+
|
| 52 |
+
new_real_data, new_syn_data, metadata = reorder(real_data, syn_data, info)
|
| 53 |
+
|
| 54 |
+
qual_report = QualityReport()
|
| 55 |
+
qual_report.generate(new_real_data, new_syn_data, metadata)
|
| 56 |
+
|
| 57 |
+
diag_report = DiagnosticReport()
|
| 58 |
+
diag_report.generate(new_real_data, new_syn_data, metadata)
|
| 59 |
+
|
| 60 |
+
quality = qual_report.get_properties()
|
| 61 |
+
diag = diag_report.get_properties()
|
| 62 |
+
|
| 63 |
+
Shape = quality['Score'][0]
|
| 64 |
+
Trend = quality['Score'][1]
|
| 65 |
+
|
| 66 |
+
Overall = (Shape + Trend) / 2
|
| 67 |
+
|
| 68 |
+
shape_details = qual_report.get_details(property_name='Column Shapes')
|
| 69 |
+
trend_details = qual_report.get_details(property_name='Column Pair Trends')
|
| 70 |
+
|
| 71 |
+
if y_only:
|
| 72 |
+
Shape = shape_details['Score'].min()
|
| 73 |
+
out_metrics = {
|
| 74 |
+
"density/Shape": Shape,
|
| 75 |
+
"density/Trend": Trend,
|
| 76 |
+
"density/Overall": Overall,
|
| 77 |
+
}
|
| 78 |
+
out_extras = {
|
| 79 |
+
"shapes": shape_details,
|
| 80 |
+
"trends": trend_details
|
| 81 |
+
}
|
| 82 |
+
return out_metrics, out_extras
|
| 83 |
+
|
| 84 |
+
def evaluate_mle(self, syn_data):
|
| 85 |
+
train = syn_data.to_numpy()
|
| 86 |
+
test = pd.read_csv(self.test_data_path).to_numpy()
|
| 87 |
+
val = pd.read_csv(self.val_data_path).to_numpy() if self.val_data_path else None
|
| 88 |
+
|
| 89 |
+
info = deepcopy(self.info)
|
| 90 |
+
|
| 91 |
+
task_type = info['task_type']
|
| 92 |
+
|
| 93 |
+
evaluator = get_evaluator(task_type)
|
| 94 |
+
|
| 95 |
+
if task_type == 'regression':
|
| 96 |
+
best_r2_scores, best_rmse_scores = evaluator(train, test, info, val=val)
|
| 97 |
+
|
| 98 |
+
overall_scores = {}
|
| 99 |
+
for score_name in ['best_r2_scores', 'best_rmse_scores']:
|
| 100 |
+
overall_scores[score_name] = {}
|
| 101 |
+
|
| 102 |
+
scores = eval(score_name)
|
| 103 |
+
for method in scores:
|
| 104 |
+
name = method['name']
|
| 105 |
+
method.pop('name')
|
| 106 |
+
overall_scores[score_name][name] = method
|
| 107 |
+
|
| 108 |
+
else:
|
| 109 |
+
best_f1_scores, best_weighted_scores, best_auroc_scores, best_acc_scores, best_avg_scores = evaluator(train, test, info, val=val)
|
| 110 |
+
|
| 111 |
+
overall_scores = {}
|
| 112 |
+
for score_name in ['best_f1_scores', 'best_weighted_scores', 'best_auroc_scores', 'best_acc_scores', 'best_avg_scores']:
|
| 113 |
+
overall_scores[score_name] = {}
|
| 114 |
+
|
| 115 |
+
scores = eval(score_name)
|
| 116 |
+
for method in scores:
|
| 117 |
+
name = method['name']
|
| 118 |
+
method.pop('name')
|
| 119 |
+
overall_scores[score_name][name] = method
|
| 120 |
+
|
| 121 |
+
mle_score = overall_scores['best_rmse_scores']['XGBRegressor']['RMSE'] if task_type == 'regression' else overall_scores['best_auroc_scores']['XGBClassifier']['roc_auc']
|
| 122 |
+
out_metrics = {
|
| 123 |
+
"mle": mle_score,
|
| 124 |
+
}
|
| 125 |
+
out_extras = {
|
| 126 |
+
"mle": overall_scores,
|
| 127 |
+
}
|
| 128 |
+
return out_metrics, out_extras
|
| 129 |
+
|
| 130 |
+
def evaluate_c2st(self, syn_data):
|
| 131 |
+
info = deepcopy(self.info)
|
| 132 |
+
real_data = pd.read_csv(self.real_data_path)
|
| 133 |
+
|
| 134 |
+
real_data.columns = range(len(real_data.columns))
|
| 135 |
+
syn_data.columns = range(len(syn_data.columns))
|
| 136 |
+
|
| 137 |
+
metadata = info['metadata']
|
| 138 |
+
metadata['columns'] = {int(key): value for key, value in metadata['columns'].items()}
|
| 139 |
+
|
| 140 |
+
new_real_data, new_syn_data, metadata = reorder(real_data, syn_data, info)
|
| 141 |
+
|
| 142 |
+
score = LogisticDetection.compute(
|
| 143 |
+
real_data=new_real_data,
|
| 144 |
+
synthetic_data=new_syn_data,
|
| 145 |
+
metadata=metadata
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
out_metrics = {
|
| 149 |
+
"c2st": score,
|
| 150 |
+
}
|
| 151 |
+
out_extras = {}
|
| 152 |
+
return out_metrics, out_extras
|
| 153 |
+
|
| 154 |
+
def evaluate_dcr(self, syn_data):
|
| 155 |
+
info = deepcopy(self.info)
|
| 156 |
+
real_data = pd.read_csv(self.real_data_path)
|
| 157 |
+
test_data = pd.read_csv(self.test_data_path)
|
| 158 |
+
|
| 159 |
+
num_col_idx = info['num_col_idx']
|
| 160 |
+
cat_col_idx = info['cat_col_idx']
|
| 161 |
+
target_col_idx = info['target_col_idx']
|
| 162 |
+
|
| 163 |
+
task_type = info['task_type']
|
| 164 |
+
if task_type == 'regression':
|
| 165 |
+
num_col_idx += target_col_idx
|
| 166 |
+
else:
|
| 167 |
+
cat_col_idx += target_col_idx
|
| 168 |
+
|
| 169 |
+
num_ranges = []
|
| 170 |
+
|
| 171 |
+
real_data.columns = list(np.arange(len(real_data.columns)))
|
| 172 |
+
syn_data.columns = list(np.arange(len(real_data.columns)))
|
| 173 |
+
test_data.columns = list(np.arange(len(real_data.columns)))
|
| 174 |
+
for i in num_col_idx:
|
| 175 |
+
num_ranges.append(real_data[i].max() - real_data[i].min())
|
| 176 |
+
|
| 177 |
+
num_ranges = np.array(num_ranges)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
num_real_data = real_data[num_col_idx]
|
| 181 |
+
cat_real_data = real_data[cat_col_idx]
|
| 182 |
+
num_syn_data = syn_data[num_col_idx]
|
| 183 |
+
cat_syn_data = syn_data[cat_col_idx]
|
| 184 |
+
num_test_data = test_data[num_col_idx]
|
| 185 |
+
cat_test_data = test_data[cat_col_idx]
|
| 186 |
+
|
| 187 |
+
num_real_data_np = num_real_data.to_numpy()
|
| 188 |
+
cat_real_data_np = cat_real_data.to_numpy().astype('str')
|
| 189 |
+
num_syn_data_np = num_syn_data.to_numpy()
|
| 190 |
+
cat_syn_data_np = cat_syn_data.to_numpy().astype('str')
|
| 191 |
+
num_test_data_np = num_test_data.to_numpy()
|
| 192 |
+
cat_test_data_np = cat_test_data.to_numpy().astype('str')
|
| 193 |
+
|
| 194 |
+
encoder = OneHotEncoder()
|
| 195 |
+
cat_complete_data_np = np.concatenate([cat_real_data_np, cat_test_data_np], axis=0)
|
| 196 |
+
encoder.fit(cat_complete_data_np)
|
| 197 |
+
# encoder.fit(cat_real_data_np)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
cat_real_data_oh = encoder.transform(cat_real_data_np).toarray()
|
| 201 |
+
cat_syn_data_oh = encoder.transform(cat_syn_data_np).toarray()
|
| 202 |
+
cat_test_data_oh = encoder.transform(cat_test_data_np).toarray()
|
| 203 |
+
|
| 204 |
+
num_real_data_np = num_real_data_np / num_ranges
|
| 205 |
+
num_syn_data_np = num_syn_data_np / num_ranges
|
| 206 |
+
num_test_data_np = num_test_data_np / num_ranges
|
| 207 |
+
|
| 208 |
+
real_data_np = np.concatenate([num_real_data_np, cat_real_data_oh], axis=1)
|
| 209 |
+
syn_data_np = np.concatenate([num_syn_data_np, cat_syn_data_oh], axis=1)
|
| 210 |
+
test_data_np = np.concatenate([num_test_data_np, cat_test_data_oh], axis=1)
|
| 211 |
+
|
| 212 |
+
device = self.device
|
| 213 |
+
|
| 214 |
+
real_data_th = torch.tensor(real_data_np).to(device)
|
| 215 |
+
syn_data_th = torch.tensor(syn_data_np).to(device)
|
| 216 |
+
test_data_th = torch.tensor(test_data_np).to(device)
|
| 217 |
+
|
| 218 |
+
dcrs_real = []
|
| 219 |
+
dcrs_test = []
|
| 220 |
+
batch_size = 10000 // cat_real_data_oh.shape[1] # This esitmation should make sure that dcr_real and dcr_test can be fit into 10GB GPU memory
|
| 221 |
+
|
| 222 |
+
for i in tqdm(range((syn_data_th.shape[0] // batch_size) + 1)):
|
| 223 |
+
if i != (syn_data_th.shape[0] // batch_size):
|
| 224 |
+
batch_syn_data_th = syn_data_th[i*batch_size: (i+1) * batch_size]
|
| 225 |
+
else:
|
| 226 |
+
batch_syn_data_th = syn_data_th[i*batch_size:]
|
| 227 |
+
|
| 228 |
+
dcr_real = (batch_syn_data_th[:, None] - real_data_th).abs().sum(dim = 2).min(dim = 1).values
|
| 229 |
+
dcr_test = (batch_syn_data_th[:, None] - test_data_th).abs().sum(dim = 2).min(dim = 1).values
|
| 230 |
+
dcrs_real.append(dcr_real)
|
| 231 |
+
dcrs_test.append(dcr_test)
|
| 232 |
+
|
| 233 |
+
dcrs_real = torch.cat(dcrs_real)
|
| 234 |
+
dcrs_test = torch.cat(dcrs_test)
|
| 235 |
+
|
| 236 |
+
score = (dcrs_real < dcrs_test).nonzero().shape[0] / dcrs_real.shape[0]
|
| 237 |
+
|
| 238 |
+
out_metrics = {
|
| 239 |
+
"dcr": score,
|
| 240 |
+
}
|
| 241 |
+
out_extras = {
|
| 242 |
+
"dcr_real": dcrs_real.cpu().numpy(),
|
| 243 |
+
"dcr_test": dcrs_test.cpu().numpy(),
|
| 244 |
+
}
|
| 245 |
+
return out_metrics, out_extras
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def plot_density(self, syn_data):
|
| 249 |
+
syn_data_cp = deepcopy(syn_data)
|
| 250 |
+
real_data = pd.read_csv(self.real_data_path)
|
| 251 |
+
info = deepcopy(self.info)
|
| 252 |
+
y_only = len(syn_data_cp.columns)==1
|
| 253 |
+
if y_only:
|
| 254 |
+
target_col_idx = info['target_col_idx'][0]
|
| 255 |
+
target_col_name = info['column_names'][target_col_idx]
|
| 256 |
+
syn_data_cp = self.complete_y_only_data(syn_data_cp, real_data, target_col_name)
|
| 257 |
+
img = plot_density(syn_data_cp, real_data, info)
|
| 258 |
+
return img
|
| 259 |
+
|
| 260 |
+
def complete_y_only_data(self, syn_data, real_data, target_col_idx):
|
| 261 |
+
syn_target_col = deepcopy(syn_data.iloc[:, 0])
|
| 262 |
+
syn_data = deepcopy(real_data)
|
| 263 |
+
syn_data[target_col_idx] = syn_target_col
|
| 264 |
+
return syn_data
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def reorder(real_data, syn_data, info):
|
| 268 |
+
num_col_idx = deepcopy(info['num_col_idx']) # BUG: info will be modified by += in the next few lines
|
| 269 |
+
cat_col_idx = deepcopy(info['cat_col_idx'])
|
| 270 |
+
target_col_idx = deepcopy(info['target_col_idx'])
|
| 271 |
+
|
| 272 |
+
task_type = info['task_type']
|
| 273 |
+
if task_type == 'regression':
|
| 274 |
+
num_col_idx += target_col_idx
|
| 275 |
+
else:
|
| 276 |
+
cat_col_idx += target_col_idx
|
| 277 |
+
|
| 278 |
+
real_num_data = real_data[num_col_idx]
|
| 279 |
+
real_cat_data = real_data[cat_col_idx]
|
| 280 |
+
|
| 281 |
+
new_real_data = pd.concat([real_num_data, real_cat_data], axis=1)
|
| 282 |
+
new_real_data.columns = range(len(new_real_data.columns))
|
| 283 |
+
|
| 284 |
+
syn_num_data = syn_data[num_col_idx]
|
| 285 |
+
syn_cat_data = syn_data[cat_col_idx]
|
| 286 |
+
|
| 287 |
+
new_syn_data = pd.concat([syn_num_data, syn_cat_data], axis=1)
|
| 288 |
+
new_syn_data.columns = range(len(new_syn_data.columns))
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
metadata = info['metadata']
|
| 292 |
+
|
| 293 |
+
columns = metadata['columns']
|
| 294 |
+
metadata['columns'] = {}
|
| 295 |
+
|
| 296 |
+
inverse_idx_mapping = info['inverse_idx_mapping']
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
for i in range(len(new_real_data.columns)):
|
| 300 |
+
if i < len(num_col_idx):
|
| 301 |
+
metadata['columns'][i] = columns[num_col_idx[i]]
|
| 302 |
+
else:
|
| 303 |
+
metadata['columns'][i] = columns[cat_col_idx[i-len(num_col_idx)]]
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
return new_real_data, new_syn_data, metadata
|
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_tabdiff_runtime/tabdiff/models/noise_schedule.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import abc
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class Noise(abc.ABC, nn.Module):
|
| 8 |
+
"""
|
| 9 |
+
Baseline forward method to get the total + rate of noise at a timestep
|
| 10 |
+
"""
|
| 11 |
+
def forward(self, t):
|
| 12 |
+
# Assume time goes from 0 to 1
|
| 13 |
+
return self.total_noise(t), self.rate_noise(t)
|
| 14 |
+
|
| 15 |
+
@abc.abstractmethod
|
| 16 |
+
def total_noise(self, t):
|
| 17 |
+
"""
|
| 18 |
+
Total noise ie \int_0^t g(t) dt + g(0)
|
| 19 |
+
"""
|
| 20 |
+
pass
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class LogLinearNoise(Noise):
|
| 24 |
+
"""Log Linear noise schedule.
|
| 25 |
+
|
| 26 |
+
"""
|
| 27 |
+
def __init__(self, eps_max=1e-3, eps_min=1e-5, **kwargs):
|
| 28 |
+
super().__init__()
|
| 29 |
+
self.eps_max = eps_max
|
| 30 |
+
self.eps_min = eps_min
|
| 31 |
+
self.sigma_max = self.total_noise(torch.tensor(1.0))
|
| 32 |
+
self.sigma_min = self.total_noise(torch.tensor(0.0))
|
| 33 |
+
|
| 34 |
+
def k(self):
|
| 35 |
+
return torch.tensor(1)
|
| 36 |
+
|
| 37 |
+
def rate_noise(self, t):
|
| 38 |
+
return (1 - self.eps_max - self.eps_min) / (1 - ((1 - self.eps_max - self.eps_min) * t + self.eps_min))
|
| 39 |
+
|
| 40 |
+
def total_noise(self, t):
|
| 41 |
+
"""
|
| 42 |
+
sigma_min=-log(1-eps_min), when t=0
|
| 43 |
+
sigma_max=-log(eps_max), when t=1
|
| 44 |
+
"""
|
| 45 |
+
return -torch.log1p(-((1 - self.eps_max - self.eps_min) * t + self.eps_min))
|
| 46 |
+
|
| 47 |
+
class PowerMeanNoise(Noise):
|
| 48 |
+
"""The noise schedule using the power mean interpolation function.
|
| 49 |
+
|
| 50 |
+
This is the schedule used in EDM
|
| 51 |
+
"""
|
| 52 |
+
def __init__(self, sigma_min=0.002, sigma_max=80, rho=7, **kwargs):
|
| 53 |
+
super().__init__()
|
| 54 |
+
self.sigma_min = sigma_min
|
| 55 |
+
self.sigma_max = sigma_max
|
| 56 |
+
self.raw_rho = rho
|
| 57 |
+
|
| 58 |
+
def rho(self):
|
| 59 |
+
# Return the softplus-transformed rho for all num_numerical values
|
| 60 |
+
return torch.tensor(self.raw_rho)
|
| 61 |
+
|
| 62 |
+
def total_noise(self, t):
|
| 63 |
+
sigma = (self.sigma_min ** (1/self.rho()) + t * (
|
| 64 |
+
self.sigma_max ** (1/self.rho()) - self.sigma_min ** (1/self.rho()))).pow(self.rho())
|
| 65 |
+
return sigma
|
| 66 |
+
|
| 67 |
+
def inverse_to_t(self, sigma):
|
| 68 |
+
t = (sigma.pow(1/self.rho()) - self.sigma_min ** (1/self.rho())) / (self.sigma_max ** (1/self.rho()) - self.sigma_min ** (1/self.rho()))
|
| 69 |
+
return t
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class PowerMeanNoise_PerColumn(nn.Module):
|
| 73 |
+
|
| 74 |
+
def __init__(self, num_numerical, sigma_min=0.002, sigma_max=80, rho_init=1, rho_offset=2, **kwargs):
|
| 75 |
+
super().__init__()
|
| 76 |
+
self.sigma_min = sigma_min
|
| 77 |
+
self.sigma_max = sigma_max
|
| 78 |
+
self.num_numerical = num_numerical
|
| 79 |
+
self.rho_offset = rho_offset
|
| 80 |
+
self.rho_raw = nn.Parameter(torch.tensor([rho_init] * self.num_numerical, dtype=torch.float32))
|
| 81 |
+
|
| 82 |
+
def rho(self):
|
| 83 |
+
# Return the softplus-transformed rho for all num_numerical values
|
| 84 |
+
return nn.functional.softplus(self.rho_raw) + self.rho_offset
|
| 85 |
+
|
| 86 |
+
def total_noise(self, t):
|
| 87 |
+
"""
|
| 88 |
+
Compute total noise for each t in the batch for all num_numerical rhos.
|
| 89 |
+
t: [batch_size]
|
| 90 |
+
Returns: [batch_size, num_numerical]
|
| 91 |
+
"""
|
| 92 |
+
batch_size = t.size(0)
|
| 93 |
+
|
| 94 |
+
rho = self.rho()
|
| 95 |
+
|
| 96 |
+
sigma_min_pow = self.sigma_min ** (1 / rho) # Shape: [num_numerical]
|
| 97 |
+
sigma_max_pow = self.sigma_max ** (1 / rho) # Shape: [num_numerical]
|
| 98 |
+
|
| 99 |
+
sigma = (sigma_min_pow + t * (sigma_max_pow - sigma_min_pow)).pow(rho) # Shape: [batch_size, num_numerical]
|
| 100 |
+
|
| 101 |
+
return sigma
|
| 102 |
+
|
| 103 |
+
def rate_noise(self, t):
|
| 104 |
+
return None
|
| 105 |
+
|
| 106 |
+
def inverse_to_t(self, sigma):
|
| 107 |
+
"""
|
| 108 |
+
Inverse function to map sigma back to t, with proper broadcasting support.
|
| 109 |
+
sigma: [batch_size, num_numerical] or [batch_size, 1]
|
| 110 |
+
Returns: t: [batch_size, num_numerical]
|
| 111 |
+
"""
|
| 112 |
+
rho = self.rho()
|
| 113 |
+
|
| 114 |
+
sigma_min_pow = self.sigma_min ** (1 / rho) # Shape: [num_numerical]
|
| 115 |
+
sigma_max_pow = self.sigma_max ** (1 / rho) # Shape: [num_numerical]
|
| 116 |
+
|
| 117 |
+
# To enable broadcasting between sigma and the per-column rho values, expand rho where needed.
|
| 118 |
+
t = (sigma.pow(1 / rho) - sigma_min_pow) / (sigma_max_pow - sigma_min_pow)
|
| 119 |
+
|
| 120 |
+
return t
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
class LogLinearNoise_PerColumn(nn.Module):
|
| 124 |
+
|
| 125 |
+
def __init__(self, num_categories, eps_max=1e-3, eps_min=1e-5, k_init=-6, k_offset=1, **kwargs):
|
| 126 |
+
|
| 127 |
+
super().__init__()
|
| 128 |
+
self.eps_max = eps_max
|
| 129 |
+
self.eps_min = eps_min
|
| 130 |
+
# Use softplus to ensure k is positive
|
| 131 |
+
self.num_categories = num_categories
|
| 132 |
+
self.k_offset = k_offset
|
| 133 |
+
self.k_raw = nn.Parameter(torch.tensor([k_init] * self.num_categories, dtype=torch.float32))
|
| 134 |
+
|
| 135 |
+
def k(self):
|
| 136 |
+
return torch.nn.functional.softplus(self.k_raw) + self.k_offset
|
| 137 |
+
|
| 138 |
+
def rate_noise(self, t, noise_fn=None):
|
| 139 |
+
"""
|
| 140 |
+
Compute rate noise for all categories with broadcasting.
|
| 141 |
+
t: [batch_size]
|
| 142 |
+
Returns: [batch_size, num_categories]
|
| 143 |
+
"""
|
| 144 |
+
k = self.k() # Shape: [num_categories]
|
| 145 |
+
|
| 146 |
+
numerator = (1 - self.eps_max - self.eps_min) * k * t.pow(k - 1)
|
| 147 |
+
denominator = 1 - ((1 - self.eps_max - self.eps_min) * t.pow(k) + self.eps_min)
|
| 148 |
+
rate = numerator / denominator # Shape: [batch_size, num_categories]
|
| 149 |
+
|
| 150 |
+
return rate
|
| 151 |
+
|
| 152 |
+
def total_noise(self, t, noise_fn=None):
|
| 153 |
+
k = self.k() # Shape: [num_categories]
|
| 154 |
+
|
| 155 |
+
total_noise = -torch.log1p(-((1 - self.eps_max - self.eps_min) * t.pow(k) + self.eps_min))
|
| 156 |
+
|
| 157 |
+
return total_noise
|
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_tabdiff_runtime/tabdiff/models/unified_ctime_diffusion.py
ADDED
|
@@ -0,0 +1,597 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch.nn.functional as F
|
| 2 |
+
import torch
|
| 3 |
+
import math
|
| 4 |
+
import numpy as np
|
| 5 |
+
from tabdiff.models.noise_schedule import *
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
+
from itertools import chain
|
| 8 |
+
|
| 9 |
+
"""
|
| 10 |
+
“Our implementation of the continuous-time masked diffusion is inspired by https://arxiv.org/abs/2406.07524's implementation at [https://github.com/kuleshov-group/mdlm], with modifications to support data distributions that include categorical dimensions of different sizes.”
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
S_churn= 1
|
| 14 |
+
S_min=0
|
| 15 |
+
S_max=float('inf')
|
| 16 |
+
S_noise=1
|
| 17 |
+
|
| 18 |
+
class UnifiedCtimeDiffusion(torch.nn.Module):
|
| 19 |
+
def __init__(
|
| 20 |
+
self,
|
| 21 |
+
num_classes: np.array,
|
| 22 |
+
num_numerical_features: int,
|
| 23 |
+
denoise_fn,
|
| 24 |
+
y_only_model,
|
| 25 |
+
num_timesteps=1000,
|
| 26 |
+
scheduler='power_mean',
|
| 27 |
+
cat_scheduler='log_linear',
|
| 28 |
+
noise_dist='uniform',
|
| 29 |
+
edm_params={},
|
| 30 |
+
noise_dist_params={},
|
| 31 |
+
noise_schedule_params={},
|
| 32 |
+
sampler_params={},
|
| 33 |
+
device=torch.device('cpu'),
|
| 34 |
+
**kwargs
|
| 35 |
+
):
|
| 36 |
+
|
| 37 |
+
super(UnifiedCtimeDiffusion, self).__init__()
|
| 38 |
+
|
| 39 |
+
self.num_numerical_features = num_numerical_features
|
| 40 |
+
self.num_classes = num_classes # it as a vector [K1, K2, ..., Km]
|
| 41 |
+
self.num_classes_expanded = torch.from_numpy(
|
| 42 |
+
np.concatenate([num_classes[i].repeat(num_classes[i]) for i in range(len(num_classes))])
|
| 43 |
+
).to(device) if len(num_classes)>0 else torch.tensor([]).to(device).int()
|
| 44 |
+
self.mask_index = torch.tensor(self.num_classes).long().to(device)
|
| 45 |
+
self.neg_infinity = -1000000.0
|
| 46 |
+
self.num_classes_w_mask = tuple(self.num_classes + 1)
|
| 47 |
+
|
| 48 |
+
offsets = np.cumsum(self.num_classes)
|
| 49 |
+
offsets = np.append([0], offsets)
|
| 50 |
+
self.slices_for_classes = []
|
| 51 |
+
for i in range(1, len(offsets)):
|
| 52 |
+
self.slices_for_classes.append(np.arange(offsets[i - 1], offsets[i]))
|
| 53 |
+
self.offsets = torch.from_numpy(offsets).to(device)
|
| 54 |
+
|
| 55 |
+
offsets = np.cumsum(self.num_classes) + np.arange(1, len(self.num_classes)+1)
|
| 56 |
+
offsets = np.append([0], offsets)
|
| 57 |
+
self.slices_for_classes_with_mask = []
|
| 58 |
+
for i in range(1, len(offsets)):
|
| 59 |
+
self.slices_for_classes_with_mask.append(np.arange(offsets[i - 1], offsets[i]))
|
| 60 |
+
|
| 61 |
+
self._denoise_fn = denoise_fn
|
| 62 |
+
self.y_only_model = y_only_model
|
| 63 |
+
self.num_timesteps = num_timesteps
|
| 64 |
+
self.scheduler = scheduler
|
| 65 |
+
self.cat_scheduler = cat_scheduler
|
| 66 |
+
self.noise_dist = noise_dist
|
| 67 |
+
self.edm_params = edm_params
|
| 68 |
+
self.noise_dist_params = noise_dist_params
|
| 69 |
+
self.sampler_params = sampler_params
|
| 70 |
+
if self.num_numerical_features == 0:
|
| 71 |
+
self.sampler_params['stochastic_sampler'] = False
|
| 72 |
+
self.sampler_params['second_order_correction'] = False
|
| 73 |
+
|
| 74 |
+
self.w_num = 0.0
|
| 75 |
+
self.w_cat = 0.0
|
| 76 |
+
self.num_mask_idx = []
|
| 77 |
+
self.cat_mask_idx = []
|
| 78 |
+
|
| 79 |
+
self.device = device
|
| 80 |
+
|
| 81 |
+
if self.scheduler == 'power_mean':
|
| 82 |
+
self.num_schedule = PowerMeanNoise(**noise_schedule_params)
|
| 83 |
+
elif self.scheduler == 'power_mean_per_column':
|
| 84 |
+
self.num_schedule = PowerMeanNoise_PerColumn(num_numerical = num_numerical_features, **noise_schedule_params)
|
| 85 |
+
else:
|
| 86 |
+
raise NotImplementedError(f"The noise schedule--{self.scheduler}-- is not implemented for contiuous data at CTIME ")
|
| 87 |
+
|
| 88 |
+
if self.cat_scheduler == 'log_linear':
|
| 89 |
+
self.cat_schedule = LogLinearNoise(**noise_schedule_params)
|
| 90 |
+
elif self.cat_scheduler == 'log_linear_per_column':
|
| 91 |
+
self.cat_schedule = LogLinearNoise_PerColumn(num_categories = len(num_classes), **noise_schedule_params)
|
| 92 |
+
else:
|
| 93 |
+
raise NotImplementedError(f"The noise schedule--{self.cat_scheduler}-- is not implemented for discrete data at CTIME ")
|
| 94 |
+
|
| 95 |
+
def mixed_loss(self, x):
|
| 96 |
+
b = x.shape[0]
|
| 97 |
+
device = x.device
|
| 98 |
+
|
| 99 |
+
x_num = x[:, :self.num_numerical_features]
|
| 100 |
+
x_cat = x[:, self.num_numerical_features:].long()
|
| 101 |
+
# Sample noise level
|
| 102 |
+
if self.noise_dist == "uniform_t":
|
| 103 |
+
t = torch.rand(b, device=device, dtype=x_num.dtype)
|
| 104 |
+
t = t[:, None]
|
| 105 |
+
sigma_num = self.num_schedule.total_noise(t)
|
| 106 |
+
sigma_cat = self.cat_schedule.total_noise(t)
|
| 107 |
+
dsigma_cat = self.cat_schedule.rate_noise(t)
|
| 108 |
+
else:
|
| 109 |
+
sigma_num = self.sample_ctime_noise(x)
|
| 110 |
+
t = self.num_schedule.inverse_to_t(sigma_num)
|
| 111 |
+
while torch.any((t < 0) + (t > 1)):
|
| 112 |
+
# restrict t to [0,1]
|
| 113 |
+
# this iterative approach is equivalent to sampling from a truncated version of the orignal noise distribution
|
| 114 |
+
invalid_idx = ((t < 0) + (t > 1)).nonzero().squeeze(-1)
|
| 115 |
+
sigma_num[invalid_idx] = self.sample_ctime_noise(x[:len(invalid_idx)])
|
| 116 |
+
t = self.num_schedule.inverse_to_t(sigma_num)
|
| 117 |
+
assert not torch.any((t < 0) + (t > 1))
|
| 118 |
+
sigma_cat = self.cat_schedule.total_noise(t)
|
| 119 |
+
# Convert sigma_cat to the corresponding alpha and move_chance
|
| 120 |
+
alpha = torch.exp(-sigma_cat)
|
| 121 |
+
move_chance = -torch.expm1(-sigma_cat) # torch.expm1 gives better numertical stability
|
| 122 |
+
|
| 123 |
+
# Continuous forward diff
|
| 124 |
+
x_num_t = x_num
|
| 125 |
+
if x_num.shape[1] > 0:
|
| 126 |
+
noise = torch.randn_like(x_num)
|
| 127 |
+
x_num_t = x_num + noise * sigma_num
|
| 128 |
+
|
| 129 |
+
# Discrete forward diff
|
| 130 |
+
x_cat_t = x_cat
|
| 131 |
+
x_cat_t_soft = x_cat # in the case where x_cat is empty, x_cat_t_soft will have the same shape as x_cat
|
| 132 |
+
if x_cat.shape[1] > 0:
|
| 133 |
+
is_learnable = self.cat_scheduler == 'log_linear_per_column'
|
| 134 |
+
strategy = 'soft'if is_learnable else 'hard'
|
| 135 |
+
x_cat_t, x_cat_t_soft = self.q_xt(x_cat, move_chance, strategy=strategy)
|
| 136 |
+
|
| 137 |
+
# Predict orignal data (distribution)
|
| 138 |
+
model_out_num, model_out_cat = self._denoise_fn(
|
| 139 |
+
x_num_t, x_cat_t_soft,
|
| 140 |
+
t.squeeze(), sigma=sigma_num
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
d_loss = torch.zeros((1,)).float()
|
| 144 |
+
c_loss = torch.zeros((1,)).float()
|
| 145 |
+
|
| 146 |
+
if x_num.shape[1] > 0:
|
| 147 |
+
c_loss = self._edm_loss(model_out_num, x_num, sigma_num)
|
| 148 |
+
if x_cat.shape[1] > 0:
|
| 149 |
+
logits = self._subs_parameterization(model_out_cat, x_cat_t) # log normalized probabilities, with the entry mask category being set to -inf
|
| 150 |
+
d_loss = self._absorbed_closs(logits, x_cat, sigma_cat, dsigma_cat)
|
| 151 |
+
|
| 152 |
+
return d_loss.mean(), c_loss.mean()
|
| 153 |
+
|
| 154 |
+
@torch.no_grad()
|
| 155 |
+
def sample(self, num_samples):
|
| 156 |
+
b = num_samples
|
| 157 |
+
device = self.device
|
| 158 |
+
dtype = torch.float32
|
| 159 |
+
|
| 160 |
+
# Create the chain of t
|
| 161 |
+
t = torch.linspace(0,1,self.num_timesteps, dtype=dtype, device=device) # times = 0.0,...,1.0
|
| 162 |
+
t = t[:, None]
|
| 163 |
+
|
| 164 |
+
# Compute the chains of sigma
|
| 165 |
+
sigma_num_cur = self.num_schedule.total_noise(t)
|
| 166 |
+
sigma_cat_cur = self.cat_schedule.total_noise(t)
|
| 167 |
+
sigma_num_next = torch.zeros_like(sigma_num_cur)
|
| 168 |
+
sigma_num_next[1:] = sigma_num_cur[0:-1]
|
| 169 |
+
sigma_cat_next = torch.zeros_like(sigma_cat_cur)
|
| 170 |
+
sigma_cat_next[1:] = sigma_cat_cur[0:-1]
|
| 171 |
+
|
| 172 |
+
# Prepare sigma_hat for stochastic sampling mode
|
| 173 |
+
if self.sampler_params['stochastic_sampler']:
|
| 174 |
+
gamma = min(S_churn / self.num_timesteps, np.sqrt(2) - 1) * (S_min <= sigma_num_cur) * (sigma_num_cur <= S_max)
|
| 175 |
+
sigma_num_hat = sigma_num_cur + gamma * sigma_num_cur
|
| 176 |
+
t_hat = self.num_schedule.inverse_to_t(sigma_num_hat)
|
| 177 |
+
t_hat = torch.min(t_hat, dim=-1, keepdim=True).values # take the samllest t_hat induced by sigma_num
|
| 178 |
+
zero_gamma = (gamma==0).any()
|
| 179 |
+
t_hat[zero_gamma] = t[zero_gamma]
|
| 180 |
+
out_of_bound = (t_hat > 1).squeeze()
|
| 181 |
+
sigma_num_hat[out_of_bound] = sigma_num_cur[out_of_bound]
|
| 182 |
+
t_hat[out_of_bound] = t[out_of_bound]
|
| 183 |
+
sigma_cat_hat = self.cat_schedule.total_noise(t_hat)
|
| 184 |
+
else:
|
| 185 |
+
t_hat = t
|
| 186 |
+
sigma_num_hat = sigma_num_cur
|
| 187 |
+
sigma_cat_hat = sigma_cat_cur
|
| 188 |
+
|
| 189 |
+
# Sample priors for the continuous dimensions
|
| 190 |
+
z_norm = torch.randn((b, self.num_numerical_features), device=device) * sigma_num_cur[-1]
|
| 191 |
+
|
| 192 |
+
# Sample priors for the discrete dimensions
|
| 193 |
+
has_cat = len(self.num_classes) > 0
|
| 194 |
+
z_cat = torch.zeros((b, 0), device=device).float() # the default values for categorical sample if the dataset has no categorical entry
|
| 195 |
+
if has_cat:
|
| 196 |
+
z_cat = self._sample_masked_prior(
|
| 197 |
+
b,
|
| 198 |
+
len(self.num_classes),
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
pbar = tqdm(reversed(range(0, self.num_timesteps)), total=self.num_timesteps)
|
| 202 |
+
pbar.set_description(f"Sampling Progress")
|
| 203 |
+
for i in pbar:
|
| 204 |
+
z_norm, z_cat, q_xs = self.edm_update(
|
| 205 |
+
z_norm, z_cat, i,
|
| 206 |
+
t[i], t[i-1] if i > 0 else None, t_hat[i],
|
| 207 |
+
sigma_num_cur[i], sigma_num_next[i], sigma_num_hat[i],
|
| 208 |
+
sigma_cat_cur[i], sigma_cat_next[i], sigma_cat_hat[i],
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
assert torch.all(z_cat < self.mask_index)
|
| 212 |
+
sample = torch.cat([z_norm, z_cat], dim=1).cpu()
|
| 213 |
+
return sample
|
| 214 |
+
|
| 215 |
+
def sample_all(self, num_samples, batch_size, keep_nan_samples=False):
|
| 216 |
+
b = batch_size
|
| 217 |
+
|
| 218 |
+
all_samples = []
|
| 219 |
+
num_generated = 0
|
| 220 |
+
while num_generated < num_samples:
|
| 221 |
+
print(f"Samples left to generate: {num_samples-num_generated}")
|
| 222 |
+
sample = self.sample(b)
|
| 223 |
+
mask_nan = torch.any(sample.isnan(), dim=1)
|
| 224 |
+
if keep_nan_samples:
|
| 225 |
+
# If the sample instances that contains Nan are decided to be kept, the row with Nan will be foreced to all zeros
|
| 226 |
+
sample = sample * (~mask_nan)[:, None]
|
| 227 |
+
else:
|
| 228 |
+
# Otherwise the instances with Nan will be eliminated
|
| 229 |
+
sample = sample[~mask_nan]
|
| 230 |
+
|
| 231 |
+
all_samples.append(sample)
|
| 232 |
+
num_generated += sample.shape[0]
|
| 233 |
+
|
| 234 |
+
x_gen = torch.cat(all_samples, dim=0)[:num_samples]
|
| 235 |
+
|
| 236 |
+
return x_gen
|
| 237 |
+
|
| 238 |
+
def q_xt(self, x, move_chance, strategy='hard'):
|
| 239 |
+
"""Computes the noisy sample xt.
|
| 240 |
+
|
| 241 |
+
Args:
|
| 242 |
+
x: int torch.Tensor with shape (batch_size,
|
| 243 |
+
diffusion_model_input_length), input.
|
| 244 |
+
move_chance: float torch.Tensor with shape (batch_size, 1).
|
| 245 |
+
"""
|
| 246 |
+
if strategy == 'hard':
|
| 247 |
+
move_indices = torch.rand(
|
| 248 |
+
* x.shape, device=x.device) < move_chance
|
| 249 |
+
xt = torch.where(move_indices, self.mask_index, x)
|
| 250 |
+
xt_soft = self.to_one_hot(xt).to(move_chance.dtype)
|
| 251 |
+
return xt, xt_soft
|
| 252 |
+
elif strategy == 'soft':
|
| 253 |
+
bs = x.shape[0]
|
| 254 |
+
xt_soft = torch.zeros(bs, torch.sum(self.mask_index+1), device=x.device)
|
| 255 |
+
xt = torch.zeros_like(x)
|
| 256 |
+
for i in range(len(self.num_classes)):
|
| 257 |
+
slice_i = self.slices_for_classes_with_mask[i]
|
| 258 |
+
# set the bernoulli probabilities, which determines the "coin flip" transition to the mask class
|
| 259 |
+
prob_i = torch.zeros(bs, 2, device=x.device)
|
| 260 |
+
prob_i[:,0] = 1-move_chance[:,i]
|
| 261 |
+
prob_i[:,-1] = move_chance[:,i]
|
| 262 |
+
log_prob_i = torch.log(prob_i)
|
| 263 |
+
# draw soft samples and place them back to the corresponding columns
|
| 264 |
+
soft_sample_i = F.gumbel_softmax(log_prob_i, tau=0.01, hard=True)
|
| 265 |
+
idx = torch.stack((x[:,i]+slice_i[0], torch.ones_like(x[:,i])*slice_i[-1]), dim=-1)
|
| 266 |
+
xt_soft[torch.arange(len(idx)).unsqueeze(1), idx] = soft_sample_i
|
| 267 |
+
# retrieve the hard samples
|
| 268 |
+
xt[:, i] = torch.where(soft_sample_i[:,1] > soft_sample_i[:,0], self.mask_index[i], x[:,i])
|
| 269 |
+
return xt, xt_soft
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def _subs_parameterization(self, unormalized_prob, xt):
|
| 273 |
+
# log prob at the mask index = - infinity
|
| 274 |
+
unormalized_prob = self.pad(unormalized_prob, self.neg_infinity)
|
| 275 |
+
|
| 276 |
+
unormalized_prob[:, range(unormalized_prob.shape[1]), self.mask_index] += self.neg_infinity
|
| 277 |
+
|
| 278 |
+
# Take log softmax on the unnormalized probabilities to the logits
|
| 279 |
+
logits = unormalized_prob - torch.logsumexp(unormalized_prob, dim=-1,
|
| 280 |
+
keepdim=True)
|
| 281 |
+
# Apply updates directly in the logits matrix.
|
| 282 |
+
# For the logits of the unmasked tokens, set all values
|
| 283 |
+
# to -infinity except for the indices corresponding to
|
| 284 |
+
# the unmasked tokens.
|
| 285 |
+
unmasked_indices = (xt != self.mask_index) # (bs, K)
|
| 286 |
+
logits[unmasked_indices] = self.neg_infinity
|
| 287 |
+
logits[unmasked_indices, xt[unmasked_indices]] = 0
|
| 288 |
+
return logits
|
| 289 |
+
|
| 290 |
+
def pad(self, x, pad_value):
|
| 291 |
+
"""
|
| 292 |
+
Converts a concatenated tensor of class probabilities into a padded matrix,
|
| 293 |
+
where each sub-tensor is padded along the last dimension to match the largest
|
| 294 |
+
category size (max number of classes).
|
| 295 |
+
|
| 296 |
+
Args:
|
| 297 |
+
x (Tensor): The input tensor containing concatenated probabilities for all the categories in x_cat.
|
| 298 |
+
[bs, sum(num_classes_w_mask)]
|
| 299 |
+
pad_value (float): The value filled into the dummy entries, which are padded to ensure all sub-tensors have equal size
|
| 300 |
+
along the last dimension.
|
| 301 |
+
|
| 302 |
+
Returns:
|
| 303 |
+
Tensor: A new tensorwith
|
| 304 |
+
[bs, len(num_classes_w_mask), max(num_classes_w_mask)), num_categories]
|
| 305 |
+
"""
|
| 306 |
+
splited = torch.split(x, self.num_classes_w_mask, dim=-1)
|
| 307 |
+
max_K = max(self.num_classes_w_mask)
|
| 308 |
+
padded_ = [
|
| 309 |
+
torch.cat((
|
| 310 |
+
t,
|
| 311 |
+
pad_value*torch.ones(*(t.shape[:-1]), max_K-t.shape[-1], dtype=t.dtype, device=t.device)
|
| 312 |
+
), dim=-1)
|
| 313 |
+
for t in splited]
|
| 314 |
+
out = torch.stack(padded_, dim=-2)
|
| 315 |
+
return out
|
| 316 |
+
|
| 317 |
+
def to_one_hot(self, x_cat):
|
| 318 |
+
x_cat_oh = torch.cat(
|
| 319 |
+
[F.one_hot(x_cat[:, i], num_classes=self.num_classes[i]+1,) for i in range(len(self.num_classes))],
|
| 320 |
+
dim=-1
|
| 321 |
+
)
|
| 322 |
+
return x_cat_oh
|
| 323 |
+
|
| 324 |
+
def _absorbed_closs(self, model_output, x0, sigma, dsigma):
|
| 325 |
+
"""
|
| 326 |
+
alpha: (bs,)
|
| 327 |
+
"""
|
| 328 |
+
log_p_theta = torch.gather(
|
| 329 |
+
model_output, -1, x0[:, :, None]
|
| 330 |
+
).squeeze(-1)
|
| 331 |
+
alpha = torch.exp(-sigma)
|
| 332 |
+
if self.cat_scheduler in ['log_linear_unified', 'log_linear_per_column']:
|
| 333 |
+
elbo_weight = - dsigma / torch.expm1(sigma)
|
| 334 |
+
else:
|
| 335 |
+
elbo_weight = -1/(1-alpha)
|
| 336 |
+
|
| 337 |
+
loss = elbo_weight * log_p_theta
|
| 338 |
+
return loss
|
| 339 |
+
|
| 340 |
+
def _sample_masked_prior(self, *batch_dims):
|
| 341 |
+
return self.mask_index[None,:] * torch.ones(
|
| 342 |
+
* batch_dims, dtype=torch.int64, device=self.mask_index.device)
|
| 343 |
+
|
| 344 |
+
def _mdlm_update(self, log_p_x0, x, alpha_t, alpha_s):
|
| 345 |
+
"""
|
| 346 |
+
# t: (bs,)
|
| 347 |
+
log_p_x0: (bs, K, K_max)
|
| 348 |
+
# alpha_t: (bs,)
|
| 349 |
+
# alpha_s: (bs,)
|
| 350 |
+
alpha_t: (bs, 1/K_cat)
|
| 351 |
+
alpha_s: (bs,1/K_cat)
|
| 352 |
+
"""
|
| 353 |
+
move_chance_t = 1 - alpha_t
|
| 354 |
+
move_chance_s = 1 - alpha_s
|
| 355 |
+
move_chance_t = move_chance_t.unsqueeze(-1)
|
| 356 |
+
move_chance_s = move_chance_s.unsqueeze(-1)
|
| 357 |
+
assert move_chance_t.ndim == log_p_x0.ndim
|
| 358 |
+
# Technically, this isn't q_xs since there's a division
|
| 359 |
+
# term that is missing. This division term doesn't affect
|
| 360 |
+
# the samples.
|
| 361 |
+
# There is a noremalizing term is (1-\alpha_t) who's responsility is to ensure q_xs is normalized.
|
| 362 |
+
# However, omiting it won't make a difference for the Gumbel-max sampling trick in _sample_categorical()
|
| 363 |
+
q_xs = log_p_x0.exp() * (move_chance_t
|
| 364 |
+
- move_chance_s)
|
| 365 |
+
q_xs[:, range(q_xs.shape[1]), self.mask_index] = move_chance_s[:, :, 0]
|
| 366 |
+
|
| 367 |
+
# Important: make sure that prob of dummy classes are exactly 0
|
| 368 |
+
dummy_mask = torch.tensor([[(1 if i <= mask_idx else 0) for i in range(max(self.mask_index+1))] for mask_idx in self.mask_index], device=q_xs.device)
|
| 369 |
+
dummy_mask = torch.ones_like(q_xs) * dummy_mask
|
| 370 |
+
q_xs *= dummy_mask
|
| 371 |
+
|
| 372 |
+
_x = self._sample_categorical(q_xs)
|
| 373 |
+
|
| 374 |
+
copy_flag = (x != self.mask_index).to(x.dtype)
|
| 375 |
+
|
| 376 |
+
z_cat = copy_flag * x + (1 - copy_flag) * _x
|
| 377 |
+
return copy_flag * x + (1 - copy_flag) * _x, q_xs
|
| 378 |
+
|
| 379 |
+
def _sample_categorical(self, categorical_probs):
|
| 380 |
+
gumbel_norm = (
|
| 381 |
+
1e-10
|
| 382 |
+
- (torch.rand_like(categorical_probs) + 1e-10).log())
|
| 383 |
+
return (categorical_probs / gumbel_norm).argmax(dim=-1)
|
| 384 |
+
|
| 385 |
+
def sample_ctime_noise(self, batch):
|
| 386 |
+
if self.noise_dist == 'log_norm':
|
| 387 |
+
rnd_normal = torch.randn(batch.shape[0], device=batch.device)
|
| 388 |
+
sigma = (rnd_normal * self.noise_dist_params['P_std'] + self.noise_dist_params['P_mean']).exp()
|
| 389 |
+
else:
|
| 390 |
+
raise NotImplementedError(f"The noise distribution--{self.noise_dist}-- is not implemented for CTIME ")
|
| 391 |
+
return sigma
|
| 392 |
+
|
| 393 |
+
def _edm_loss(self, D_yn, y, sigma):
|
| 394 |
+
weight = (sigma ** 2 + self.edm_params['sigma_data'] ** 2) / (sigma * self.edm_params['sigma_data']) ** 2
|
| 395 |
+
|
| 396 |
+
target = y
|
| 397 |
+
loss = weight * ((D_yn - target) ** 2)
|
| 398 |
+
|
| 399 |
+
return loss
|
| 400 |
+
|
| 401 |
+
def edm_update(
|
| 402 |
+
self, x_num_cur, x_cat_cur, i,
|
| 403 |
+
t_cur, t_next, t_hat,
|
| 404 |
+
sigma_num_cur, sigma_num_next, sigma_num_hat,
|
| 405 |
+
sigma_cat_cur, sigma_cat_next, sigma_cat_hat,
|
| 406 |
+
):
|
| 407 |
+
"""
|
| 408 |
+
i = T-1,...,0
|
| 409 |
+
"""
|
| 410 |
+
cfg = self.y_only_model is not None
|
| 411 |
+
|
| 412 |
+
b = x_num_cur.shape[0]
|
| 413 |
+
has_cat = len(self.num_classes) > 0
|
| 414 |
+
|
| 415 |
+
# Get x_num_hat by move towards the noise by a small step
|
| 416 |
+
x_num_hat = x_num_cur + (sigma_num_hat ** 2 - sigma_num_cur ** 2).sqrt() * S_noise * torch.randn_like(x_num_cur)
|
| 417 |
+
# Get x_cat_hat
|
| 418 |
+
move_chance = -torch.expm1(sigma_cat_cur - sigma_cat_hat) # the incremental move change is 1 - alpha_t/alpha_s = 1 - exp(sigma_s - sigma_t)
|
| 419 |
+
x_cat_hat, _ = self.q_xt(x_cat_cur, move_chance) if has_cat else (x_cat_cur, x_cat_cur)
|
| 420 |
+
|
| 421 |
+
# Get predictions
|
| 422 |
+
x_cat_hat_oh = self.to_one_hot(x_cat_hat).to(x_num_hat.dtype) if has_cat else x_cat_hat
|
| 423 |
+
denoised, raw_logits = self._denoise_fn(
|
| 424 |
+
x_num_hat.float(), x_cat_hat_oh,
|
| 425 |
+
t_hat.squeeze().repeat(b), sigma=sigma_num_hat.unsqueeze(0).repeat(b,1) # sigma accepts (bs, K_num)
|
| 426 |
+
)
|
| 427 |
+
|
| 428 |
+
# Apply cfg updates, if is in cfg mode
|
| 429 |
+
is_bin_class = len(self.num_mask_idx) == 0
|
| 430 |
+
is_learnable = self.scheduler=="power_mean_per_column"
|
| 431 |
+
if cfg:
|
| 432 |
+
if not is_learnable:
|
| 433 |
+
sigma_cond = sigma_num_hat
|
| 434 |
+
else:
|
| 435 |
+
if is_bin_class:
|
| 436 |
+
sigma_cond = (0.002 ** (1/7) + t_hat * (80 ** (1/7) - 0.002 ** (1/7))).pow(7)
|
| 437 |
+
else:
|
| 438 |
+
sigma_cond = sigma_num_hat[self.num_mask_idx]
|
| 439 |
+
y_num_hat = x_num_hat.float()[:, self.num_mask_idx]
|
| 440 |
+
idx = list(chain(*[self.slices_for_classes_with_mask[i] for i in self.cat_mask_idx]))
|
| 441 |
+
y_cat_hat = x_cat_hat_oh[:,idx]
|
| 442 |
+
y_only_denoised, y_only_raw_logits = self.y_only_model(
|
| 443 |
+
y_num_hat,
|
| 444 |
+
y_cat_hat,
|
| 445 |
+
t_hat.squeeze().repeat(b), sigma=sigma_cond.unsqueeze(0).repeat(b,1) # sigma accepts (bs, K_num)
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
denoised[:, self.num_mask_idx] *= 1 + self.w_num
|
| 449 |
+
denoised[:, self.num_mask_idx] -= self.w_num*y_only_denoised
|
| 450 |
+
|
| 451 |
+
mask_logit_idx = [self.slices_for_classes_with_mask[i] for i in self.cat_mask_idx]
|
| 452 |
+
mask_logit_idx = np.concatenate(mask_logit_idx) if len(mask_logit_idx)>0 else np.array([])
|
| 453 |
+
|
| 454 |
+
raw_logits[:, mask_logit_idx] *= 1 + self.w_cat
|
| 455 |
+
raw_logits[:, mask_logit_idx] -= self.w_cat*y_only_raw_logits
|
| 456 |
+
|
| 457 |
+
# Euler step
|
| 458 |
+
d_cur = (x_num_hat - denoised) / sigma_num_hat
|
| 459 |
+
x_num_next = x_num_hat + (sigma_num_next - sigma_num_hat) * d_cur
|
| 460 |
+
|
| 461 |
+
# Unmasking
|
| 462 |
+
x_cat_next = x_cat_cur
|
| 463 |
+
q_xs = torch.zeros_like(x_cat_cur).float()
|
| 464 |
+
if has_cat:
|
| 465 |
+
logits = self._subs_parameterization(raw_logits, x_cat_hat)
|
| 466 |
+
alpha_t = torch.exp(-sigma_cat_hat).unsqueeze(0).repeat(b,1)
|
| 467 |
+
alpha_s = torch.exp(-sigma_cat_next).unsqueeze(0).repeat(b,1)
|
| 468 |
+
x_cat_next, q_xs = self._mdlm_update(logits, x_cat_hat, alpha_t, alpha_s)
|
| 469 |
+
|
| 470 |
+
# Apply 2nd order correction.
|
| 471 |
+
if self.sampler_params['second_order_correction']:
|
| 472 |
+
if i > 0:
|
| 473 |
+
x_cat_hat_oh = self.to_one_hot(x_cat_hat).to(x_num_next.dtype) if has_cat else x_cat_hat
|
| 474 |
+
denoised, raw_logits = self._denoise_fn(
|
| 475 |
+
x_num_next.float(), x_cat_hat_oh,
|
| 476 |
+
t_next.squeeze().repeat(b), sigma=sigma_num_next.unsqueeze(0).repeat(b,1)
|
| 477 |
+
)
|
| 478 |
+
if cfg:
|
| 479 |
+
if not is_learnable:
|
| 480 |
+
sigma_cond = sigma_num_next
|
| 481 |
+
else:
|
| 482 |
+
if is_bin_class:
|
| 483 |
+
sigma_cond = (0.002 ** (1/7) + t_next * (80 ** (1/7) - 0.002 ** (1/7))).pow(7)
|
| 484 |
+
else:
|
| 485 |
+
sigma_cond = sigma_num_next[self.num_mask_idx]
|
| 486 |
+
y_num_next = x_num_next.float()[:, self.num_mask_idx]
|
| 487 |
+
idx = list(chain(*[self.slices_for_classes_with_mask[i] for i in self.cat_mask_idx]))
|
| 488 |
+
y_cat_hat = x_cat_hat_oh[:, idx]
|
| 489 |
+
y_only_denoised, y_only_raw_logits = self.y_only_model(
|
| 490 |
+
y_num_next,
|
| 491 |
+
y_cat_hat,
|
| 492 |
+
t_next.squeeze().repeat(b), sigma=sigma_cond.unsqueeze(0).repeat(b,1) # sigma accepts (bs, K_num)
|
| 493 |
+
)
|
| 494 |
+
denoised[:, self.num_mask_idx] *= 1 + self.w_num
|
| 495 |
+
denoised[:, self.num_mask_idx] -= self.w_num*y_only_denoised
|
| 496 |
+
|
| 497 |
+
d_prime = (x_num_next - denoised) / sigma_num_next
|
| 498 |
+
x_num_next = x_num_hat + (sigma_num_next - sigma_num_hat) * (0.5 * d_cur + 0.5 * d_prime)
|
| 499 |
+
|
| 500 |
+
return x_num_next, x_cat_next, q_xs
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
def sample_impute(self, x_num, x_cat, num_mask_idx, cat_mask_idx, resample_rounds, impute_condition, w_num, w_cat):
|
| 504 |
+
self.w_num = w_num
|
| 505 |
+
self.w_cat = w_cat
|
| 506 |
+
self.num_mask_idx = num_mask_idx
|
| 507 |
+
self.cat_mask_idx = cat_mask_idx
|
| 508 |
+
|
| 509 |
+
b = x_num.size(0)
|
| 510 |
+
device = self.device
|
| 511 |
+
dtype = torch.float32
|
| 512 |
+
|
| 513 |
+
# Create masks, true for the missing columns
|
| 514 |
+
num_mask = [i in num_mask_idx for i in range(self.num_numerical_features)]
|
| 515 |
+
cat_mask = [i in cat_mask_idx for i in range(len(self.num_classes))]
|
| 516 |
+
num_mask = torch.tensor(num_mask).to(x_num.device).to(x_num.dtype)
|
| 517 |
+
cat_mask = torch.tensor(cat_mask).to(x_cat.device).to(x_cat.dtype)
|
| 518 |
+
|
| 519 |
+
# Create the chain of t
|
| 520 |
+
t = torch.linspace(0,1,self.num_timesteps, dtype=dtype, device=device) # times = 0.0,...,1.0
|
| 521 |
+
t = t[:, None]
|
| 522 |
+
|
| 523 |
+
# Compute the chains of sigma
|
| 524 |
+
sigma_num_cur = self.num_schedule.total_noise(t)
|
| 525 |
+
sigma_cat_cur = self.cat_schedule.total_noise(t)
|
| 526 |
+
sigma_num_next = torch.zeros_like(sigma_num_cur)
|
| 527 |
+
sigma_num_next[1:] = sigma_num_cur[0:-1]
|
| 528 |
+
sigma_cat_next = torch.zeros_like(sigma_cat_cur)
|
| 529 |
+
sigma_cat_next[1:] = sigma_cat_cur[0:-1]
|
| 530 |
+
|
| 531 |
+
# Prepare sigma_hat for stochastic sampling mode
|
| 532 |
+
if self.sampler_params['stochastic_sampler']:
|
| 533 |
+
gamma = min(S_churn / self.num_timesteps, np.sqrt(2) - 1) * (S_min <= sigma_num_cur) * (sigma_num_cur <= S_max)
|
| 534 |
+
sigma_num_hat = sigma_num_cur + gamma * sigma_num_cur
|
| 535 |
+
t_hat = self.num_schedule.inverse_to_t(sigma_num_hat)
|
| 536 |
+
t_hat = torch.min(t_hat, dim=-1, keepdim=True).values # take the samllest t_hat induced by sigma_num
|
| 537 |
+
zero_gamma = (gamma==0).any()
|
| 538 |
+
t_hat[zero_gamma] = t[zero_gamma]
|
| 539 |
+
out_of_bound = (t_hat > 1).squeeze()
|
| 540 |
+
sigma_num_hat[out_of_bound] = sigma_num_cur[out_of_bound]
|
| 541 |
+
t_hat[out_of_bound] = t[out_of_bound]
|
| 542 |
+
sigma_cat_hat = self.cat_schedule.total_noise(t_hat)
|
| 543 |
+
else:
|
| 544 |
+
t_hat = t
|
| 545 |
+
sigma_num_hat = sigma_num_cur
|
| 546 |
+
sigma_cat_hat = sigma_cat_cur
|
| 547 |
+
|
| 548 |
+
# Sample priors for the continuous dimensions
|
| 549 |
+
if impute_condition == "x_t":
|
| 550 |
+
z_norm = x_num + torch.randn((b, self.num_numerical_features), device=device) * sigma_num_cur[-1] # z_{t_max} = x_0(masked) + sigma_max*epsilon
|
| 551 |
+
elif impute_condition == "x_0":
|
| 552 |
+
z_norm = x_num
|
| 553 |
+
|
| 554 |
+
# Sample priors for the discrete dimensions
|
| 555 |
+
has_cat = len(self.num_classes) > 0
|
| 556 |
+
z_cat = torch.zeros((b, 0), device=device).float() # the default values for categorical sample if the dataset has no categorical entry
|
| 557 |
+
if has_cat:
|
| 558 |
+
if impute_condition == "x_t":
|
| 559 |
+
z_cat = self._sample_masked_prior(
|
| 560 |
+
b,
|
| 561 |
+
len(self.num_classes),
|
| 562 |
+
) # z_{t_max} is still all pushed to [MASK]
|
| 563 |
+
elif impute_condition == "x_0":
|
| 564 |
+
z_cat = x_cat
|
| 565 |
+
|
| 566 |
+
pbar = tqdm(reversed(range(0, self.num_timesteps)), total=self.num_timesteps)
|
| 567 |
+
pbar.set_description(f"Sampling Progress")
|
| 568 |
+
for i in pbar:
|
| 569 |
+
for u in range (resample_rounds):
|
| 570 |
+
# Get known parts by Forward Flow
|
| 571 |
+
if impute_condition == "x_t":
|
| 572 |
+
z_norm_known = x_num + torch.randn((b, self.num_numerical_features), device=device) * sigma_num_next[i]
|
| 573 |
+
move_chance = 1 - torch.exp(-sigma_cat_next[i]) if i < (self.num_timesteps-1) else torch.ones_like(sigma_cat_next[i]) # force move_chance to be 1 for the first iteration
|
| 574 |
+
z_cat_known, _ = self.q_xt(x_cat, move_chance)
|
| 575 |
+
elif impute_condition == "x_0":
|
| 576 |
+
z_norm_known = x_num
|
| 577 |
+
z_cat_known = x_cat
|
| 578 |
+
|
| 579 |
+
# Get unknown by Reverse Step
|
| 580 |
+
z_norm_unknown, z_cat_unknown, q_xs = self.edm_update(
|
| 581 |
+
z_norm, z_cat, i,
|
| 582 |
+
t[i], t[i-1] if i > 0 else None, t_hat[i],
|
| 583 |
+
sigma_num_cur[i], sigma_num_next[i], sigma_num_hat[i],
|
| 584 |
+
sigma_cat_cur[i], sigma_cat_next[i], sigma_cat_hat[i],
|
| 585 |
+
)
|
| 586 |
+
z_norm = (1 - num_mask) * z_norm_known + num_mask * z_norm_unknown
|
| 587 |
+
z_cat = (1 - cat_mask) * z_cat_known + cat_mask * z_cat_unknown
|
| 588 |
+
|
| 589 |
+
# Resample x_t from x_{t-1} by Foward Step
|
| 590 |
+
if u < resample_rounds-1:
|
| 591 |
+
z_norm = z_norm + (sigma_num_cur[i] ** 2 - sigma_num_next[i] ** 2).sqrt() * S_noise * torch.randn_like(z_norm)
|
| 592 |
+
move_chance = -torch.expm1(sigma_cat_next[i] - sigma_cat_cur[i])
|
| 593 |
+
z_cat, _ = self.q_xt(z_cat, move_chance)
|
| 594 |
+
|
| 595 |
+
sample = torch.cat([z_norm, z_cat], dim=1).cpu()
|
| 596 |
+
return sample
|
| 597 |
+
|
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_tabdiff_runtime/tabdiff/modules/main_modules.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Callable, Union
|
| 2 |
+
|
| 3 |
+
from tabdiff.modules.transformer import Reconstructor, Tokenizer, Transformer
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch.optim
|
| 7 |
+
|
| 8 |
+
ModuleType = Union[str, Callable[..., nn.Module]]
|
| 9 |
+
|
| 10 |
+
class SiLU(nn.Module):
|
| 11 |
+
def forward(self, x):
|
| 12 |
+
return x * torch.sigmoid(x)
|
| 13 |
+
|
| 14 |
+
class PositionalEmbedding(torch.nn.Module):
|
| 15 |
+
def __init__(self, num_channels, max_positions=10000, endpoint=False):
|
| 16 |
+
super().__init__()
|
| 17 |
+
self.num_channels = num_channels
|
| 18 |
+
self.max_positions = max_positions
|
| 19 |
+
self.endpoint = endpoint
|
| 20 |
+
|
| 21 |
+
def forward(self, x):
|
| 22 |
+
freqs = torch.arange(start=0, end=self.num_channels//2, dtype=torch.float32, device=x.device)
|
| 23 |
+
freqs = freqs / (self.num_channels // 2 - (1 if self.endpoint else 0))
|
| 24 |
+
freqs = (1 / self.max_positions) ** freqs
|
| 25 |
+
x = x.ger(freqs.to(x.dtype))
|
| 26 |
+
x = torch.cat([x.cos(), x.sin()], dim=1)
|
| 27 |
+
return x
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class MLPDiffusion(nn.Module):
|
| 31 |
+
def __init__(self, d_in, dim_t = 512, use_mlp=True):
|
| 32 |
+
super().__init__()
|
| 33 |
+
self.dim_t = dim_t
|
| 34 |
+
|
| 35 |
+
self.proj = nn.Linear(d_in, dim_t)
|
| 36 |
+
|
| 37 |
+
self.mlp = nn.Sequential(
|
| 38 |
+
nn.Linear(dim_t, dim_t * 2),
|
| 39 |
+
nn.SiLU(),
|
| 40 |
+
nn.Linear(dim_t * 2, dim_t * 2),
|
| 41 |
+
nn.SiLU(),
|
| 42 |
+
nn.Linear(dim_t * 2, dim_t),
|
| 43 |
+
nn.SiLU(),
|
| 44 |
+
nn.Linear(dim_t, d_in),
|
| 45 |
+
) if use_mlp else nn.Linear(dim_t, d_in)
|
| 46 |
+
|
| 47 |
+
self.map_noise = PositionalEmbedding(num_channels=dim_t)
|
| 48 |
+
self.time_embed = nn.Sequential(
|
| 49 |
+
nn.Linear(dim_t, dim_t),
|
| 50 |
+
nn.SiLU(),
|
| 51 |
+
nn.Linear(dim_t, dim_t)
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
self.use_mlp = use_mlp
|
| 55 |
+
|
| 56 |
+
def forward(self, x, timesteps):
|
| 57 |
+
emb = self.map_noise(timesteps)
|
| 58 |
+
emb = emb.reshape(emb.shape[0], 2, -1).flip(1).reshape(*emb.shape) # swap sin/cos
|
| 59 |
+
emb = self.time_embed(emb)
|
| 60 |
+
|
| 61 |
+
x = self.proj(x) + emb
|
| 62 |
+
return self.mlp(x)
|
| 63 |
+
|
| 64 |
+
class UniModMLP(nn.Module):
|
| 65 |
+
"""
|
| 66 |
+
Input:
|
| 67 |
+
x_num: [bs, d_numerical]
|
| 68 |
+
x_cat: [bs, len(categories)]
|
| 69 |
+
Output:
|
| 70 |
+
x_num_pred: [bs, d_numerical], the predicted mean for numerical data
|
| 71 |
+
x_cat_pred: [bs, sum(categories)], the predicted UNORMALIZED logits for categorical data
|
| 72 |
+
"""
|
| 73 |
+
def __init__(
|
| 74 |
+
self, d_numerical, categories, num_layers, d_token,
|
| 75 |
+
n_head = 1, factor = 4, bias = True, dim_t=512, use_mlp=True, **kwargs
|
| 76 |
+
):
|
| 77 |
+
super().__init__()
|
| 78 |
+
self.d_numerical = d_numerical
|
| 79 |
+
self.categories = categories
|
| 80 |
+
|
| 81 |
+
self.tokenizer = Tokenizer(d_numerical, categories, d_token, bias = bias)
|
| 82 |
+
self.encoder = Transformer(num_layers, d_token, n_head, d_token, factor)
|
| 83 |
+
d_in = d_token * (d_numerical + len(categories))
|
| 84 |
+
self.mlp = MLPDiffusion(d_in, dim_t=dim_t, use_mlp=use_mlp)
|
| 85 |
+
self.decoder = Transformer(num_layers, d_token, n_head, d_token, factor)
|
| 86 |
+
self.detokenizer = Reconstructor(d_numerical, categories, d_token)
|
| 87 |
+
|
| 88 |
+
self.model = nn.ModuleList([self.tokenizer, self.encoder, self.mlp, self.decoder, self.detokenizer])
|
| 89 |
+
|
| 90 |
+
def forward(self, x_num, x_cat, timesteps):
|
| 91 |
+
e = self.tokenizer(x_num, x_cat)
|
| 92 |
+
decoder_input = e[:, 1:, :] # ignore the first CLS token.
|
| 93 |
+
y = self.encoder(decoder_input)
|
| 94 |
+
pred_y = self.mlp(y.reshape(y.shape[0], -1), timesteps)
|
| 95 |
+
pred_e = self.decoder(pred_y.reshape(*y.shape))
|
| 96 |
+
x_num_pred, x_cat_pred = self.detokenizer(pred_e)
|
| 97 |
+
x_cat_pred = torch.cat(x_cat_pred, dim=-1) if len(x_cat_pred)>0 else torch.zeros_like(x_cat).to(x_num_pred.dtype)
|
| 98 |
+
|
| 99 |
+
return x_num_pred, x_cat_pred
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class Precond(nn.Module):
|
| 103 |
+
def __init__(self,
|
| 104 |
+
denoise_fn,
|
| 105 |
+
sigma_data = 0.5, # Expected standard deviation of the training data.
|
| 106 |
+
net_conditioning = "sigma",
|
| 107 |
+
):
|
| 108 |
+
super().__init__()
|
| 109 |
+
self.sigma_data = sigma_data
|
| 110 |
+
self.net_conditioning = net_conditioning
|
| 111 |
+
self.denoise_fn_F = denoise_fn
|
| 112 |
+
|
| 113 |
+
def forward(self, x_num, x_cat, t, sigma):
|
| 114 |
+
|
| 115 |
+
x_num = x_num.to(torch.float32)
|
| 116 |
+
|
| 117 |
+
sigma = sigma.to(torch.float32)
|
| 118 |
+
assert sigma.ndim == 2
|
| 119 |
+
if sigma.dim() > 1: # if learnable column-wise noise schedule, sigma conditioning is set to the defaults schedule of rho=7
|
| 120 |
+
sigma_cond = (0.002 ** (1/7) + t * (80 ** (1/7) - 0.002 ** (1/7))).pow(7)
|
| 121 |
+
else:
|
| 122 |
+
sigma_cond = sigma
|
| 123 |
+
dtype = torch.float32
|
| 124 |
+
|
| 125 |
+
c_skip = self.sigma_data ** 2 / (sigma ** 2 + self.sigma_data ** 2)
|
| 126 |
+
c_out = sigma * self.sigma_data / (sigma ** 2 + self.sigma_data ** 2).sqrt()
|
| 127 |
+
c_in = 1 / (self.sigma_data ** 2 + sigma ** 2).sqrt()
|
| 128 |
+
c_noise = sigma_cond.log() / 4
|
| 129 |
+
|
| 130 |
+
x_in = c_in * x_num
|
| 131 |
+
if self.net_conditioning == "sigma":
|
| 132 |
+
F_x, x_cat_pred = self.denoise_fn_F(x_in, x_cat, c_noise.flatten())
|
| 133 |
+
elif self.net_conditioning == "t":
|
| 134 |
+
F_x, x_cat_pred = self.denoise_fn_F(x_in, x_cat, t)
|
| 135 |
+
|
| 136 |
+
assert F_x.dtype == dtype
|
| 137 |
+
D_x = c_skip * x_num + c_out * F_x.to(torch.float32)
|
| 138 |
+
|
| 139 |
+
return D_x, x_cat_pred
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class Model(nn.Module):
|
| 143 |
+
def __init__(
|
| 144 |
+
self, denoise_fn,
|
| 145 |
+
sigma_data=0.5,
|
| 146 |
+
precond=False,
|
| 147 |
+
net_conditioning="sigma",
|
| 148 |
+
**kwargs
|
| 149 |
+
):
|
| 150 |
+
super().__init__()
|
| 151 |
+
self.precond = precond
|
| 152 |
+
if precond:
|
| 153 |
+
self.denoise_fn_D = Precond(
|
| 154 |
+
denoise_fn,
|
| 155 |
+
sigma_data=sigma_data,
|
| 156 |
+
net_conditioning=net_conditioning
|
| 157 |
+
)
|
| 158 |
+
else:
|
| 159 |
+
self.denoise_fn_D = denoise_fn
|
| 160 |
+
|
| 161 |
+
def forward(self, x_num, x_cat, t, sigma=None):
|
| 162 |
+
if self.precond:
|
| 163 |
+
return self.denoise_fn_D(x_num, x_cat, t, sigma)
|
| 164 |
+
else:
|
| 165 |
+
return self.denoise_fn_D(x_num, x_cat, t)
|
| 166 |
+
|
| 167 |
+
|
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/_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_051642/_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_051642/_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_051642/_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_051642/tabular_bundle/pipeline_n11"
|
| 6 |
+
rt = r"/work/output-Benchmark-trainonly-v1/n11/tabdiff/tabdiff-n11-20260521_051642/_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"] = "800"
|
| 64 |
+
os.environ["TABDIFF_STEPS"] = "800"
|
| 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.0005"
|
| 69 |
+
os.environ["TABDIFF_LEARNING_RATE"] = "0.0005"
|
| 70 |
+
os.environ["TABDIFF_NUM_TIMESTEPS"] = "50"
|
| 71 |
+
os.environ["TABDIFF_TIMESTEPS"] = "50"
|
| 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_051642/bo_combo.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d37a51ffaead2135bc00a1fcf46dba603bdd155db5a1b8825145bf6752cd7295
|
| 3 |
+
size 125
|
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/gen_20260521_053144.log
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d72dc4ea01ab55238a60b5c117ce26c12312b79c88530c72afea059156766521
|
| 3 |
+
size 20387
|
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/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_051642/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_051642/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_051642/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_051642/public_gate/staged_input_manifest.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:32d9c1a9eafb6c20f6b23d6b217a5ddfde71b19c8ae9e59dea50d011a252d99b
|
| 3 |
+
size 6099
|
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/run_config.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:897059ca6095e411a9cd7d8dce6a5acbafa461b766807ba300b2c5dc45e720cf
|
| 3 |
+
size 2433
|
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/runtime_result.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8b7f66df6e8dda0dbfd932327610396f9401f78a22d4472e3317547668906426
|
| 3 |
+
size 915
|
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/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_051642/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_051642/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_051642/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_051642/staged/tabdiff/adapter_report.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cd0d98b50a84988c33f6fa6e22b6e80992b440b8fab4e7b067a84e72b72ad321
|
| 3 |
+
size 323
|
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/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_051642/staged/tabdiff/model_input_manifest.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0e3296beeba05b6b8688d4f5d2d1e14a40e1f9dab65700c6ff669c3560095cff
|
| 3 |
+
size 6298
|
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/tabdiff-n11-15215-20260521_053144.csv
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:61845644c05fdf5b2162f1dcc1ce55cbd87ab15a117e1c82de8f3be4cc95156c
|
| 3 |
+
size 1556916
|
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/tabdiff_train_meta.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:19e8c8193f6d065da2531a02d4a36c0f067daa5ae4c8c346b118fa2799a8a172
|
| 3 |
+
size 534
|
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_051642/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_051642/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_051642/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_051642/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_051642/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_051642/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_051642/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_051642/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_051642/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_051642/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_051642/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_051642/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_051642/train_20260521_051643.log
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5da1d3b70e43c003d4edbc75a11899ec8174fa5a06d49fa2642c63774d4b79ee
|
| 3 |
+
size 5034188
|
SynthData0523/hyper_parameter_tuning/n11/tabdiff/runs/tabdiff-n11-20260521_053348/_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_053348/tabular_bundle/pipeline_n11"
|
| 6 |
+
rt = r"/work/output-Benchmark-trainonly-v1/n11/tabdiff/tabdiff-n11-20260521_053348/_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_053348/_tabdiff_runtime/tabdiff/ckpt/pipeline_n11/adapter_learnable/model_800.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_053348/tabdiff-n11-15215-20260521_054153.csv")
|