TabQueryBench commited on
Commit
40b3396
·
verified ·
1 Parent(s): 60da973

Resume SynthData0523 main/c19 batch 4

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +29 -0
  2. SynthData0523/main/c19/realtabformer/rtf-c19-20260513_062753/train_20260513_062755.log +3 -0
  3. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/.gitignore +174 -0
  4. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/LICENCE +7 -0
  5. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/README.md +128 -0
  6. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/X_cat_test.npy +3 -0
  7. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/X_cat_train.npy +3 -0
  8. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/X_cat_val.npy +3 -0
  9. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/X_num_test.npy +3 -0
  10. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/X_num_train.npy +3 -0
  11. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/X_num_val.npy +3 -0
  12. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/info.json +3 -0
  13. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/real.csv +3 -0
  14. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/staged_features.json +3 -0
  15. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/test.csv +3 -0
  16. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/train.csv +3 -0
  17. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/val.csv +3 -0
  18. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/y_test.npy +3 -0
  19. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/y_train.npy +3 -0
  20. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/y_val.npy +3 -0
  21. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/download_dataset.py +49 -0
  22. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/ckpt/pipeline_c19/adapter_efvfm/config.pkl +3 -0
  23. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/ckpt/pipeline_c19/adapter_efvfm/ema_model_100.pt +3 -0
  24. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/ckpt/pipeline_c19/adapter_efvfm/model_100.pt +3 -0
  25. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/configs/ef_vfm_configs.toml +3 -0
  26. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/main.py +246 -0
  27. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/metrics.py +306 -0
  28. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/models/flow_model.py +195 -0
  29. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/modules/main_modules.py +102 -0
  30. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/modules/transformer.py +269 -0
  31. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/result/pipeline_c19/adapter_efvfm/100/all_results.json +3 -0
  32. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/result/pipeline_c19/adapter_efvfm/100/ema/all_results.json +3 -0
  33. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/result/pipeline_c19/adapter_efvfm/100/ema/samples.csv +3 -0
  34. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/result/pipeline_c19/adapter_efvfm/100/ema/shapes.csv +3 -0
  35. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/result/pipeline_c19/adapter_efvfm/100/ema/trends.csv +3 -0
  36. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/result/pipeline_c19/adapter_efvfm/100/samples.csv +3 -0
  37. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/result/pipeline_c19/adapter_efvfm/100/shapes.csv +3 -0
  38. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/result/pipeline_c19/adapter_efvfm/100/trends.csv +3 -0
  39. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/trainer.py +557 -0
  40. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/eval/eval_quality.py +149 -0
  41. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/eval/mle/mle.py +781 -0
  42. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/eval/mle/tabular_dataload.py +111 -0
  43. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/eval/mle/tabular_transformer.py +110 -0
  44. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/eval/visualize_density.py +85 -0
  45. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/images/demo.jpg +3 -0
  46. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/images/demo.pdf +3 -0
  47. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/main.py +32 -0
  48. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/process_dataset.py +492 -0
  49. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/pyproject.toml +3 -0
  50. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/src/__init__.py +11 -0
.gitattributes CHANGED
@@ -2790,3 +2790,32 @@ SynthData0523/main/c19/realtabformer/rtf-c19-20260513_062753/staged/public/val.c
2790
  SynthData0523/main/c19/realtabformer/rtf-c19-20260513_062753/staged/realtabformer/adapter_report.json filter=lfs diff=lfs merge=lfs -text
2791
  SynthData0523/main/c19/realtabformer/rtf-c19-20260513_062753/staged/realtabformer/adapter_transforms_applied.json filter=lfs diff=lfs merge=lfs -text
2792
  SynthData0523/main/c19/realtabformer/rtf-c19-20260513_062753/staged/realtabformer/model_input_manifest.json filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2790
  SynthData0523/main/c19/realtabformer/rtf-c19-20260513_062753/staged/realtabformer/adapter_report.json filter=lfs diff=lfs merge=lfs -text
2791
  SynthData0523/main/c19/realtabformer/rtf-c19-20260513_062753/staged/realtabformer/adapter_transforms_applied.json filter=lfs diff=lfs merge=lfs -text
2792
  SynthData0523/main/c19/realtabformer/rtf-c19-20260513_062753/staged/realtabformer/model_input_manifest.json filter=lfs diff=lfs merge=lfs -text
2793
+ SynthData0523/main/c19/realtabformer/rtf-c19-20260513_062753/train_20260513_062755.log filter=lfs diff=lfs merge=lfs -text
2794
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/X_cat_test.npy filter=lfs diff=lfs merge=lfs -text
2795
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/X_cat_train.npy filter=lfs diff=lfs merge=lfs -text
2796
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/X_cat_val.npy filter=lfs diff=lfs merge=lfs -text
2797
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/X_num_test.npy filter=lfs diff=lfs merge=lfs -text
2798
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/X_num_train.npy filter=lfs diff=lfs merge=lfs -text
2799
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/X_num_val.npy filter=lfs diff=lfs merge=lfs -text
2800
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/info.json filter=lfs diff=lfs merge=lfs -text
2801
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/real.csv filter=lfs diff=lfs merge=lfs -text
2802
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/staged_features.json filter=lfs diff=lfs merge=lfs -text
2803
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/test.csv filter=lfs diff=lfs merge=lfs -text
2804
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/train.csv filter=lfs diff=lfs merge=lfs -text
2805
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/val.csv filter=lfs diff=lfs merge=lfs -text
2806
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/y_test.npy filter=lfs diff=lfs merge=lfs -text
2807
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/y_train.npy filter=lfs diff=lfs merge=lfs -text
2808
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/y_val.npy filter=lfs diff=lfs merge=lfs -text
2809
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/ckpt/pipeline_c19/adapter_efvfm/config.pkl filter=lfs diff=lfs merge=lfs -text
2810
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/ckpt/pipeline_c19/adapter_efvfm/ema_model_100.pt filter=lfs diff=lfs merge=lfs -text
2811
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/ckpt/pipeline_c19/adapter_efvfm/model_100.pt filter=lfs diff=lfs merge=lfs -text
2812
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/configs/ef_vfm_configs.toml filter=lfs diff=lfs merge=lfs -text
2813
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/result/pipeline_c19/adapter_efvfm/100/all_results.json filter=lfs diff=lfs merge=lfs -text
2814
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/result/pipeline_c19/adapter_efvfm/100/ema/all_results.json filter=lfs diff=lfs merge=lfs -text
2815
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/result/pipeline_c19/adapter_efvfm/100/ema/samples.csv filter=lfs diff=lfs merge=lfs -text
2816
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/result/pipeline_c19/adapter_efvfm/100/ema/shapes.csv filter=lfs diff=lfs merge=lfs -text
2817
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/result/pipeline_c19/adapter_efvfm/100/ema/trends.csv filter=lfs diff=lfs merge=lfs -text
2818
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/result/pipeline_c19/adapter_efvfm/100/samples.csv filter=lfs diff=lfs merge=lfs -text
2819
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/result/pipeline_c19/adapter_efvfm/100/shapes.csv filter=lfs diff=lfs merge=lfs -text
2820
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/result/pipeline_c19/adapter_efvfm/100/trends.csv filter=lfs diff=lfs merge=lfs -text
2821
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/pyproject.toml filter=lfs diff=lfs merge=lfs -text
SynthData0523/main/c19/realtabformer/rtf-c19-20260513_062753/train_20260513_062755.log ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:be6136097c43fbe6e42bddd05064b3af0ebc8dea7ee92b9bc9cd679f003302d9
3
+ size 1209872
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/.gitignore ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
110
+ .pdm.toml
111
+ .pdm-python
112
+ .pdm-build/
113
+
114
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
115
+ __pypackages__/
116
+
117
+ # Celery stuff
118
+ celerybeat-schedule
119
+ celerybeat.pid
120
+
121
+ # SageMath parsed files
122
+ *.sage.py
123
+
124
+ # Environments
125
+ .env
126
+ .venv
127
+ env/
128
+ venv/
129
+ ENV/
130
+ env.bak/
131
+ venv.bak/
132
+
133
+ # Spyder project settings
134
+ .spyderproject
135
+ .spyproject
136
+
137
+ # Rope project settings
138
+ .ropeproject
139
+
140
+ # mkdocs documentation
141
+ /site
142
+
143
+ # mypy
144
+ .mypy_cache/
145
+ .dmypy.json
146
+ dmypy.json
147
+
148
+ # Pyre type checker
149
+ .pyre/
150
+
151
+ # pytype static type analyzer
152
+ .pytype/
153
+
154
+ # Cython debug symbols
155
+ cython_debug/
156
+
157
+ # PyCharm
158
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
159
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
161
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
162
+ #.idea/
163
+
164
+ .DS_Store
165
+ # data/adult
166
+ data/beijing
167
+ data/default
168
+ data/magic
169
+ data/news
170
+ data/shoppers
171
+
172
+ wandb/
173
+
174
+ *.DS_Store
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/LICENCE ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ Copyright 2024 Andrés Guzmán-Cordero
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/README.md ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Exponential Family Variational Flow Matching for Tabular Data Generation
2
+
3
+ <p align="center">
4
+ <a href="https://github.com/andresguzco/ef-vfm/blob/main/LICENSE.txt">
5
+ <img alt="MIT License" src="https://img.shields.io/badge/License-MIT-yellow.svg">
6
+ </a>
7
+ <a href="https://openreview.net/pdf?id=kjtvCSkSsy">
8
+ <img alt="Openreview" src="https://img.shields.io/badge/review-OpenReview-blue">
9
+ </a>
10
+ <a href="https://arxiv.org/pdf/2506.05940">
11
+ <img alt="Paper URL" src="https://img.shields.io/badge/cs.LG-2506.05940-B31B1B.svg">
12
+ </a>
13
+ </p>
14
+
15
+ <div align="center">
16
+ <img src="images/demo.jpg" alt="Model Logo" width="800" style="margin-left:'auto' margin-right:'auto' display:'block'"/>
17
+ <p><em> Figure 1: Exponential Family Variational Flow Matching (EF-VFM) is a generative modeling framework designed for mixed continuous
18
+ and discrete variables. By leveraging the exponential family and a mean-field assumption, EF-VFM efficiently matches the sufficient
19
+ statistics of the distributions via learned probability paths, ensuring state-of-the-art fidelity and diversity in synthetic data.</a></em></p>
20
+ </div>
21
+
22
+ This repository provides the prototypical implementation of EF-VFM: TabbyFlow (ICML, 2025).
23
+
24
+ ## Latest Update
25
+
26
+ - [2025.09]:We are finally releasing our code! To speed the release and avoid compatibility isues, we removed the hyperparameter scripts we use to launch out experiments in our available cluster. Contact us if you have any questions!
27
+
28
+ ## Introduction
29
+
30
+ EF-VFM uses the exponential family to jointly model different distributions with a single variational flow matching framework. Its key contributions are:
31
+
32
+ 1) We propose Exponential Family Variational Flow Matching (EF-VFM), an extension of VFM that incorporates exponential family distributions that facilitates efficient training via moment matching.
33
+ 2) We establish a deep connection between VFM and a generalized flow matching objective through the lens of Bregman divergences, offering a theoretical foundation for learning probability paths over mixed data types.
34
+ 3) To demonstrate the effectiveness of EF-VFM, we introduce TabbyFlow, a model that achieves state-of-the-art performance on standard tabular benchmarks, improving both fidelity and diversity in synthetic data generation.
35
+
36
+ The schema of EF-VFM is presented in the figure above. For more details, please refer to [our paper](https://arxiv.org/pdf/2506.05940).
37
+
38
+ ## Environment Setup
39
+
40
+ Create the main environment with [ef_vfm.yaml](ef_vfm.yaml). This environment will be used for all tasks except for the evaluation of additional data fidelity metrics (i.e., $\alpha$-precision and $\beta$-recall scores)
41
+
42
+ ```conda env create -f ef_vfm.yaml```
43
+
44
+ Create another environment with [synthcity.yaml](synthcity.yaml) to evaluate additional data fidelity metrics
45
+
46
+ ```conda env create -f synthcity.yaml```
47
+
48
+ ## Datasets Preparation
49
+
50
+ ### Using the datasets experimented in the paper
51
+
52
+ Download raw datasets:
53
+
54
+ ```python download_dataset.py```
55
+
56
+ Process datasets:
57
+
58
+ ```python process_dataset.py```
59
+
60
+ ## Training TabbyFlow
61
+
62
+ To train an unconditional EF-VFM model across the entire table, run
63
+
64
+ ```python main.py --dataname <NAME_OF_DATASET> --mode train --exp_name <EXP_NAME>```
65
+
66
+ where ```<NAME_OF_DATASET>``` is the name of the dataset you want to train on, and ```<EXP_NAME>``` is the name of your experiment.
67
+
68
+ Current Options of ```<NAME_OF_DATASET>``` are: adult, default, shoppers, magic, beijing, news
69
+
70
+ Wanb logging is enabled by default. To disable it and log locally, add the ```--no_wandb``` flag.
71
+
72
+ You must specify the experiment name, which will be used for logging and saving files, add ```--exp_name <your experiment name>```.
73
+
74
+ ## Sampling and Evaluating TabbyFlow (Density, MLE, C2ST)
75
+
76
+ To sample synthetic tables from trained EF-VFM models and evaluate them, run
77
+
78
+ ```python main.py --dataname <NAME_OF_DATASET> --mode test --report --no_wandb --exp_name <EXP_NAME>```
79
+
80
+ where ```<NAME_OF_DATASET>``` and ```<EXP_NAME>``` should be the same as those used in training.
81
+
82
+ This will sample 20 synthetic tables randomly. Meanwhile, it will evaluate the density, mle, and c2st scores for each sample and report their average and standard deviation. The results will be printed out in the terminal, and the samples and detailed evaluation results will be placed in ./eval/report_runs/<EXP_NAME>/<NAME_OF_DATASET>/.
83
+
84
+ ## Evaluating on Additional Fidelity Metrics ($\alpha$-precision and $\beta$-recall scores)
85
+
86
+ To evaluate EF-VFM on the additional fidelity metrics ($\alpha$-precision and $\beta$-recall scores), you need to first make sure that you have already generated some samples by the previous commands. Then, you need to switch to the `synthcity` environment (as the synthcity packet used to compute those metrics conflicts with the main environment), by running
87
+
88
+ ```conda activate synthcity```
89
+
90
+ Then, evaluate the metrics by running
91
+
92
+ ```python eval/eval_quality.py --dataname <NAME_OF_DATASET>```
93
+
94
+ Similarly, the results will be printed out in the terminal and added to ./eval/report_runs/<EXP_NAME>/<NAME_OF_DATASET>/
95
+
96
+ ## Evaluating Data Privacy (DCR score)
97
+
98
+ To evalute the privacy metric DCR score, you first need to retrain all the models, as the metric requires an equal split between the training and testing data (our initial splits employ a 90/10 ratio). To retrain with an equal split, run the training command but append `_dcr` to ```<NAME_OF_DATASET>```
99
+
100
+ ```python main.py --dataname <NAME_OF_DATASET>_dcr --mode train```
101
+
102
+ Then, test the models on DCR with the same `_dcr` suffix
103
+
104
+ ```python main.py --dataname <NAME_OF_DATASET>_dcr --mode test --report --no_wandb```
105
+
106
+ ## License
107
+
108
+ This work is licensed under the MIT License.
109
+
110
+ ## Acknowledgement
111
+
112
+ This repo is built upon the previous work TabDiff's [[codebase]](https://github.com/MinkaiXu/TabDiff). Many thanks to Juntong, Minkai, Harper and Hengrui!
113
+
114
+ ## Citation
115
+
116
+ ```@inproceedings{
117
+ guzmancordero2025exponentialfamily,
118
+ title={Exponential Family Variational Flow Matching for Tabular Data Generation},
119
+ author={Andr\'es Guzm\'an-Cordero and Floor Eijkelboom and Jan-Willem van de Meent},
120
+ booktitle={The Forty-Second International Conference on Machine Learning},
121
+ year={2025},
122
+ url={https://openreview.net/forum?id=kjtvCSkSsy}
123
+ }
124
+ ```
125
+
126
+ ## Contact
127
+
128
+ If you encounter any problem or you have any question regarding the paper, please contact [Andrés](andresguzco@gmail.com).
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/X_cat_test.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7e8e273d7cebc9c535de23aac186a248e19f1b9270192e8516df2b3ff4d03b37
3
+ size 360576
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/X_cat_train.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:34a72bf9b360ceafc923a841725257c58f68702db5988848164e6a73030811ca
3
+ size 2882920
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/X_cat_val.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d7520984bdd5518919a6429f53fe78669a4c04ec06e58bb0b5388e56628d3080
3
+ size 360400
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/X_num_test.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:30bb71265025b7923a442d2e4818d163e76ace6a48bd5be6e29de20770bc8e15
3
+ size 65664
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/X_num_train.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:42ba0171576b4338cee3594e553bc298640933ba7a7c8a127ec106b642ee63e6
3
+ size 524272
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/X_num_val.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:adb8a29c75d7bdc3c8f7e797e555998c90f3b3154ccaeee3dc93d8cbe6c3c2d1
3
+ size 65632
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/info.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:26b65c13dd436fb96a31e3ea486b261897b74f9a192fe79828dc57be59be2f35
3
+ size 2739
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/real.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:092346325db7f445db2c00d2f5dd9a8397ecc33eaba7b2b14d9d48d92659fcfc
3
+ size 51459027
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/staged_features.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a57a0c3c2a45c85e74d4496ad733ad7f30b2615f97be5155850895fee1727948
3
+ size 1564
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/test.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fd9c98343a92c7b1afe63b402f07b9a55013adbfcc60ec1e17d5e026385eeec8
3
+ size 6304860
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/train.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:092346325db7f445db2c00d2f5dd9a8397ecc33eaba7b2b14d9d48d92659fcfc
3
+ size 51459027
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/val.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:69c75639e81916d3b4f2a28db38d7e15c78e442748aa5bf9fed2eb3784912a70
3
+ size 6331589
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/y_test.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:81ee7259842c7941a044da2da22e21e7cfc06ae84f376f61f795079639c0f830
3
+ size 32896
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/y_train.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:977de15b5bd4785ce2c1370504303a66f974c6dd474345dc88784832776cf98f
3
+ size 262200
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/data/pipeline_c19/y_val.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7a9ff40f59b5afc2a1752a1d42a673b1c24c422c859c9e3c35d6110919dfb7f7
3
+ size 32880
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/download_dataset.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from urllib import request
3
+ import zipfile
4
+
5
+ DATA_DIR = 'data'
6
+
7
+
8
+ NAME_URL_DICT_UCI = {
9
+ 'adult': 'https://archive.ics.uci.edu/static/public/2/adult.zip',
10
+ 'default': 'https://archive.ics.uci.edu/static/public/350/default+of+credit+card+clients.zip',
11
+ 'magic': 'https://archive.ics.uci.edu/static/public/159/magic+gamma+telescope.zip',
12
+ 'shoppers': 'https://archive.ics.uci.edu/static/public/468/online+shoppers+purchasing+intention+dataset.zip',
13
+ 'beijing': 'https://archive.ics.uci.edu/static/public/381/beijing+pm2+5+data.zip',
14
+ 'news': 'https://archive.ics.uci.edu/static/public/332/online+news+popularity.zip',
15
+ 'news_nocat': 'https://archive.ics.uci.edu/static/public/332/online+news+popularity.zip',
16
+ 'adult_dcr': 'https://archive.ics.uci.edu/static/public/2/adult.zip',
17
+ 'default_dcr': 'https://archive.ics.uci.edu/static/public/350/default+of+credit+card+clients.zip',
18
+ 'magic_dcr': 'https://archive.ics.uci.edu/static/public/159/magic+gamma+telescope.zip',
19
+ 'shoppers_dcr': 'https://archive.ics.uci.edu/static/public/468/online+shoppers+purchasing+intention+dataset.zip',
20
+ 'beijing_dcr': 'https://archive.ics.uci.edu/static/public/381/beijing+pm2+5+data.zip',
21
+ 'news_dcr': 'https://archive.ics.uci.edu/static/public/332/online+news+popularity.zip',
22
+ }
23
+
24
+ def unzip_file(zip_filepath, dest_path):
25
+ with zipfile.ZipFile(zip_filepath, 'r') as zip_ref:
26
+ zip_ref.extractall(dest_path)
27
+
28
+
29
+ def download_from_uci(name):
30
+
31
+ print(f'Start processing dataset {name} from UCI.')
32
+ save_dir = f'{DATA_DIR}/{name}'
33
+ if not os.path.exists(save_dir):
34
+ os.makedirs(save_dir)
35
+
36
+ url = NAME_URL_DICT_UCI[name]
37
+ request.urlretrieve(url, f'{save_dir}/{name}.zip')
38
+ print(f'Finish downloading dataset from {url}, data has been saved to {save_dir}.')
39
+
40
+ unzip_file(f'{save_dir}/{name}.zip', save_dir)
41
+ print(f'Finish unzipping {name}.')
42
+
43
+ else:
44
+ print('Aready downloaded.')
45
+
46
+ if __name__ == '__main__':
47
+ for name in NAME_URL_DICT_UCI.keys():
48
+ download_from_uci(name)
49
+
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/ckpt/pipeline_c19/adapter_efvfm/config.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4414412ce77c556d589837072bfdedea7320630b8edc529db7168c12e4fa784f
3
+ size 963
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/ckpt/pipeline_c19/adapter_efvfm/ema_model_100.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e8a354f962f44b4e9e6304a485bca8594834b7981128e2b294dcd9fe062a1966
3
+ size 44003907
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/ckpt/pipeline_c19/adapter_efvfm/model_100.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b35b837c2370a9cda8934b60ed52fcb46033de3dd2fd1c943acf0ea3912f22f4
3
+ size 44003467
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/configs/ef_vfm_configs.toml ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:677698232b3ea325b54527cccdc11c49fadb971129a77065e71d64aa7567ddb6
3
+ size 674
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/main.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import json
3
+ import os
4
+ import pickle
5
+ import random
6
+
7
+ import numpy as np
8
+ from ef_vfm.metrics import TabMetrics
9
+ from ef_vfm.modules.main_modules import UniModMLP
10
+ from ef_vfm.models.flow_model import ExpVFM
11
+ from ef_vfm.trainer import Trainer
12
+ import src
13
+ import torch
14
+
15
+ from torch.utils.data import DataLoader
16
+ import argparse
17
+ import warnings
18
+
19
+ import wandb
20
+
21
+
22
+ from utils_train import EFVFMDataset
23
+
24
+ warnings.filterwarnings('ignore')
25
+
26
+
27
+ def main(args):
28
+ device = args.device
29
+
30
+ ## Disable scientific numerical format
31
+ np.set_printoptions(suppress=True)
32
+ torch.set_printoptions(sci_mode=False)
33
+
34
+ ## Get data info
35
+ dataname = args.dataname
36
+ data_dir = f'data/{dataname}'
37
+ info_path = f'data/{dataname}/info.json'
38
+ with open(info_path, 'r') as f:
39
+ info = json.load(f)
40
+
41
+ ## Set up flags
42
+ is_dcr = 'dcr' in dataname
43
+
44
+ ## Set experiment name
45
+ exp_name = args.exp_name
46
+ assert args.exp_name is not None, "Experiment name must be provided"
47
+
48
+ ## Load configs
49
+ curr_dir = os.path.dirname(os.path.abspath(__file__))
50
+ config_path = f'{curr_dir}/configs/ef_vfm_configs.toml'
51
+ raw_config = src.load_config(config_path)
52
+
53
+ print(f"{args.mode.capitalize()} Mode is Enabled")
54
+ num_samples_to_generate = None
55
+ ckpt_path = None
56
+ if args.mode == 'train':
57
+ print("NEW training is started")
58
+ elif args.mode == 'test':
59
+ num_samples_to_generate = args.num_samples_to_generate
60
+ ckpt_path = args.ckpt_path
61
+ if ckpt_path is None:
62
+ ckpt_parent_path = f"{curr_dir}/ckpt/{dataname}/{exp_name}"
63
+ ckpt_path_arr = glob.glob(f"{ckpt_parent_path}/best_ema_model*")
64
+ 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!"
65
+ ckpt_path = ckpt_path_arr[0]
66
+ config_path = os.path.join(os.path.dirname(ckpt_path), 'config.pkl')
67
+ if os.path.exists(config_path):
68
+ with open(config_path, 'rb') as f:
69
+ cached_raw_config = pickle.load(f)
70
+ print(f"Found cached config at {config_path}")
71
+ raw_config = cached_raw_config
72
+
73
+
74
+ ## Creat model_save and result paths
75
+ model_save_path, result_save_path = None, None
76
+ if args.mode == 'train':
77
+ model_save_path = 'debug/ckpt' if args.debug else f'{curr_dir}/ckpt/{dataname}/{exp_name}'
78
+ result_save_path = model_save_path.replace('ckpt', 'result') #i.e., f'{curr_dir}/results/{dataname}/{exp_name}'
79
+ elif args.mode == 'test':
80
+ if args.report:
81
+ result_save_path = f"eval/report_runs/{exp_name}/{dataname}"
82
+ else:
83
+ result_save_path = os.path.dirname(ckpt_path).replace('ckpt', 'result') # infer the exp_name from the ckpt_name
84
+ raw_config['model_save_path'] = model_save_path
85
+ raw_config['result_save_path'] = result_save_path
86
+ if model_save_path is not None:
87
+ if not os.path.exists(model_save_path):
88
+ os.makedirs(model_save_path)
89
+ if result_save_path is not None:
90
+ if not os.path.exists(result_save_path):
91
+ os.makedirs(result_save_path)
92
+
93
+ ## Make everything determinstic if needed
94
+ raw_config['deterministic'] = args.deterministic
95
+ if args.deterministic:
96
+ print("DETERMINISTIC MODE is enabled!!!")
97
+ ## Set global random seeds
98
+ torch.manual_seed(0)
99
+ random.seed(0)
100
+ np.random.seed(0)
101
+
102
+ ## Ensure deterministic CUDA operations
103
+ os.environ['PYTHONHASHSEED'] = '0'
104
+ os.environ['CUBLAS_WORKSPACE_CONFIG'] = ':4096:8' # or ':16:8'
105
+ torch.use_deterministic_algorithms(True)
106
+ if torch.cuda.is_available():
107
+ torch.cuda.manual_seed(0)
108
+ torch.cuda.manual_seed_all(0)
109
+ torch.backends.cudnn.deterministic = True
110
+ torch.backends.cudnn.benchmark = False
111
+
112
+ ## Set debug mode parameters
113
+ if args.debug: # fast eval for DEBUG mode
114
+ raw_config['train']['main']['check_val_every'] = 2
115
+ raw_config['train']['main']['batch_size'] = 4096
116
+ raw_config['sample']['batch_size'] = 10000
117
+
118
+ _smoke = os.environ.get("EFVFM_SMOKE_STEPS", "").strip()
119
+ if _smoke and args.mode == "train":
120
+ n = max(1, int(_smoke))
121
+ raw_config["train"]["main"]["steps"] = n
122
+ raw_config["train"]["main"]["check_val_every"] = max(
123
+ 1, min(n, raw_config["train"]["main"]["check_val_every"])
124
+ )
125
+ if os.environ.get("EFVFM_ADAPTER_TRAIN", "").strip() and args.mode == "train":
126
+ raw_config["train"]["main"]["check_val_every"] = int(raw_config["train"]["main"]["steps"])
127
+
128
+ _sample_batch = os.environ.get("EFVFM_SAMPLE_BATCH_SIZE", "").strip()
129
+ if _sample_batch:
130
+ raw_config["sample"]["batch_size"] = max(1, int(_sample_batch))
131
+ _train_workers = os.environ.get("EFVFM_TRAIN_NUM_WORKERS", "").strip()
132
+ train_num_workers = max(0, int(_train_workers)) if _train_workers else 4
133
+
134
+ ## Load training data
135
+ batch_size = raw_config['train']['main']['batch_size']
136
+
137
+ train_data = EFVFMDataset(dataname, data_dir, info, isTrain=True, dequant_dist=raw_config['data']['dequant_dist'], int_dequant_factor=raw_config['data']['int_dequant_factor'])
138
+ train_loader = DataLoader(
139
+ train_data,
140
+ batch_size = batch_size,
141
+ shuffle = True,
142
+ num_workers = train_num_workers,
143
+ )
144
+ d_numerical, categories = train_data.d_numerical, train_data.categories
145
+
146
+ val_data = EFVFMDataset(dataname, data_dir, info, isTrain=False, dequant_dist=raw_config['data']['dequant_dist'], int_dequant_factor=raw_config['data']['int_dequant_factor'])
147
+
148
+ ## Load Metrics
149
+ real_data_path = f'synthetic/{dataname}/real.csv'
150
+ test_data_path = f'synthetic/{dataname}/test.csv'
151
+ val_data_path = f'synthetic/{dataname}/val.csv'
152
+ if not os.path.exists(val_data_path):
153
+ print(f"{args.dataname} does not have its validation set. During MLE evaluation, a validation set will be splitted from the training set!")
154
+ val_data_path = None
155
+ if args.mode == 'train':
156
+ metric_list = ["density"]
157
+ else:
158
+ if is_dcr:
159
+ metric_list = ["dcr"]
160
+ else:
161
+ metric_list = [
162
+ "density",
163
+ "mle",
164
+ "c2st",
165
+ ]
166
+ metrics = TabMetrics(real_data_path, test_data_path, val_data_path, info, device, metric_list=metric_list)
167
+
168
+ ## Load the module and models
169
+ raw_config['unimodmlp_params']['d_numerical'] = d_numerical
170
+ raw_config['unimodmlp_params']['categories'] = (categories).tolist()
171
+ model = UniModMLP(**raw_config['unimodmlp_params'])
172
+ model.to(device)
173
+
174
+ flow_model = ExpVFM(
175
+ num_classes=categories,
176
+ num_numerical_features=d_numerical,
177
+ vf_fn=model,
178
+ device=device,
179
+ )
180
+ num_params = sum(p.numel() for p in flow_model.parameters())
181
+ print("The number of parameters = ", num_params)
182
+ flow_model.to(device)
183
+ flow_model.train()
184
+
185
+ ## Print the configs
186
+ printed_configs = json.dumps(raw_config, default=lambda x: int(x) if isinstance(x, np.int64) else x, indent=4)
187
+ print(f"The config of the current run is : \n {printed_configs}")
188
+
189
+ ## Enable Wandb
190
+ project_name = f"XVFM_{dataname}"
191
+ raw_config['project_name'] = project_name
192
+ logger = wandb.init(
193
+ project=raw_config['project_name'],
194
+ name=exp_name,
195
+ config=raw_config,
196
+ mode='disabled' if args.debug or args.no_wandb else 'online',
197
+ )
198
+
199
+ ## Load Trainer
200
+ sample_batch_size = raw_config['sample']['batch_size']
201
+ trainer = Trainer(
202
+ flow_model,
203
+ train_loader,
204
+ train_data,
205
+ val_data,
206
+ metrics,
207
+ logger,
208
+ **raw_config['train']['main'],
209
+ sample_batch_size=sample_batch_size,
210
+ num_samples_to_generate=num_samples_to_generate,
211
+ model_save_path=raw_config['model_save_path'],
212
+ result_save_path=raw_config['result_save_path'],
213
+ device=device,
214
+ ckpt_path=ckpt_path,
215
+ )
216
+ if args.mode == 'test':
217
+ if args.report:
218
+ if is_dcr:
219
+ trainer.report_test_dcr(args.num_runs)
220
+ else:
221
+ trainer.report_test(args.num_runs)
222
+ else:
223
+ trainer.test()
224
+ else:
225
+ ## Save config
226
+ config_save_path = raw_config['model_save_path']
227
+ with open (os.path.join(config_save_path, 'config.pkl'), 'wb') as f:
228
+ pickle.dump(raw_config, f)
229
+ trainer.run_loop()
230
+
231
+
232
+
233
+ if __name__ == '__main__':
234
+
235
+ parser = argparse.ArgumentParser(description='Training of TabbyFlow')
236
+
237
+ parser.add_argument('--dataname', type=str, default='adult', help='Name of dataset.')
238
+ parser.add_argument('--gpu', type=int, default=0, help='GPU index.')
239
+
240
+ args = parser.parse_args()
241
+
242
+ # check cuda
243
+ if args.gpu != -1 and torch.cuda.is_available():
244
+ args.device = f'cuda:{args.gpu}'
245
+ else:
246
+ args.device = 'cpu'
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/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/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/models/flow_model.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn.functional as F
2
+ import torch
3
+ import numpy as np
4
+ from torchdiffeq import odeint_adjoint as odeint
5
+
6
+
7
+ class ExpVFM(torch.nn.Module):
8
+ def __init__(
9
+ self,
10
+ num_classes: np.array,
11
+ num_numerical_features: int,
12
+ vf_fn,
13
+ device=torch.device('cpu'),
14
+ **kwargs
15
+ ):
16
+
17
+ super(ExpVFM, self).__init__()
18
+
19
+ self.num_numerical_features = num_numerical_features
20
+ self.num_classes = num_classes # it as a vector [K1, K2, ..., Km]
21
+ self.num_classes_expanded = torch.from_numpy(
22
+ np.concatenate([num_classes[i].repeat(num_classes[i]) for i in range(len(num_classes))])
23
+ ).to(device) if len(num_classes)>0 else torch.tensor([]).to(device).int()
24
+ self.neg_infinity = -1000000.0
25
+
26
+ offsets = np.cumsum(self.num_classes)
27
+ offsets = np.append([0], offsets)
28
+ self.slices_for_classes = []
29
+ for i in range(1, len(offsets)):
30
+ self.slices_for_classes.append(np.arange(offsets[i - 1], offsets[i]))
31
+ self.offsets = torch.from_numpy(offsets).to(device)
32
+
33
+ offsets = np.cumsum(self.num_classes) + np.arange(1, len(self.num_classes)+1)
34
+ offsets = np.append([0], offsets)
35
+
36
+ self._vf_fn = vf_fn
37
+ self.device = device
38
+
39
+
40
+ def mixed_loss(self, x):
41
+ b = x.shape[0]
42
+ dev = x.device
43
+
44
+ x_num = x[:, :self.num_numerical_features]
45
+ x_cat = x[:, self.num_numerical_features:].long()
46
+
47
+ t = torch.rand(b, device=dev, dtype=x_num.dtype)
48
+ t = t[:, None]
49
+
50
+ # Continuous interpolation
51
+ x_num_t = x_num
52
+ if x_num.shape[1] > 0:
53
+ noise = torch.randn_like(x_num)
54
+ x_num_t = t * x_num + (1 - t) * noise # + noise * sigma_num
55
+
56
+ # Discrete interpolation
57
+ x_cat_oh = self.to_one_hot(x_cat).float()
58
+ x_cat_t = x_cat_oh
59
+ if x_cat.shape[1] > 0:
60
+ x_cat_t = t * x_cat_oh + (1 - t) * torch.randn_like(x_cat_oh)
61
+
62
+ # Predict orignal data (distribution)
63
+ model_out_num, model_out_cat = self._vf_fn(x_num_t, x_cat_t, t.squeeze())
64
+
65
+ d_loss = torch.zeros((1,)).float()
66
+ c_loss = torch.zeros((1,)).float()
67
+
68
+ # Compute the loss
69
+ if x_num.shape[1] > 0:
70
+ c_loss = self._mvgloss(model_out_num, x_num, t)
71
+
72
+ if x_cat.shape[1] > 0:
73
+ d_loss = self._absorbed_closs(model_out_cat, x_cat, self._vf_fn.categories)
74
+
75
+ return d_loss.mean(), c_loss.mean()
76
+
77
+ def _mvgloss(self, mu_t, x_num_t, t):
78
+ n, k = mu_t.shape
79
+ dev = mu_t.device
80
+ dt = mu_t.dtype
81
+
82
+ identity = torch.eye(k, device=dev, dtype=dt).unsqueeze(0).expand(n, -1, -1)
83
+ scale = 1 - (1 - 0.01) * t.unsqueeze(1) ** 2
84
+ sigma = scale * identity
85
+ dist = torch.distributions.MultivariateNormal(mu_t, sigma)
86
+ return -dist.log_prob(x_num_t).mean()
87
+
88
+ @torch.no_grad()
89
+ def sample(self, num_samples):
90
+ dev = self.device
91
+ dt = torch.float32
92
+ d_in = self.num_numerical_features + sum(self.num_classes)
93
+ d_out = self.num_numerical_features + len(self.num_classes)
94
+
95
+ x0 = torch.randn(num_samples, d_in, device=dev)
96
+ t = torch.tensor([0.0, 0.999]).to(dev)
97
+ vf = Velocity(self._vf_fn)
98
+ trajectory = odeint(vf, x0, t, method="dopri5", rtol=1e-5, atol=1e-5)
99
+ out = trajectory[1]
100
+
101
+ sample = torch.zeros(num_samples, d_out, device=dev, dtype=dt)
102
+ sample[:, :self.num_numerical_features] = out[:, :self.num_numerical_features].to(torch.float32)
103
+ if sum(self.num_classes) != 0:
104
+ idx = self.num_numerical_features
105
+ for i, val in enumerate(self.num_classes):
106
+ col = self.num_numerical_features + i
107
+ sample[:, col] = torch.argmax(out[:, idx:idx + val], dim=1)
108
+ idx += val
109
+ assert val >= sample[:, col].max() >= 0, f"Sampled value {sample[:, col].max()} is out of range for categorical feature {i} with {val} classes."
110
+
111
+ return sample.cpu()
112
+
113
+ def sample_all(self, num_samples, batch_size, keep_nan_samples=False):
114
+ b = batch_size
115
+
116
+ all_samples = []
117
+ num_generated = 0
118
+ while num_generated < num_samples:
119
+ print(f"Samples left to generate: {num_samples-num_generated}")
120
+ sample = self.sample(b)
121
+ mask_nan = torch.any(sample.isnan(), dim=1)
122
+ if keep_nan_samples:
123
+ # If the sample instances that contains Nan are decided to be kept, the row with Nan will be foreced to all zeros
124
+ sample = sample * (~mask_nan)[:, None]
125
+ else:
126
+ # Otherwise the instances with Nan will be eliminated
127
+ sample = sample[~mask_nan]
128
+
129
+ all_samples.append(sample)
130
+ num_generated += sample.shape[0]
131
+
132
+ x_gen = torch.cat(all_samples, dim=0)[:num_samples]
133
+
134
+ return x_gen
135
+
136
+ def to_one_hot(self, x_cat):
137
+ if len(self.num_classes) == 0:
138
+ return torch.zeros(x_cat.shape[0], 0, device=x_cat.device, dtype=torch.long)
139
+ x_cat_oh = torch.cat(
140
+ [F.one_hot(x_cat[:, i], num_classes=self.num_classes[i]) for i in range(len(self.num_classes))],
141
+ dim=-1
142
+ )
143
+ return x_cat_oh
144
+
145
+ def _absorbed_closs(self, model_output, x0, cats): #, sigma, dsigma):
146
+ """
147
+ alpha: (bs,)
148
+ """
149
+ cum_sum =0
150
+ losses = torch.zeros(len(cats), device=model_output.device)
151
+ for i, val in enumerate(cats):
152
+ dist = torch.distributions.Categorical(logits=model_output[:, cum_sum:cum_sum+val])
153
+ losses[i] = -dist.log_prob(x0[:, i]).mean()
154
+ cum_sum += val
155
+
156
+ loss = losses.sum()
157
+ return loss
158
+
159
+
160
+ class Velocity(torch.nn.Module):
161
+ def __init__(self, model):
162
+ super(Velocity, self).__init__()
163
+ self.model = model
164
+
165
+ def forward(self, t, x):
166
+ t = t * torch.ones(x.shape[0]).to(x.device)
167
+
168
+ x_num = x[:, :self.model.d_numerical]
169
+ x_cat = x[:, self.model.d_numerical:]
170
+ mu, logits = self.model(x_num, x_cat, t)
171
+
172
+ # Numerical velocity
173
+ if self.model.d_numerical > 0:
174
+ v_num = (mu - (1 - 0.01) * x_num) / (1 - (1 - 0.01) * t.unsqueeze(1))
175
+ else:
176
+ v_num = torch.zeros_like(x_num)
177
+
178
+ # Categorical velocity: normalize logits into probability space before computing velocity
179
+ if len(self.model.categories) > 0:
180
+ v_cat_parts = []
181
+ logit_idx = 0
182
+ oh_idx = 0
183
+ for k in self.model.categories:
184
+ probs_k = F.softmax(logits[:, logit_idx:logit_idx + k], dim=-1)
185
+ x_k = x_cat[:, oh_idx:oh_idx + k]
186
+ v_k = (probs_k - (1 - 0.01) * x_k) / (1 - (1 - 0.01) * t.unsqueeze(1))
187
+ v_cat_parts.append(v_k)
188
+ logit_idx += k
189
+ oh_idx += k
190
+ v_cat = torch.cat(v_cat_parts, dim=1)
191
+ else:
192
+ v_cat = torch.zeros_like(x_cat)
193
+
194
+ v_t = torch.cat([v_num, v_cat], dim=1)
195
+ return v_t
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/modules/main_modules.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, Union
2
+
3
+ from ef_vfm.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
+
15
+ class PositionalEmbedding(torch.nn.Module):
16
+ def __init__(self, num_channels, max_positions=10000, endpoint=False):
17
+ super().__init__()
18
+ self.num_channels = num_channels
19
+ self.max_positions = max_positions
20
+ self.endpoint = endpoint
21
+
22
+ def forward(self, x):
23
+ freqs = torch.arange(start=0, end=self.num_channels//2, dtype=torch.float32, device=x.device)
24
+ freqs = freqs / (self.num_channels // 2 - (1 if self.endpoint else 0))
25
+ freqs = (1 / self.max_positions) ** freqs
26
+ x = x.ger(freqs.to(x.dtype))
27
+ x = torch.cat([x.cos(), x.sin()], dim=1)
28
+ return x
29
+
30
+
31
+ class MLP(nn.Module):
32
+ def __init__(self, d_in, dim_t = 512, use_mlp=True):
33
+ super().__init__()
34
+ self.dim_t = dim_t
35
+
36
+ self.proj = nn.Linear(d_in, dim_t)
37
+
38
+ self.mlp = nn.Sequential(
39
+ nn.Linear(dim_t, dim_t * 2),
40
+ nn.SiLU(),
41
+ nn.Linear(dim_t * 2, dim_t * 2),
42
+ nn.SiLU(),
43
+ nn.Linear(dim_t * 2, dim_t),
44
+ nn.SiLU(),
45
+ nn.Linear(dim_t, d_in),
46
+ ) if use_mlp else nn.Linear(dim_t, d_in)
47
+
48
+ self.map_noise = PositionalEmbedding(num_channels=dim_t)
49
+ self.time_embed = nn.Sequential(
50
+ nn.Linear(dim_t, dim_t),
51
+ nn.SiLU(),
52
+ nn.Linear(dim_t, dim_t)
53
+ )
54
+
55
+ self.use_mlp = use_mlp
56
+
57
+ def forward(self, x, timesteps):
58
+ emb = self.map_noise(timesteps)
59
+ emb = emb.reshape(emb.shape[0], 2, -1).flip(1).reshape(*emb.shape) # swap sin/cos
60
+ emb = self.time_embed(emb)
61
+
62
+ x = self.proj(x) + emb
63
+ return self.mlp(x)
64
+
65
+
66
+ class UniModMLP(nn.Module):
67
+ """
68
+ Input:
69
+ x_num: [bs, d_numerical]
70
+ x_cat: [bs, len(categories)]
71
+ Output:
72
+ x_num_pred: [bs, d_numerical], the predicted mean for numerical data
73
+ x_cat_pred: [bs, sum(categories)], the predicted UNORMALIZED logits for categorical data
74
+ """
75
+ def __init__(
76
+ self, d_numerical, categories, num_layers, d_token,
77
+ n_head = 1, factor = 4, bias = True, dim_t=512, use_mlp=True,
78
+ activation='gelu', **kwargs
79
+ ):
80
+ super().__init__()
81
+ self.d_numerical = d_numerical
82
+ self.categories = categories
83
+
84
+ self.tokenizer = Tokenizer(d_numerical, categories, d_token, bias = bias)
85
+ self.encoder = Transformer(num_layers, d_token, n_head, d_token, factor, activation=activation)
86
+ d_in = d_token * (d_numerical + len(categories))
87
+ self.mlp = MLP(d_in, dim_t=dim_t, use_mlp=use_mlp)
88
+ self.decoder = Transformer(num_layers, d_token, n_head, d_token, factor, activation=activation)
89
+ self.detokenizer = Reconstructor(d_numerical, categories, d_token)
90
+
91
+ self.model = nn.ModuleList([self.tokenizer, self.encoder, self.mlp, self.decoder, self.detokenizer])
92
+
93
+ def forward(self, x_num, x_cat, timesteps):
94
+ e = self.tokenizer(x_num, x_cat)
95
+ decoder_input = e[:, 1:, :] # ignore the first CLS token.
96
+ y = self.encoder(decoder_input)
97
+ pred_y = self.mlp(y.reshape(y.shape[0], -1), timesteps)
98
+ pred_e = self.decoder(pred_y.reshape(*y.shape))
99
+ x_num_pred, x_cat_pred = self.detokenizer(pred_e)
100
+ 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)
101
+
102
+ return x_num_pred, x_cat_pred
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/modules/transformer.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.init as nn_init
4
+ import torch.nn.functional as F
5
+ from torch import Tensor
6
+
7
+ import math
8
+
9
+ class Tokenizer(nn.Module):
10
+
11
+ def __init__(self, d_numerical, categories, d_token, bias):
12
+ super().__init__()
13
+ if categories is None:
14
+ d_bias = d_numerical
15
+ self.category_offsets = None
16
+ self.category_embeddings = None
17
+ self.n_categories = 0
18
+ else:
19
+ d_bias = d_numerical + len(categories)
20
+ category_offsets = torch.tensor([0] + list(categories[:-1])).cumsum(0)
21
+ category_ends = torch.tensor(list(categories)).cumsum(0)
22
+ self.register_buffer('category_offsets', category_offsets)
23
+ self.register_buffer('category_ends', category_ends)
24
+ self.cat_weight = nn.Parameter(Tensor(sum(categories), d_token))
25
+ nn.init.kaiming_uniform_(self.cat_weight, a=math.sqrt(5))
26
+ self.n_categories = len(categories)
27
+
28
+ # take [CLS] token into account
29
+ self.weight = nn.Parameter(Tensor(d_numerical + 1, d_token))
30
+ self.bias = nn.Parameter(Tensor(d_bias, d_token)) if bias else None
31
+ # The initialization is inspired by nn.Linear
32
+ nn_init.kaiming_uniform_(self.weight, a=math.sqrt(5))
33
+ if self.bias is not None:
34
+ nn_init.kaiming_uniform_(self.bias, a=math.sqrt(5))
35
+
36
+ @property
37
+ def n_tokens(self):
38
+ return len(self.weight) + (
39
+ 0 if self.category_offsets is None else len(self.category_offsets)
40
+ )
41
+
42
+ def forward(self, x_num, x_cat):
43
+ x_some = x_num if x_cat is None else x_cat
44
+ assert x_some is not None
45
+ x_num = torch.cat(
46
+ [torch.ones(len(x_some), 1, device=x_some.device)] # [CLS]
47
+ + ([] if x_num is None else [x_num]),
48
+ dim=1,
49
+ )
50
+
51
+ x = self.weight[None] * x_num[:, :, None]
52
+
53
+ if x_cat is not None and self.n_categories > 0:
54
+ # Vectorized categorical token computation: one matmul per category
55
+ cat_tokens = []
56
+ for start, end in zip(self.category_offsets, self.category_ends):
57
+ # x_cat[:, start:end] @ cat_weight[start:end] -> [batch, d_token]
58
+ cat_tokens.append(
59
+ (x_cat[:, start:end] @ self.cat_weight[start:end]).unsqueeze(1)
60
+ )
61
+ x = torch.cat([x] + cat_tokens, dim=1)
62
+
63
+ if self.bias is not None:
64
+ bias = torch.cat(
65
+ [
66
+ torch.zeros(1, self.bias.shape[1], device=x.device),
67
+ self.bias,
68
+ ]
69
+ )
70
+ x = x + bias[None]
71
+
72
+ return x
73
+
74
+
75
+ class MultiheadAttention(nn.Module):
76
+ def __init__(self, d, n_heads, dropout, initialization = 'kaiming'):
77
+
78
+ if n_heads > 1:
79
+ assert d % n_heads == 0
80
+ assert initialization in ['xavier', 'kaiming']
81
+
82
+ super().__init__()
83
+ self.W_q = nn.Linear(d, d)
84
+ self.W_k = nn.Linear(d, d)
85
+ self.W_v = nn.Linear(d, d)
86
+ self.W_out = nn.Linear(d, d) if n_heads > 1 else None
87
+ self.n_heads = n_heads
88
+ self.dropout = nn.Dropout(dropout) if dropout else None
89
+
90
+ for m in [self.W_q, self.W_k, self.W_v]:
91
+ if initialization == 'xavier' and (n_heads > 1 or m is not self.W_v):
92
+ # gain is needed since W_qkv is represented with 3 separate layers
93
+ nn_init.xavier_uniform_(m.weight, gain=1 / math.sqrt(2))
94
+ nn_init.zeros_(m.bias)
95
+ if self.W_out is not None:
96
+ nn_init.zeros_(self.W_out.bias)
97
+
98
+ def _reshape(self, x):
99
+ batch_size, n_tokens, d = x.shape
100
+ d_head = d // self.n_heads
101
+ return (
102
+ x.reshape(batch_size, n_tokens, self.n_heads, d_head)
103
+ .transpose(1, 2)
104
+ .reshape(batch_size * self.n_heads, n_tokens, d_head)
105
+ )
106
+
107
+ def forward(self, x_q, x_kv, key_compression = None, value_compression = None):
108
+
109
+ q, k, v = self.W_q(x_q), self.W_k(x_kv), self.W_v(x_kv)
110
+ for tensor in [q, k, v]:
111
+ assert tensor.shape[-1] % self.n_heads == 0
112
+ if key_compression is not None:
113
+ assert value_compression is not None
114
+ k = key_compression(k.transpose(1, 2)).transpose(1, 2)
115
+ v = value_compression(v.transpose(1, 2)).transpose(1, 2)
116
+ else:
117
+ assert value_compression is None
118
+
119
+ batch_size = len(q)
120
+ d_head_key = k.shape[-1] // self.n_heads
121
+ d_head_value = v.shape[-1] // self.n_heads
122
+ n_q_tokens = q.shape[1]
123
+
124
+ q = self._reshape(q)
125
+ k = self._reshape(k)
126
+
127
+ a = q @ k.transpose(1, 2)
128
+ b = math.sqrt(d_head_key)
129
+ attention = F.softmax(a/b , dim=-1)
130
+
131
+
132
+ if self.dropout is not None:
133
+ attention = self.dropout(attention)
134
+ x = attention @ self._reshape(v)
135
+ x = (
136
+ x.reshape(batch_size, self.n_heads, n_q_tokens, d_head_value)
137
+ .transpose(1, 2)
138
+ .reshape(batch_size, n_q_tokens, self.n_heads * d_head_value)
139
+ )
140
+ if self.W_out is not None:
141
+ x = self.W_out(x)
142
+
143
+ return x
144
+
145
+ class Transformer(nn.Module):
146
+
147
+ def __init__(
148
+ self,
149
+ n_layers: int,
150
+ d_token: int,
151
+ n_heads: int,
152
+ d_out: int,
153
+ d_ffn_factor: int,
154
+ attention_dropout = 0.0,
155
+ ffn_dropout = 0.0,
156
+ residual_dropout = 0.0,
157
+ activation = 'relu',
158
+ prenormalization = True,
159
+ initialization = 'kaiming',
160
+ ):
161
+ super().__init__()
162
+
163
+ def make_normalization():
164
+ return nn.LayerNorm(d_token)
165
+
166
+ d_hidden = int(d_token * d_ffn_factor)
167
+ self.layers = nn.ModuleList([])
168
+ for layer_idx in range(n_layers):
169
+ layer = nn.ModuleDict(
170
+ {
171
+ 'attention': MultiheadAttention(
172
+ d_token, n_heads, attention_dropout, initialization
173
+ ),
174
+ 'linear0': nn.Linear(
175
+ d_token, d_hidden
176
+ ),
177
+ 'linear1': nn.Linear(d_hidden, d_token),
178
+ 'norm1': make_normalization(),
179
+ }
180
+ )
181
+ if not prenormalization or layer_idx:
182
+ layer['norm0'] = make_normalization()
183
+
184
+ self.layers.append(layer)
185
+
186
+ _activations = {
187
+ 'relu': nn.ReLU,
188
+ 'gelu': nn.GELU,
189
+ 'silu': nn.SiLU,
190
+ }
191
+ if activation not in _activations:
192
+ raise ValueError(f"Unknown activation '{activation}'. Choose from: {list(_activations)}")
193
+ self.activation = _activations[activation]()
194
+ self.last_activation = _activations[activation]()
195
+ self.prenormalization = prenormalization
196
+ self.last_normalization = make_normalization() if prenormalization else None
197
+ self.ffn_dropout = ffn_dropout
198
+ self.residual_dropout = residual_dropout
199
+ self.head = nn.Linear(d_token, d_out)
200
+
201
+
202
+ def _start_residual(self, x, layer, norm_idx):
203
+ x_residual = x
204
+ if self.prenormalization:
205
+ norm_key = f'norm{norm_idx}'
206
+ if norm_key in layer:
207
+ x_residual = layer[norm_key](x_residual)
208
+ return x_residual
209
+
210
+ def _end_residual(self, x, x_residual, layer, norm_idx):
211
+ if self.residual_dropout:
212
+ x_residual = F.dropout(x_residual, self.residual_dropout, self.training)
213
+ x = x + x_residual
214
+ if not self.prenormalization:
215
+ x = layer[f'norm{norm_idx}'](x)
216
+ return x
217
+
218
+ def forward(self, x):
219
+ for layer_idx, layer in enumerate(self.layers):
220
+ is_last_layer = layer_idx + 1 == len(self.layers)
221
+
222
+ x_residual = self._start_residual(x, layer, 0)
223
+ x_residual = layer['attention'](
224
+ # for the last attention, it is enough to process only [CLS]
225
+ x_residual,
226
+ x_residual,
227
+ )
228
+
229
+ x = self._end_residual(x, x_residual, layer, 0)
230
+
231
+ x_residual = self._start_residual(x, layer, 1)
232
+ x_residual = layer['linear0'](x_residual)
233
+ x_residual = self.activation(x_residual)
234
+ if self.ffn_dropout:
235
+ x_residual = F.dropout(x_residual, self.ffn_dropout, self.training)
236
+ x_residual = layer['linear1'](x_residual)
237
+ x = self._end_residual(x, x_residual, layer, 1)
238
+ return x
239
+
240
+
241
+ class Reconstructor(nn.Module):
242
+ def __init__(self, d_numerical, categories, d_token):
243
+ super(Reconstructor, self).__init__()
244
+
245
+ self.d_numerical = d_numerical
246
+ self.categories = categories
247
+ self.d_token = d_token
248
+
249
+ self.weight = nn.Parameter(Tensor(d_numerical, d_token))
250
+ nn.init.xavier_uniform_(self.weight, gain=1 / math.sqrt(2))
251
+ self.cat_recons = nn.ModuleList()
252
+
253
+ for d in categories:
254
+ recon = nn.Linear(d_token, d)
255
+ nn.init.xavier_uniform_(recon.weight, gain=1 / math.sqrt(2))
256
+ self.cat_recons.append(recon)
257
+
258
+ def forward(self, h):
259
+ h_num = h[:, :self.d_numerical]
260
+ h_cat = h[:, self.d_numerical:]
261
+
262
+ recon_x_num = torch.mul(h_num, self.weight.unsqueeze(0)).sum(-1)
263
+ recon_x_cat = []
264
+
265
+ for i, recon in enumerate(self.cat_recons):
266
+
267
+ recon_x_cat.append(recon(h_cat[:, i]))
268
+
269
+ return recon_x_num, recon_x_cat
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/result/pipeline_c19/adapter_efvfm/100/all_results.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:51f0231fd0a085fdf3a03904f8f823a2dac6347098a88ec9847655a526ad46c0
3
+ size 132
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/result/pipeline_c19/adapter_efvfm/100/ema/all_results.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3e32a4989adf12211b51525c3e02d8bf48757b9be33d9b23d0b764c582b12aa5
3
+ size 129
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/result/pipeline_c19/adapter_efvfm/100/ema/samples.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:feff0db338fe5b7bf0eb35084fdb9f165ba02d96765cfd278f760c41bc3b25cc
3
+ size 43072
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/result/pipeline_c19/adapter_efvfm/100/ema/shapes.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:296ac865c0ea7a1bb75431f42a7b22fc377a03b0f9527b4f50961c23b0b9ad45
3
+ size 639
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/result/pipeline_c19/adapter_efvfm/100/ema/trends.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0cbfc33efd738efb3ebdadb9ecfefc9b0a2932e3886ac5be94b29b0396bdd0bd
3
+ size 7573
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/result/pipeline_c19/adapter_efvfm/100/samples.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9a9bd2a5ee0513c6a2e9d175ed4bbce00a08d5b0cf9a5dcdd4197554a87c74f6
3
+ size 2638756
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/result/pipeline_c19/adapter_efvfm/100/shapes.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b419de87b933eefe4aec4c58981201d745bedf11a77f951c133e7b68514333dd
3
+ size 639
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/result/pipeline_c19/adapter_efvfm/100/trends.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c91a464ee4d0c6206c428b447c005a3960db7670c275555591e13315d37a4d19
3
+ size 7628
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/ef_vfm/trainer.py ADDED
@@ -0,0 +1,557 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, flow, 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
+ max_grad_norm = 1.0,
37
+ warmup_epochs = 0,
38
+ device=torch.device('cuda:1'),
39
+ ckpt_path = None,
40
+ **kwargs
41
+ ):
42
+ self.flow = flow
43
+ self.ema_model = deepcopy(self.flow._vf_fn)
44
+ for param in self.ema_model.parameters():
45
+ param.detach_()
46
+
47
+ self.train_iter = train_iter
48
+ self.dataset = dataset
49
+ self.test_dataset = test_dataset
50
+ self.steps = steps
51
+ self.init_lr = lr
52
+ self.optimizer = torch.optim.AdamW(self.flow.parameters(), lr=lr, weight_decay=weight_decay)
53
+ self.ema_decay = ema_decay
54
+ self.lr_scheduler = lr_scheduler
55
+ self.scheduler = ReduceLROnPlateau(self.optimizer, mode='min', factor=factor, patience=reduce_lr_patience)
56
+ self.closs_weight_schedule = closs_weight_schedule
57
+ self.c_lambda = c_lambda
58
+ self.d_lambda = d_lambda
59
+ self.max_grad_norm = max_grad_norm
60
+ self.warmup_epochs = warmup_epochs
61
+
62
+ self.batch_size = batch_size
63
+ self.sample_batch_size = sample_batch_size
64
+ self.num_samples_to_generate = num_samples_to_generate
65
+ self.metrics = metrics
66
+ self.logger = logger
67
+ self.check_val_every = check_val_every
68
+
69
+ self.device = device
70
+ self.model_save_path = model_save_path
71
+ self.result_save_path = result_save_path
72
+ self.ckpt_path = ckpt_path
73
+ if self.ckpt_path is not None:
74
+ state_dicts = torch.load(self.ckpt_path, map_location=self.device)
75
+ self.flow._vf_fn.load_state_dict(state_dicts['vf_fn'])
76
+ print(f"Weights are loaded from {self.ckpt_path}")
77
+
78
+ self.curr_epoch = int(os.path.basename(self.ckpt_path).split('_')[-1].split('.')[0]) if self.ckpt_path is not None else 0
79
+
80
+ def _anneal_lr(self, step):
81
+ frac_done = step / self.steps
82
+ lr = self.init_lr * (1 - frac_done)
83
+ for param_group in self.optimizer.param_groups:
84
+ param_group["lr"] = lr
85
+
86
+ def _run_step(self, x, closs_weight, dloss_weight):
87
+ x = x.to(self.device)
88
+
89
+ self.flow.train()
90
+
91
+ self.optimizer.zero_grad()
92
+
93
+ dloss, closs = self.flow.mixed_loss(x)
94
+
95
+ loss = dloss_weight * dloss + closs_weight * closs
96
+ loss.backward()
97
+ if self.max_grad_norm > 0:
98
+ torch.nn.utils.clip_grad_norm_(self.flow.parameters(), self.max_grad_norm)
99
+ self.optimizer.step()
100
+
101
+ return dloss, closs
102
+
103
+ def compute_loss(self): # eval loss is not weighted
104
+ curr_dloss = 0.0
105
+ curr_closs = 0.0
106
+ curr_count = 0
107
+ data_iter = self.train_iter
108
+ for batch in data_iter:
109
+ x = batch.float().to(self.device)
110
+ self.flow.eval()
111
+ with torch.no_grad():
112
+ batch_dloss, batch_closs = self.flow.mixed_loss(x)
113
+ curr_dloss += batch_dloss.item() * len(x)
114
+ curr_closs += batch_closs.item() * len(x)
115
+ curr_count += len(x)
116
+ mloss = np.around(curr_dloss / curr_count, 4)
117
+ gloss = np.around(curr_closs / curr_count, 4)
118
+ return mloss, gloss
119
+
120
+ def run_loop(self):
121
+ patience = 0
122
+ closs_weight, dloss_weight = self.c_lambda, self.d_lambda
123
+ best_loss = np.inf
124
+ best_ema_loss = np.inf
125
+ best_val_loss = np.inf
126
+ start_time = time.time()
127
+ print_with_bar(f"Starting Trainin Loop, total number of epoch = {self.steps}")
128
+ # Set up wandb's step metric
129
+ self.logger.define_metric("epoch")
130
+ self.logger.define_metric("*", step_metric="epoch")
131
+
132
+ start_epoch = self.curr_epoch
133
+ if start_epoch > 0:
134
+ print_with_bar(f"Resuming training from epoch {start_epoch}, with validation check every {self.check_val_every} epoches")
135
+ for epoch in range (start_epoch, self.steps):
136
+ self.curr_epoch = epoch+1
137
+ # Set up pbar
138
+ pbar = tqdm(self.train_iter, total=len(self.train_iter))
139
+ pbar.set_description(f"Epoch {epoch+1}/{self.steps}")
140
+
141
+ # Compute the loss weights
142
+ if self.closs_weight_schedule == "fixed":
143
+ pass
144
+ elif self.closs_weight_schedule == "anneal":
145
+ frac_done = epoch / self.steps
146
+ closs_weight = self.c_lambda * (1 - frac_done)
147
+ else:
148
+ raise NotImplementedError(f"The continuous loss weight schedule {self.closs_weight_schedule} is not implemneted")
149
+
150
+ # Training Step
151
+ curr_dloss = 0.0
152
+ curr_closs = 0.0
153
+ curr_count = 0
154
+ curr_lr = self.optimizer.param_groups[0]['lr']
155
+ for batch in pbar:
156
+ x = batch.float().to(self.device)
157
+ batch_dloss, batch_closs = self._run_step(x, closs_weight, dloss_weight)
158
+ curr_dloss += batch_dloss.item() * len(x)
159
+ curr_closs += batch_closs.item() * len(x)
160
+ curr_count += len(x)
161
+ pbar.set_postfix({
162
+ "lr": curr_lr,
163
+ "DLoss": np.around(curr_dloss/curr_count, 4),
164
+ "CLoss": np.around(curr_closs/curr_count, 4),
165
+ "TotalLoss": np.around((curr_dloss + curr_closs)/curr_count, 4),
166
+ "closs_weight": closs_weight,
167
+ "dloss_weight": dloss_weight,
168
+ })
169
+
170
+ # Log training Loss
171
+ log_dict = {}
172
+ mloss = np.around(curr_dloss / curr_count, 4)
173
+ gloss = np.around(curr_closs / curr_count, 4)
174
+ total_loss = mloss + gloss
175
+ if np.isnan(gloss):
176
+ print('Finding Nan in gaussian loss')
177
+ break
178
+ loss_dict = {
179
+ "epoch": epoch + 1,
180
+ "lr": curr_lr,
181
+ "closs_weight": closs_weight,
182
+ "dloss_weight": dloss_weight,
183
+ "loss/c_loss": gloss,
184
+ "loss/d_loss": mloss,
185
+ "loss/total_loss": total_loss
186
+ }
187
+ log_dict.update(loss_dict)
188
+
189
+ # Adjust learning rate (warmup overrides during early epochs)
190
+ if self.warmup_epochs > 0 and (epoch + 1) <= self.warmup_epochs:
191
+ warmup_lr = self.init_lr * (epoch + 1) / self.warmup_epochs
192
+ for param_group in self.optimizer.param_groups:
193
+ param_group["lr"] = warmup_lr
194
+ elif self.lr_scheduler == 'reduce_lr_on_plateau':
195
+ self.scheduler.step(total_loss)
196
+ elif self.lr_scheduler == 'anneal':
197
+ self._anneal_lr(epoch)
198
+ elif self.lr_scheduler == 'fixed':
199
+ pass
200
+ else:
201
+ raise NotImplementedError(f"LR scheduler with name '{self.lr_scheduler}' is not implemented")
202
+
203
+ # Update EMA models
204
+ update_ema(self.ema_model.parameters(), self.flow._vf_fn.parameters(), rate=self.ema_decay)
205
+
206
+ # Save ckpt base on the best training loss
207
+ if total_loss < best_loss and self.curr_epoch > 4000:
208
+ best_loss = total_loss
209
+ to_remove = glob.glob(os.path.join(self.model_save_path, f"best_model_*"))
210
+ if to_remove:
211
+ os.remove(to_remove[0])
212
+ state_dicts = {
213
+ 'vf_fn': self.flow._vf_fn.state_dict(),
214
+ }
215
+ torch.save(state_dicts, os.path.join(self.model_save_path, f'best_model_{np.round(total_loss,4)}_{epoch+1}.pt'))
216
+ patience = 0
217
+ else:
218
+ patience += 1 # increment patience if best loss is not surpassed
219
+
220
+ # Compute and log EMA model loss
221
+ curr_model = self.to_ema_model()
222
+ ema_mloss, ema_gloss = self.compute_loss()
223
+ self.to_model(curr_model)
224
+ ema_total_loss = ema_mloss + ema_gloss
225
+ ema_loss_dict = {
226
+ "ema_loss/c_loss": ema_gloss,
227
+ "ema_loss/d_loss": ema_mloss,
228
+ "ema_loss/total_loss": ema_total_loss
229
+ }
230
+
231
+ # Save the best ema ckpt
232
+ if ema_total_loss < best_ema_loss and self.curr_epoch > 4000:
233
+ best_ema_loss = ema_total_loss
234
+ to_remove = glob.glob(os.path.join(self.model_save_path, f"best_ema_model_*"))
235
+ if to_remove:
236
+ os.remove(to_remove[0])
237
+ state_dicts = {
238
+ 'vf_fn': self.ema_model.state_dict(),
239
+ }
240
+ torch.save(state_dicts, os.path.join(self.model_save_path, f'best_ema_model_{np.round(ema_total_loss,4)}_{epoch+1}.pt'))
241
+
242
+ # Evaluate Sample Quality
243
+ if (epoch+1) % self.check_val_every == 0:
244
+ state_dicts = {
245
+ 'vf_fn': self.flow._vf_fn.state_dict(),
246
+ }
247
+ torch.save(state_dicts, os.path.join(self.model_save_path, f'model_{epoch+1}.pt'))
248
+
249
+ print_with_bar(f"Routine Generation Evaluation every {self.check_val_every}, currently at epoch #{epoch+1}, wiht total_loss={total_loss}.")
250
+ _plot_density = os.environ.get("EFVFM_ADAPTER_TRAIN", "").strip().lower() not in ("1", "true", "yes")
251
+ out_metrics, _, _ = self.evaluate_generation(save_metric_details=True, plot_density=_plot_density)
252
+ log_dict.update(out_metrics)
253
+ print(f"Eval Resutls of the Non-EMA model:\n {out_metrics}")
254
+
255
+ # Evaluate the EMA model
256
+ torch.save(self.ema_model.state_dict(), os.path.join(self.model_save_path, f'ema_model_{epoch+1}.pt'))
257
+ ema_out_metrics, _, _ = self.evaluate_generation(ema=True, save_metric_details=True, plot_density=_plot_density)
258
+ log_dict.update({
259
+ "ema": ema_out_metrics,
260
+ })
261
+ print(f"Eval Resutls of the EMA model:\n {ema_out_metrics}")
262
+ # Submit logs
263
+ self.logger.log(log_dict)
264
+
265
+ end_time = time.time()
266
+ print_with_bar(f"Ending Trainnig Loop, totoal training time = {end_time - start_time}")
267
+ self.logger.log({
268
+ 'training_time': end_time - start_time
269
+ })
270
+
271
+ def report_test(self, num_runs):
272
+ save_dir = self.result_save_path
273
+
274
+ shape_ = []
275
+ trend_ = []
276
+ mle_ = []
277
+ c2st_ = []
278
+ for i in range(num_runs):
279
+ print_with_bar(f"GENERAL Evaluation Run {i}")
280
+ out_metrics, extras, syn_df = self.evaluate_generation()
281
+ print(f"Results of Run {i} are: \n{out_metrics}")
282
+ shape_.append(out_metrics["density/Shape"])
283
+ trend_.append(out_metrics["density/Trend"])
284
+ mle_.append(out_metrics["mle"])
285
+ c2st_.append(out_metrics["c2st"])
286
+ # Save samples for quality evaluation
287
+ save_path = os.path.join(save_dir, "all_samples")
288
+ if not os.path.exists(save_path):
289
+ os.makedirs(save_path)
290
+ syn_df.to_csv(os.path.join(save_path, f"samples_{i}.csv"), index=False)
291
+
292
+ shape_ = np.array(shape_)
293
+ trend_ = np.array(trend_)
294
+ mle_ = np.array(mle_)
295
+ c2st_ = np.array(c2st_)
296
+
297
+ shape_error = (1 - shape_)*100
298
+ trend_error = (1 - trend_)*100
299
+ c2st_percent = c2st_ * 100
300
+
301
+ all_results = pd.DataFrame({
302
+ "shape": shape_error,
303
+ "trend": trend_error,
304
+ "mle": mle_,
305
+ "c2st": c2st_percent,
306
+ })
307
+ avg = all_results.mean(axis=0).round(3)
308
+ std = all_results.std(axis=0).round(3)
309
+ avg_std = pd.concat([avg, std], axis=1, ignore_index=True)
310
+ avg_std.columns = ["avg", "std"]
311
+ avg_std.index = [
312
+ "shape",
313
+ "trend",
314
+ "mle",
315
+ "c2st",
316
+ ]
317
+
318
+ # Savings
319
+ all_results.to_csv(f"{save_dir}/all_results.csv", index=True)
320
+ avg_std.to_csv(f"{save_dir}/avg_std.csv", index=True)
321
+ print_with_bar(f"The AVG over {num_runs} runs are: \n{avg_std}")
322
+
323
+ def report_test_dcr(self, num_runs):
324
+ save_dir = self.result_save_path
325
+
326
+ dcr_ = []
327
+ dcr_real_ = []
328
+ dcr_test_ = []
329
+ for i in range(num_runs):
330
+ print_with_bar(f"DCR Evaluation Run {i}")
331
+ out_metrics, extras, syn_df = self.evaluate_generation()
332
+ print(f"Results of Run {i} are: \n{out_metrics}")
333
+ dcr_.append(out_metrics["dcr"])
334
+ dcr_real_.append(extras["dcr_real"])
335
+ dcr_test_.append(extras["dcr_test"])
336
+ save_path = os.path.join(save_dir, "all_samples")
337
+ if not os.path.exists(save_path):
338
+ os.makedirs(save_path)
339
+ syn_df.to_csv(os.path.join(save_path, f"samples_{i}.csv"), index=False)
340
+
341
+ dcr_ = np.array(dcr_)
342
+
343
+ dcr_percent = dcr_ * 100
344
+
345
+ all_results = pd.DataFrame({
346
+ "dcr": dcr_percent,
347
+ })
348
+ avg = all_results.mean(axis=0).round(3)
349
+ std = all_results.std(axis=0).round(3)
350
+ avg_std = pd.concat([avg, std], axis=1, ignore_index=True)
351
+ avg_std.columns = ["avg", "std"]
352
+ avg_std.index = [
353
+ "dcr",
354
+ ]
355
+
356
+ # Savings
357
+ all_results.to_csv(f"{save_dir}/all_results.csv", index=True)
358
+ avg_std.to_csv(f"{save_dir}/avg_std.csv", index=True)
359
+ dcr_real = np.concatenate(dcr_real_, axis=0)
360
+ dcr_test = np.concatenate(dcr_test_, axis=0)
361
+ dcr_df = pd.DataFrame({
362
+ "dcr_real": dcr_real,
363
+ "dcr_test": dcr_test
364
+ })
365
+ dcr_df.to_csv(f"{save_dir}/dcr.csv", index=False)
366
+
367
+ print_with_bar(f"The AVG over {num_runs} runs are: \n{avg_std}")
368
+
369
+ def test(self):
370
+ _plot_density = os.environ.get("EFVFM_ADAPTER_TRAIN", "").strip().lower() not in ("1", "true", "yes")
371
+ out_metrics, _, _ = self.evaluate_generation(save_metric_details=True, plot_density=_plot_density)
372
+ print_with_bar(f"Results of the test are: \n{out_metrics}")
373
+ self.logger.log(out_metrics)
374
+ print(out_metrics)
375
+
376
+ def evaluate_generation(self, save_metric_details=False, plot_density=False, ema=False):
377
+ self.flow.eval()
378
+
379
+ # Sample a synthetic table
380
+ env_num_samples = os.environ.get("EFVFM_EVAL_NUM_SAMPLES", "").strip()
381
+ if self.num_samples_to_generate:
382
+ num_samples = self.num_samples_to_generate
383
+ elif env_num_samples:
384
+ num_samples = max(1, int(env_num_samples))
385
+ else:
386
+ num_samples = 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.
387
+ syn_df = self.sample_synthetic(num_samples, ema=ema)
388
+
389
+ # Save the sample
390
+ save_path = os.path.join(self.result_save_path, str(self.curr_epoch), "ema" if ema else "")
391
+ if not os.path.exists(save_path):
392
+ os.makedirs(save_path)
393
+ path = os.path.join(save_path, "samples.csv")
394
+ syn_df.to_csv(path, index=False)
395
+ print(
396
+ f"Samples are saved at {path}"
397
+ )
398
+
399
+ if os.environ.get("EFVFM_ADAPTER_SAMPLE_ONLY", "").strip().lower() in ("1", "true", "yes"):
400
+ return {}, {}, syn_df
401
+
402
+ # Compute evaluation metrics on the sample
403
+ 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.
404
+ out_metrics, extras = self.metrics.evaluate(syn_df_loaded)
405
+
406
+ # Save metrics and metric details
407
+ path = os.path.join(save_path, "all_results.json")
408
+ with open(path, "w") as json_file:
409
+ json.dump(out_metrics, json_file, indent=4, separators=(", ", ": ")) # always locally save the output metrics
410
+ if save_metric_details:
411
+ for name, extra in extras.items():
412
+ if isinstance(extra, pd.DataFrame):
413
+ extra.to_csv(os.path.join(save_path, f"{name}.csv"))
414
+ elif isinstance(extra, dict):
415
+ with open(os.path.join(save_path, f"{name}.json"), "w") as json_file:
416
+ json.dump(extra, json_file, indent=4, separators=(", ", ": "))
417
+ else:
418
+ raise NotImplementedError(f"Extra file generated during evaluations has type {type(extra)}, and code to save this type of file is not implemented")
419
+
420
+ # Plot density figures
421
+ if plot_density:
422
+ img = self.metrics.plot_density(syn_df_loaded)
423
+ path = os.path.join(save_path, "density_plots.png")
424
+ img.save(path)
425
+ print(
426
+ f"The density plots are saved at {path}"
427
+ )
428
+ return out_metrics, extras, syn_df
429
+
430
+ def sample_synthetic(self, num_samples, keep_nan_samples=True, ema=False):
431
+ if ema:
432
+ curr_model = self.to_ema_model()
433
+
434
+ info = self.metrics.info
435
+
436
+ print_with_bar(f"Starting Sampling, total samples to generate = {num_samples}")
437
+ start_time = time.time()
438
+
439
+ syn_data = self.flow.sample_all(num_samples, self.sample_batch_size, keep_nan_samples=keep_nan_samples)
440
+ print(f"Shape of the generated sample = {syn_data.shape}")
441
+
442
+ if keep_nan_samples:
443
+ num_all_zero_row = (syn_data.sum(dim=1) == 0).sum()
444
+ if num_all_zero_row:
445
+ print(f"The generated samples contain {num_all_zero_row} Nan instances!!!")
446
+ self.logger.log({
447
+ 'num_Nan_sample': num_all_zero_row
448
+ })
449
+
450
+ # Recover tables
451
+ num_inverse = self.dataset.num_inverse
452
+ int_inverse = self.dataset.int_inverse
453
+ cat_inverse = self.dataset.cat_inverse
454
+
455
+ syn_num, syn_cat, syn_target = split_num_cat_target(syn_data, info, num_inverse, int_inverse, cat_inverse)
456
+ syn_df = recover_data(syn_num, syn_cat, syn_target, info)
457
+
458
+ idx_name_mapping = info['idx_name_mapping']
459
+ idx_name_mapping = {int(key): value for key, value in idx_name_mapping.items()}
460
+
461
+ syn_df.rename(columns = idx_name_mapping, inplace=True)
462
+
463
+ end_time = time.time()
464
+ print_with_bar(f"Ending Sampling, totoal sampling time = {end_time - start_time}")
465
+
466
+ if ema:
467
+ self.to_model(curr_model)
468
+
469
+ return syn_df
470
+
471
+ def to_ema_model(self):
472
+ curr_model = self.flow._vf_fn
473
+ self.flow._vf_fn = self.ema_model # temporarily install the ema parameters into the model
474
+
475
+ return curr_model
476
+
477
+ def to_model(self, curr_model):
478
+ self.flow._vf_fn = curr_model # give back the parameters
479
+
480
+
481
+ def _as_numpy_float32(x):
482
+ if x is None:
483
+ return np.array([], dtype=np.float32)
484
+ if isinstance(x, torch.Tensor):
485
+ x = x.detach().cpu().numpy()
486
+ return np.asarray(x, dtype=np.float32)
487
+
488
+
489
+ @torch.no_grad()
490
+ def split_num_cat_target(syn_data, info, num_inverse, int_inverse, cat_inverse):
491
+ task_type = info['task_type']
492
+
493
+ num_col_idx = info['num_col_idx']
494
+ cat_col_idx = info['cat_col_idx']
495
+ target_col_idx = info['target_col_idx']
496
+
497
+ n_num_feat = len(num_col_idx)
498
+ n_cat_feat = len(cat_col_idx)
499
+
500
+ if task_type == 'regression':
501
+ n_num_feat += len(target_col_idx)
502
+ else:
503
+ n_cat_feat += len(target_col_idx)
504
+
505
+ syn_num = syn_data[:, :n_num_feat]
506
+ syn_cat = syn_data[:, n_num_feat:]
507
+
508
+ if n_num_feat > 0:
509
+ syn_num = _as_numpy_float32(num_inverse(syn_num))
510
+ syn_num = _as_numpy_float32(int_inverse(syn_num))
511
+ else:
512
+ syn_num = np.zeros((syn_data.shape[0], 0), dtype=np.float32)
513
+ syn_cat = cat_inverse(syn_cat)
514
+
515
+
516
+ if info['task_type'] == 'regression':
517
+ syn_target = syn_num[:, :len(target_col_idx)]
518
+ syn_num = syn_num[:, len(target_col_idx):]
519
+
520
+ else:
521
+ syn_target = syn_cat[:, :len(target_col_idx)]
522
+ syn_cat = syn_cat[:, len(target_col_idx):]
523
+
524
+ return syn_num, syn_cat, syn_target
525
+
526
+ def recover_data(syn_num, syn_cat, syn_target, info):
527
+
528
+ num_col_idx = info['num_col_idx']
529
+ cat_col_idx = info['cat_col_idx']
530
+ target_col_idx = info['target_col_idx']
531
+
532
+
533
+ idx_mapping = info['idx_mapping']
534
+ idx_mapping = {int(key): value for key, value in idx_mapping.items()}
535
+
536
+ syn_df = pd.DataFrame()
537
+
538
+ if info['task_type'] == 'regression':
539
+ for i in range(len(num_col_idx) + len(cat_col_idx) + len(target_col_idx)):
540
+ if i in set(num_col_idx):
541
+ syn_df[i] = syn_num[:, idx_mapping[i]]
542
+ elif i in set(cat_col_idx):
543
+ syn_df[i] = syn_cat[:, idx_mapping[i] - len(num_col_idx)]
544
+ else:
545
+ syn_df[i] = syn_target[:, idx_mapping[i] - len(num_col_idx) - len(cat_col_idx)]
546
+
547
+
548
+ else:
549
+ for i in range(len(num_col_idx) + len(cat_col_idx) + len(target_col_idx)):
550
+ if i in set(num_col_idx):
551
+ syn_df[i] = syn_num[:, idx_mapping[i]]
552
+ elif i in set(cat_col_idx):
553
+ syn_df[i] = syn_cat[:, idx_mapping[i] - len(num_col_idx)]
554
+ else:
555
+ syn_df[i] = syn_target[:, idx_mapping[i] - len(num_col_idx) - len(cat_col_idx)]
556
+
557
+ return syn_df
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/eval/eval_quality.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import numpy as np
3
+ import pandas as pd
4
+ import os
5
+ import sys
6
+ import json
7
+
8
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
9
+ from sklearn.preprocessing import OneHotEncoder
10
+ from synthcity.metrics import eval_statistical
11
+ from synthcity.plugins.core.dataloader import GenericDataLoader
12
+
13
+ pd.options.mode.chained_assignment = None
14
+
15
+ import argparse
16
+
17
+ parser = argparse.ArgumentParser()
18
+ parser.add_argument('--dataname', type=str)
19
+ parser.add_argument('--exp_name', type=str, default=None)
20
+
21
+
22
+ args = parser.parse_args()
23
+
24
+ def evaluate_quality(real_path, syn_path, info_path):
25
+ with open(info_path, 'r') as f:
26
+ info = json.load(f)
27
+
28
+ syn_data = pd.read_csv(syn_path)
29
+ real_data = pd.read_csv(real_path)
30
+
31
+
32
+ ''' Special treatment for default dataset and CoDi model '''
33
+
34
+ real_data.columns = range(len(real_data.columns))
35
+ syn_data.columns = range(len(syn_data.columns))
36
+
37
+ num_col_idx = info['num_col_idx']
38
+ cat_col_idx = info['cat_col_idx']
39
+ target_col_idx = info['target_col_idx']
40
+ if info['task_type'] == 'regression':
41
+ num_col_idx += target_col_idx
42
+ else:
43
+ cat_col_idx += target_col_idx
44
+
45
+ num_real_data = real_data[num_col_idx]
46
+ cat_real_data = real_data[cat_col_idx]
47
+
48
+ num_real_data_np = num_real_data.to_numpy()
49
+ cat_real_data_np = cat_real_data.to_numpy().astype('str')
50
+
51
+
52
+ num_syn_data = syn_data[num_col_idx]
53
+ cat_syn_data = syn_data[cat_col_idx]
54
+
55
+ num_syn_data_np = num_syn_data.to_numpy()
56
+
57
+ # cat_syn_data_np = np.array
58
+ cat_syn_data_np = cat_syn_data.to_numpy().astype('str')
59
+
60
+ encoder = OneHotEncoder()
61
+ encoder.fit(cat_real_data_np)
62
+
63
+
64
+ cat_real_data_oh = encoder.transform(cat_real_data_np).toarray()
65
+ cat_syn_data_oh = encoder.transform(cat_syn_data_np).toarray()
66
+
67
+ le_real_data = pd.DataFrame(np.concatenate((num_real_data_np, cat_real_data_oh), axis = 1)).astype(float)
68
+ le_real_num = pd.DataFrame(num_real_data_np).astype(float)
69
+ le_real_cat = pd.DataFrame(cat_real_data_oh).astype(float)
70
+
71
+
72
+ le_syn_data = pd.DataFrame(np.concatenate((num_syn_data_np, cat_syn_data_oh), axis = 1)).astype(float)
73
+ le_syn_num = pd.DataFrame(num_syn_data_np).astype(float)
74
+ le_syn_cat = pd.DataFrame(cat_syn_data_oh).astype(float)
75
+
76
+ # Check for nan
77
+ if le_syn_data.isnull().values.any():
78
+ nan_coordinate = np.isnan(le_syn_data.to_numpy()).nonzero()
79
+ nan_row = np.unique(nan_coordinate[0])
80
+ print(f"Synthetic data contains NaN at row {nan_row}: ")
81
+ print(le_syn_data.iloc[nan_row])
82
+ return None, None
83
+
84
+
85
+ np.set_printoptions(precision=4)
86
+
87
+ result = []
88
+
89
+ print('=========== All Features ===========')
90
+ print('Data shape: ', le_syn_data.shape)
91
+
92
+ X_syn_loader = GenericDataLoader(le_syn_data)
93
+ X_real_loader = GenericDataLoader(le_real_data)
94
+
95
+ quality_evaluator = eval_statistical.AlphaPrecision()
96
+ qual_res = quality_evaluator.evaluate(X_real_loader, X_syn_loader)
97
+ qual_res = {
98
+ k: v for (k, v) in qual_res.items() if "naive" in k
99
+ } # use the naive implementation of AlphaPrecision
100
+ qual_score = np.mean(list(qual_res.values()))
101
+
102
+ print('alpha precision: {:.6f}, beta recall: {:.6f}'.format(qual_res['delta_precision_alpha_naive'], qual_res['delta_coverage_beta_naive'] ))
103
+
104
+ Alpha_Precision_all = qual_res['delta_precision_alpha_naive']
105
+ Beta_Recall_all = qual_res['delta_coverage_beta_naive']
106
+
107
+ return Alpha_Precision_all, Beta_Recall_all
108
+
109
+ if __name__ == '__main__':
110
+ exp_name = args.exp_name
111
+ assert exp_name is not None, "Experiment name must be provided"
112
+ dataname = args.dataname
113
+ data_dir = f'data/{dataname}'
114
+ info_path = f'{data_dir}/info.json'
115
+ real_path = f'synthetic/{dataname}/real.csv'
116
+
117
+ sample_dir = f"eval/report_runs/{exp_name}/{dataname}/all_samples"
118
+ sample_paths = glob.glob(os.path.join(sample_dir, "*.csv"))
119
+ print(f"{len(sample_paths )} samples loaded from {sample_dir}")
120
+
121
+ alphas, betas = [], []
122
+ for syn_path in sample_paths:
123
+ alpha_precision, beta_recall = evaluate_quality(real_path, syn_path, info_path)
124
+ if (alpha_precision is None) or (beta_recall is None):
125
+ continue
126
+ alphas.append(alpha_precision)
127
+ betas.append(beta_recall)
128
+
129
+ alphas = np.array(alphas)
130
+ betas = np.array(betas)
131
+ alpha_percent = alphas * 100
132
+ beta_percent = betas * 100
133
+
134
+ quality = pd.DataFrame({
135
+ 'alpha': alpha_percent,
136
+ 'beta': beta_percent
137
+ })
138
+ avg = quality.mean(axis=0).round(2)
139
+ std = quality.std(axis=0).round(2)
140
+ quality_avg_std = pd.concat([avg, std], axis=1, ignore_index=True)
141
+ quality_avg_std.columns = ["avg", "std"]
142
+ quality_avg_std.index = ["alpha", "beta"]
143
+
144
+ save_dir = os.path.dirname(sample_dir)
145
+ quality.to_csv(os.path.join(save_dir, "quality.csv"), index=True)
146
+ avg_std = pd.read_csv(os.path.join(save_dir, "avg_std.csv"), index_col=0)
147
+ avg_std = pd.concat([avg_std, quality_avg_std])
148
+ print(avg_std)
149
+ avg_std.to_csv(os.path.join(save_dir, "avg_std.csv"), index=True)
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/eval/mle/mle.py ADDED
@@ -0,0 +1,781 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ from xgboost import XGBClassifier, XGBRegressor
4
+ from sklearn.ensemble import AdaBoostClassifier, RandomForestClassifier, RandomForestRegressor
5
+ from sklearn.linear_model import LogisticRegression, LinearRegression
6
+ from sklearn.neural_network import MLPClassifier, MLPRegressor
7
+ from sklearn.preprocessing import OneHotEncoder, LabelEncoder
8
+ from sklearn.tree import DecisionTreeClassifier
9
+ from sklearn.metrics import classification_report, accuracy_score, f1_score, precision_score, recall_score, roc_auc_score
10
+ from sklearn.metrics import explained_variance_score, mean_squared_error, mean_absolute_error, r2_score
11
+ from sklearn.model_selection import ParameterGrid
12
+ from sklearn.utils._testing import ignore_warnings
13
+ from sklearn.exceptions import ConvergenceWarning
14
+ import logging
15
+ from prdc import compute_prdc
16
+ from tqdm import tqdm
17
+
18
+ CATEGORICAL = "categorical"
19
+ CONTINUOUS = "continuous"
20
+
21
+ _MODELS = {
22
+ 'binclass': [ # 184
23
+ # {
24
+ # 'class': DecisionTreeClassifier, # 48
25
+ # 'kwargs': {
26
+ # 'max_depth': [4, 8, 16, 32],
27
+ # 'min_samples_split': [2, 4, 8],
28
+ # 'min_samples_leaf': [1, 2, 4, 8]
29
+ # }
30
+ # },
31
+ # {
32
+ # 'class': AdaBoostClassifier, # 4
33
+ # 'kwargs': {
34
+ # 'n_estimators': [10, 50, 100, 200]
35
+ # }
36
+ # },
37
+ # {
38
+ # 'class': LogisticRegression, # 36
39
+ # 'kwargs': {
40
+ # 'solver': ['lbfgs'],
41
+ # 'n_jobs': [-1],
42
+ # 'max_iter': [10, 50, 100, 200],
43
+ # 'C': [0.01, 0.1, 1.0],
44
+ # 'tol': [1e-01, 1e-02, 1e-04]
45
+ # }
46
+ # },
47
+ # {
48
+ # 'class': MLPClassifier, # 12
49
+ # 'kwargs': {
50
+ # 'hidden_layer_sizes': [(100, ), (200, ), (100, 100)],
51
+ # 'max_iter': [50, 100],
52
+ # 'alpha': [0.0001, 0.001]
53
+ # }
54
+ # },
55
+ # {
56
+ # 'class': RandomForestClassifier, # 48
57
+ # 'kwargs': {
58
+ # 'max_depth': [8, 16, None],
59
+ # 'min_samples_split': [2, 4, 8],
60
+ # 'min_samples_leaf': [1, 2, 4, 8],
61
+ # 'n_jobs': [-1]
62
+
63
+ # }
64
+ # },
65
+ {
66
+ 'class': XGBClassifier, # 36
67
+ 'kwargs': {
68
+ 'n_estimators': [10, 50, 100],
69
+ 'min_child_weight': [1, 10],
70
+ 'max_depth': [5, 10, 20],
71
+ 'gamma': [0.0, 1.0],
72
+ 'objective': ['binary:logistic'],
73
+ 'nthread': [-1],
74
+ 'tree_method': ['gpu_hist']
75
+ },
76
+ }
77
+
78
+ ],
79
+ 'multiclass': [ # 132
80
+
81
+ # {
82
+ # 'class': MLPClassifier, # 12
83
+ # 'kwargs': {
84
+ # 'hidden_layer_sizes': [(100, ), (200, ), (100, 100)],
85
+ # 'max_iter': [50, 100],
86
+ # 'alpha': [0.0001, 0.001]
87
+ # }
88
+ # },
89
+ # {
90
+ # 'class': DecisionTreeClassifier, # 48
91
+ # 'kwargs': {
92
+ # 'max_depth': [4, 8, 16, 32],
93
+ # 'min_samples_split': [2, 4, 8],
94
+ # 'min_samples_leaf': [1, 2, 4, 8]
95
+ # }
96
+ # },
97
+ # {
98
+ # 'class': RandomForestClassifier, # 36
99
+ # 'kwargs': {
100
+ # 'max_depth': [8, 16, None],
101
+ # 'min_samples_split': [2, 4, 8],
102
+ # 'min_samples_leaf': [1, 2, 4, 8],
103
+ # 'n_jobs': [-1]
104
+
105
+ # }
106
+ # },
107
+ {
108
+ 'class': XGBClassifier, # 36
109
+ 'kwargs': {
110
+ 'n_estimators': [10, 50, 100],
111
+ 'min_child_weight': [1, 10],
112
+ 'max_depth': [5, 10, 20],
113
+ 'gamma': [0.0, 1.0],
114
+ 'objective': ['binary:logistic'],
115
+ 'nthread': [-1],
116
+ 'tree_method': ['gpu_hist']
117
+ }
118
+ }
119
+
120
+ ],
121
+ 'regression': [ # 84
122
+ # {
123
+ # 'class': LinearRegression,
124
+ # },
125
+ # {
126
+ # 'class': MLPRegressor, # 12
127
+ # 'kwargs': {
128
+ # 'hidden_layer_sizes': [(100, ), (200, ), (100, 100)],
129
+ # 'max_iter': [50, 100],
130
+ # 'alpha': [0.0001, 0.001]
131
+ # }
132
+ #},
133
+ {
134
+ 'class': XGBRegressor, # 36
135
+ 'kwargs': {
136
+ 'n_estimators': [10, 50, 100],
137
+ 'min_child_weight': [1, 10],
138
+ 'max_depth': [5, 10, 20],
139
+ 'gamma': [0.0, 1.0],
140
+ 'objective': ['reg:linear'],
141
+ 'nthread': [-1],
142
+ 'tree_method': ['gpu_hist']
143
+ }
144
+ },
145
+ # {
146
+ # 'class': RandomForestRegressor, # 36
147
+ # 'kwargs': {
148
+ # 'max_depth': [8, 16, None],
149
+ # 'min_samples_split': [2, 4, 8],
150
+ # 'min_samples_leaf': [1, 2, 4, 8],
151
+ # 'n_jobs': [-1]
152
+ # }
153
+ # }
154
+ ]
155
+ }
156
+
157
+ def feat_transform(data, info, label_encoder = None, encoders = None, cmax = None, cmin = None):
158
+ num_col_idx = info['num_col_idx']
159
+ cat_col_idx = info['cat_col_idx']
160
+ target_col_idx = info['target_col_idx']
161
+
162
+ num_cols = len(num_col_idx + cat_col_idx + target_col_idx)
163
+ features = []
164
+
165
+ if not encoders:
166
+ encoders = dict()
167
+ for idx in range(num_cols):
168
+ col = data[:, idx]
169
+
170
+ if idx in target_col_idx:
171
+
172
+ if info['task_type'] != 'regression':
173
+
174
+ if not label_encoder:
175
+ label_encoder = LabelEncoder()
176
+ label_encoder.fit(col)
177
+
178
+ encoded_labels = label_encoder.transform(col)
179
+ labels = encoded_labels
180
+ else:
181
+ col = col.astype(np.float32)
182
+ labels = col.astype(np.float32)
183
+
184
+ continue
185
+
186
+ if idx in num_col_idx:
187
+ col = col.astype(np.float32)
188
+
189
+ if not cmin:
190
+ cmin = col.min()
191
+
192
+ if not cmax:
193
+ cmax = col.max()
194
+
195
+ if cmin >= 0 and cmax >= 1e3:
196
+ feature = np.log(np.maximum(col, 1e-2))
197
+
198
+ else:
199
+ feature = (col - cmin) / (cmax - cmin) * 5
200
+
201
+ elif idx in cat_col_idx:
202
+ encoder = encoders.get(idx)
203
+ col = col.reshape(-1, 1)
204
+ if encoder:
205
+ feature = encoder.transform(col)
206
+ else:
207
+ # encoder = OneHotEncoder(sparse=False, handle_unknown='ignore')
208
+ encoder = OneHotEncoder(sparse_output=False, handle_unknown='ignore') # New in version 1.2: sparse was renamed to sparse_output
209
+ encoders[idx] = encoder
210
+ feature = encoder.fit_transform(col)
211
+
212
+
213
+ features.append(feature)
214
+ features = np.column_stack(features)
215
+ return features, labels, label_encoder, encoders, cmax, cmin
216
+
217
+
218
+ def prepare_ml_problem(train, test, info, val=None):
219
+ # test_X, test_y, label_encoder, encoders = feat_transform(test, info)
220
+ # train_X, train_y, _, _ = feat_transform(train, info, label_encoder, encoders)
221
+
222
+ train_X, train_y, label_encoder, encoders, cmax, cmin = feat_transform(train, info)
223
+ test_X, test_y, _, _ , _, _ = feat_transform(test, info, label_encoder, encoders, cmax, cmin)
224
+
225
+ if val is not None:
226
+ val_X, val_y, _, _, _, _ = feat_transform(val, info, label_encoder, encoders, cmax, cmin)
227
+ else:
228
+ total_train_num = train_X.shape[0]
229
+ val_num = int(total_train_num / 9)
230
+
231
+ total_train_idx = np.arange(total_train_num)
232
+ np.random.shuffle(total_train_idx)
233
+ train_idx = total_train_idx[val_num:]
234
+ val_idx = total_train_idx[:val_num]
235
+
236
+
237
+
238
+ # val_X, val_y = train_X[val_idx], train_y[val_idx]
239
+ # train_X, train_y = train_X[train_idx], train_y[train_idx]
240
+
241
+ # model = _MODELS[info['task_type']]
242
+
243
+ # return train_X, train_y, train_X, train_y, test_X, test_y, model
244
+
245
+
246
+
247
+ val_X, val_y = train_X[val_idx], train_y[val_idx]
248
+ train_X, train_y = train_X[train_idx], train_y[train_idx]
249
+
250
+ model = _MODELS[info['task_type']]
251
+
252
+ return train_X, train_y, val_X, val_y, test_X, test_y, model
253
+
254
+ class FeatureMaker:
255
+
256
+ def __init__(self, metadata, label_column='label', label_type='int', sample=50000):
257
+ self.columns = metadata['columns']
258
+ self.label_column = label_column
259
+ self.label_type = label_type
260
+ self.sample = sample
261
+ self.encoders = dict()
262
+
263
+ def make_features(self, data):
264
+ data = data.copy()
265
+ np.random.shuffle(data)
266
+ data = data[:self.sample]
267
+
268
+ features = []
269
+ labels = []
270
+
271
+ for index, cinfo in enumerate(self.columns):
272
+ col = data[:, index]
273
+ if cinfo['name'] == self.label_column:
274
+ if self.label_type == 'int':
275
+ labels = col.astype(int)
276
+ elif self.label_type == 'float':
277
+ labels = col.astype(float)
278
+ else:
279
+ assert 0, 'unkown label type'
280
+ continue
281
+
282
+ if cinfo['type'] == CONTINUOUS:
283
+ cmin = cinfo['min']
284
+ cmax = cinfo['max']
285
+ if cmin >= 0 and cmax >= 1e3:
286
+ feature = np.log(np.maximum(col, 1e-2))
287
+
288
+ else:
289
+ feature = (col - cmin) / (cmax - cmin) * 5
290
+
291
+ else:
292
+ if cinfo['size'] <= 2:
293
+ feature = col
294
+
295
+ else:
296
+ encoder = self.encoders.get(index)
297
+ col = col.reshape(-1, 1)
298
+ if encoder:
299
+ feature = encoder.transform(col)
300
+ else:
301
+ encoder = OneHotEncoder(sparse=False, handle_unknown='ignore')
302
+ self.encoders[index] = encoder
303
+ feature = encoder.fit_transform(col)
304
+
305
+ features.append(feature)
306
+
307
+ features = np.column_stack(features)
308
+
309
+ return features, labels
310
+
311
+
312
+ def _prepare_ml_problem(train, val, test, metadata, eval):
313
+ fm = FeatureMaker(metadata)
314
+ x_trains, y_trains = [], []
315
+
316
+ for i in train:
317
+ x_train, y_train = fm.make_features(i)
318
+ x_trains.append(x_train)
319
+ y_trains.append(y_train)
320
+
321
+ x_val, y_val = fm.make_features(val)
322
+ if eval is None:
323
+ x_test = None
324
+ y_test = None
325
+ else:
326
+ x_test, y_test = fm.make_features(test)
327
+ model = _MODELS[metadata['problem_type']]
328
+
329
+ return x_trains, y_trains, x_val, y_val, x_test, y_test, model
330
+
331
+
332
+ def _weighted_f1(y_test, pred):
333
+ report = classification_report(y_test, pred, output_dict=True)
334
+ classes = list(report.keys())[:-3]
335
+ proportion = [ report[i]['support'] / len(y_test) for i in classes]
336
+ weighted_f1 = np.sum(list(map(lambda i, prop: report[i]['f1-score']* (1-prop)/(len(classes)-1), classes, proportion)))
337
+ return weighted_f1
338
+
339
+
340
+ @ignore_warnings(category=ConvergenceWarning)
341
+ def _evaluate_multi_classification(train, test, info, val=None):
342
+ x_trains, y_trains, x_valid, y_valid, x_test, y_test, classifiers = prepare_ml_problem(train, test, info, val=val)
343
+ best_f1_scores = []
344
+ unique_labels = np.unique(y_trains)
345
+
346
+
347
+ best_f1_scores = []
348
+ best_weighted_scores = []
349
+ best_auroc_scores = []
350
+ best_acc_scores = []
351
+ best_avg_scores = []
352
+
353
+ for model_spec in classifiers:
354
+ model_class = model_spec['class']
355
+ model_kwargs = model_spec.get('kwargs', dict())
356
+ model_repr = model_class.__name__
357
+
358
+ unique_labels = np.unique(y_trains)
359
+
360
+ param_set = list(ParameterGrid(model_kwargs))
361
+
362
+ results = []
363
+ for param in tqdm(param_set):
364
+ model = model_class(**param)
365
+
366
+ try:
367
+ model.fit(x_trains, y_trains)
368
+ except:
369
+ pass
370
+
371
+ if len(unique_labels) != len(np.unique(y_valid)):
372
+ pred = [unique_labels[0]] * len(x_valid)
373
+ pred_prob = np.array([1.] * len(x_valid))
374
+ else:
375
+ pred = model.predict(x_valid)
376
+ pred_prob = model.predict_proba(x_valid)
377
+
378
+ macro_f1 = f1_score(y_valid, pred, average='macro')
379
+ weighted_f1 = _weighted_f1(y_valid, pred)
380
+ acc = accuracy_score(y_valid, pred)
381
+
382
+ # 3. auroc
383
+ # size = [a["size"] for a in metadata["columns"] if a["name"] == "label"][0]
384
+ size = len(set(unique_labels))
385
+ rest_label = set(range(size)) - set(unique_labels)
386
+ tmp = []
387
+ j = 0
388
+ for i in range(size):
389
+ if i in rest_label:
390
+ tmp.append(np.array([0] * y_valid.shape[0])[:,np.newaxis])
391
+ else:
392
+ try:
393
+ tmp.append(pred_prob[:,[j]])
394
+ except:
395
+ tmp.append(pred_prob[:, np.newaxis])
396
+ j += 1
397
+
398
+ roc_auc = roc_auc_score(np.eye(size)[y_valid], np.hstack(tmp), multi_class='ovr')
399
+
400
+ results.append(
401
+ {
402
+ "name": model_repr,
403
+ "param": param,
404
+ "macro_f1": macro_f1,
405
+ "weighted_f1": weighted_f1,
406
+ "roc_auc": roc_auc,
407
+ "accuracy": acc
408
+ }
409
+ )
410
+
411
+ results = pd.DataFrame(results)
412
+ results['avg'] = results.loc[:, ['macro_f1', 'weighted_f1', 'roc_auc']].mean(axis=1)
413
+ best_f1_param = results.param[results.macro_f1.idxmax()]
414
+ best_weighted_param = results.param[results.weighted_f1.idxmax()]
415
+ best_auroc_param = results.param[results.roc_auc.idxmax()]
416
+ best_acc_param = results.param[results.accuracy.idxmax()]
417
+ best_avg_param = results.param[results.avg.idxmax()]
418
+
419
+
420
+ # test the best model
421
+ results = pd.DataFrame(results)
422
+ # best_param = results.param[results.macro_f1.idxmax()]
423
+
424
+ def _calc(best_model):
425
+ best_scores = []
426
+
427
+ x_train = x_trains
428
+ y_train = y_trains
429
+
430
+ try:
431
+ best_model.fit(x_train, y_train)
432
+ except:
433
+ pass
434
+
435
+ if len(unique_labels) != len(np.unique(y_test)):
436
+ pred = [unique_labels[0]] * len(x_test)
437
+ pred_prob = np.array([1.] * len(x_test))
438
+ else:
439
+ pred = best_model.predict(x_test)
440
+ pred_prob = best_model.predict_proba(x_test)
441
+
442
+ macro_f1 = f1_score(y_test, pred, average='macro')
443
+ weighted_f1 = _weighted_f1(y_test, pred)
444
+ acc = accuracy_score(y_test, pred)
445
+
446
+ # 3. auroc
447
+ size = len(set(unique_labels))
448
+ rest_label = set(range(size)) - set(unique_labels)
449
+ tmp = []
450
+ j = 0
451
+ for i in range(size):
452
+ if i in rest_label:
453
+ tmp.append(np.array([0] * y_test.shape[0])[:,np.newaxis])
454
+ else:
455
+ try:
456
+ tmp.append(pred_prob[:,[j]])
457
+ except:
458
+ tmp.append(pred_prob[:, np.newaxis])
459
+ j += 1
460
+ roc_auc = roc_auc_score(np.eye(size)[y_test], np.hstack(tmp), multi_class='ovr')
461
+
462
+ best_scores.append(
463
+ {
464
+ "name": model_repr,
465
+ "macro_f1": macro_f1,
466
+ "weighted_f1": weighted_f1,
467
+ "roc_auc": roc_auc,
468
+ "accuracy": acc
469
+ }
470
+ )
471
+ return pd.DataFrame(best_scores)
472
+
473
+ def _df(dataframe):
474
+ return {
475
+ "name": model_repr,
476
+ "macro_f1": dataframe.macro_f1.values[0],
477
+ "roc_auc": dataframe.roc_auc.values[0],
478
+ "weighted_f1": dataframe.weighted_f1.values[0],
479
+ "accuracy": dataframe.accuracy.values[0],
480
+ }
481
+
482
+ best_f1_scores.append(_df(_calc(model_class(**best_f1_param))))
483
+ best_weighted_scores.append(_df(_calc(model_class(**best_weighted_param))))
484
+ best_auroc_scores.append(_df(_calc(model_class(**best_auroc_param))))
485
+ best_acc_scores.append(_df(_calc(model_class(**best_acc_param))))
486
+ best_avg_scores.append(_df(_calc(model_class(**best_avg_param))))
487
+
488
+ return best_f1_scores, best_weighted_scores, best_auroc_scores, best_acc_scores, best_avg_scores
489
+
490
+ @ignore_warnings(category=ConvergenceWarning)
491
+ def _evaluate_binary_classification(train, test, info, val=None):
492
+ x_trains, y_trains, x_valid, y_valid, x_test, y_test, classifiers = prepare_ml_problem(train, test, info, val=val)
493
+
494
+ unique_labels = np.unique(y_trains)
495
+
496
+ best_f1_scores = []
497
+ best_weighted_scores = []
498
+ best_auroc_scores = []
499
+ best_acc_scores = []
500
+ best_avg_scores = []
501
+
502
+ for model_spec in classifiers:
503
+
504
+ model_class = model_spec['class']
505
+ model_kwargs = model_spec.get('kwargs', dict())
506
+ model_repr = model_class.__name__
507
+
508
+ unique_labels = np.unique(y_trains)
509
+
510
+ param_set = list(ParameterGrid(model_kwargs))
511
+
512
+ results = []
513
+ for param in tqdm(param_set):
514
+ model = model_class(**param)
515
+
516
+ try:
517
+ model.fit(x_trains, y_trains)
518
+ except ValueError:
519
+ pass
520
+
521
+ if len(unique_labels) == 1:
522
+ pred = [unique_labels[0]] * len(x_valid)
523
+ pred_prob = np.array([1.] * len(x_valid))
524
+ else:
525
+ pred = model.predict(x_valid)
526
+ pred_prob = model.predict_proba(x_valid)
527
+
528
+ binary_f1 = f1_score(y_valid, pred, average='binary')
529
+ weighted_f1 = _weighted_f1(y_valid, pred)
530
+ acc = accuracy_score(y_valid, pred)
531
+ precision = precision_score(y_valid, pred, average='binary')
532
+ recall = recall_score(y_valid, pred, average='binary')
533
+ macro_f1 = f1_score(y_valid, pred, average='macro')
534
+
535
+ # auroc
536
+ size = 2
537
+ rest_label = set(range(size)) - set(unique_labels)
538
+ tmp = []
539
+ j = 0
540
+ for i in range(size):
541
+ if i in rest_label:
542
+ tmp.append(np.array([0] * y_valid.shape[0])[:,np.newaxis])
543
+ else:
544
+ try:
545
+ tmp.append(pred_prob[:,[j]])
546
+ except:
547
+ tmp.append(pred_prob[:, np.newaxis])
548
+ j += 1
549
+ roc_auc = roc_auc_score(np.eye(size)[y_valid], np.hstack(tmp))
550
+
551
+ results.append(
552
+ {
553
+ "name": model_repr,
554
+ "param": param,
555
+ "binary_f1": binary_f1,
556
+ "weighted_f1": weighted_f1,
557
+ "roc_auc": roc_auc,
558
+ "accuracy": acc,
559
+ "precision": precision,
560
+ "recall": recall,
561
+ "macro_f1": macro_f1
562
+ }
563
+ )
564
+
565
+
566
+ # test the best model
567
+ results = pd.DataFrame(results)
568
+ results['avg'] = results.loc[:, ['binary_f1', 'weighted_f1', 'roc_auc']].mean(axis=1)
569
+ best_f1_param = results.param[results.binary_f1.idxmax()]
570
+ best_weighted_param = results.param[results.weighted_f1.idxmax()]
571
+ best_auroc_param = results.param[results.roc_auc.idxmax()]
572
+ best_acc_param = results.param[results.accuracy.idxmax()]
573
+ best_avg_param = results.param[results.avg.idxmax()]
574
+
575
+
576
+ def _calc(best_model):
577
+ best_scores = []
578
+
579
+ best_model.fit(x_trains, y_trains)
580
+
581
+ if len(unique_labels) == 1:
582
+ pred = [unique_labels[0]] * len(x_test)
583
+ pred_prob = np.array([1.] * len(x_test))
584
+ else:
585
+ pred = best_model.predict(x_test)
586
+ pred_prob = best_model.predict_proba(x_test)
587
+
588
+ binary_f1 = f1_score(y_test, pred, average='binary')
589
+ weighted_f1 = _weighted_f1(y_test, pred)
590
+ acc = accuracy_score(y_test, pred)
591
+ precision = precision_score(y_test, pred, average='binary')
592
+ recall = recall_score(y_test, pred, average='binary')
593
+ macro_f1 = f1_score(y_test, pred, average='macro')
594
+
595
+ # auroc
596
+ size = 2
597
+ rest_label = set(range(size)) - set(unique_labels)
598
+ tmp = []
599
+ j = 0
600
+ for i in range(size):
601
+ if i in rest_label:
602
+ tmp.append(np.array([0] * y_test.shape[0])[:,np.newaxis])
603
+ else:
604
+ try:
605
+ tmp.append(pred_prob[:,[j]])
606
+ except:
607
+ tmp.append(pred_prob[:, np.newaxis])
608
+ j += 1
609
+ try:
610
+ roc_auc = roc_auc_score(np.eye(size)[y_test], np.hstack(tmp))
611
+ except ValueError:
612
+ tmp[1] = tmp[1].reshape(20000, 1)
613
+ roc_auc = roc_auc_score(np.eye(size)[y_test], np.hstack(tmp))
614
+
615
+ best_scores.append(
616
+ {
617
+ "name": model_repr,
618
+ # "param": param,
619
+ "binary_f1": binary_f1,
620
+ "weighted_f1": weighted_f1,
621
+ "roc_auc": roc_auc,
622
+ "accuracy": acc,
623
+ "precision": precision,
624
+ "recall": recall,
625
+ "macro_f1": macro_f1
626
+ }
627
+ )
628
+
629
+ return pd.DataFrame(best_scores)
630
+ def _df(dataframe):
631
+ return {
632
+ "name": model_repr,
633
+ "binary_f1": dataframe.binary_f1.values[0],
634
+ "roc_auc": dataframe.roc_auc.values[0],
635
+ "weighted_f1": dataframe.weighted_f1.values[0],
636
+ "accuracy": dataframe.accuracy.values[0],
637
+ }
638
+
639
+ best_f1_scores.append(_df(_calc(model_class(**best_f1_param))))
640
+ best_weighted_scores.append(_df(_calc(model_class(**best_weighted_param))))
641
+ best_auroc_scores.append(_df(_calc(model_class(**best_auroc_param))))
642
+ best_acc_scores.append(_df(_calc(model_class(**best_acc_param))))
643
+ best_avg_scores.append(_df(_calc(model_class(**best_avg_param))))
644
+
645
+ return best_f1_scores, best_weighted_scores, best_auroc_scores, best_acc_scores, best_avg_scores
646
+
647
+ @ignore_warnings(category=ConvergenceWarning)
648
+ def _evaluate_regression(train, test, info, val=None):
649
+
650
+ x_trains, y_trains, x_valid, y_valid, x_test, y_test, regressors = prepare_ml_problem(train, test, info, val=val)
651
+
652
+
653
+ best_r2_scores = []
654
+ best_ev_scores = []
655
+ best_mae_scores = []
656
+ best_rmse_scores = []
657
+ best_avg_scores = []
658
+
659
+ y_trains = np.log(np.clip(y_trains, 1, 20000))
660
+ y_test = np.log(np.clip(y_test, 1, 20000))
661
+
662
+ for model_spec in regressors:
663
+ model_class = model_spec['class']
664
+ model_kwargs = model_spec.get('kwargs', dict())
665
+ model_repr = model_class.__name__
666
+
667
+ param_set = list(ParameterGrid(model_kwargs))
668
+
669
+ results = []
670
+ for param in tqdm(param_set):
671
+ model = model_class(**param)
672
+ model.fit(x_trains, y_trains)
673
+ pred = model.predict(x_valid)
674
+
675
+ r2 = r2_score(y_valid, pred)
676
+ explained_variance = explained_variance_score(y_valid, pred)
677
+ mean_squared = mean_squared_error(y_valid, pred)
678
+ root_mean_squared = np.sqrt(mean_squared)
679
+ mean_absolute = mean_absolute_error(y_valid, pred)
680
+
681
+ results.append(
682
+ {
683
+ "name": model_repr,
684
+ "param": param,
685
+ "r2": r2,
686
+ "explained_variance": explained_variance,
687
+ "mean_squared": mean_squared,
688
+ "mean_absolute": mean_absolute,
689
+ "rmse": root_mean_squared
690
+ }
691
+ )
692
+
693
+ results = pd.DataFrame(results)
694
+ # results['avg'] = results.loc[:, ['r2', 'rmse']].mean(axis=1)
695
+ best_r2_param = results.param[results.r2.idxmax()]
696
+ best_ev_param = results.param[results.explained_variance.idxmax()]
697
+ best_mae_param = results.param[results.mean_absolute.idxmin()]
698
+ best_rmse_param = results.param[results.rmse.idxmin()]
699
+ # best_avg_param = results.param[results.avg.idxmax()]
700
+
701
+ def _calc(best_model):
702
+ best_scores = []
703
+ x_train, y_train = x_trains, y_trains
704
+
705
+ best_model.fit(x_train, y_train)
706
+ pred = best_model.predict(x_test)
707
+
708
+ r2 = r2_score(y_test, pred)
709
+ explained_variance = explained_variance_score(y_test, pred)
710
+ mean_squared = mean_squared_error(y_test, pred)
711
+ root_mean_squared = np.sqrt(mean_squared)
712
+ mean_absolute = mean_absolute_error(y_test, pred)
713
+
714
+ best_scores.append(
715
+ {
716
+ "name": model_repr,
717
+ "param": param,
718
+ "r2": r2,
719
+ "explained_variance": explained_variance,
720
+ "mean_squared": mean_squared,
721
+ "mean_absolute": mean_absolute,
722
+ "rmse": root_mean_squared
723
+ }
724
+ )
725
+
726
+ return pd.DataFrame(best_scores)
727
+
728
+ def _df(dataframe):
729
+ return {
730
+ "name": model_repr,
731
+ "r2": dataframe.r2.values[0].astype(float),
732
+ "explained_variance": dataframe.explained_variance.values[0].astype(float),
733
+ "MAE": dataframe.mean_absolute.values[0].astype(float),
734
+ "RMSE": dataframe.rmse.values[0].astype(float),
735
+ }
736
+
737
+ best_r2_scores.append(_df(_calc(model_class(**best_r2_param))))
738
+ best_ev_scores.append(_df(_calc(model_class(**best_ev_param))))
739
+ best_mae_scores.append(_df(_calc(model_class(**best_mae_param))))
740
+ best_rmse_scores.append(_df(_calc(model_class(**best_rmse_param))))
741
+
742
+ return best_r2_scores, best_rmse_scores
743
+
744
+ @ignore_warnings(category=ConvergenceWarning)
745
+ def compute_diversity(train, fake):
746
+ nearest_k = 5
747
+ if train.shape[0] >= 50000:
748
+ num = np.random.randint(0, train.shape[0], 50000)
749
+ real_features = train[num]
750
+ fake_features_lst = [i[num] for i in fake]
751
+ else:
752
+ num = train.shape[0]
753
+ real_features = train[:num]
754
+ fake_features_lst = [i[:num] for i in fake]
755
+ scores = []
756
+ for i, data in enumerate(fake_features_lst):
757
+ fake_features = data
758
+ metrics = compute_prdc(real_features=real_features,
759
+ fake_features=fake_features,
760
+ nearest_k=nearest_k)
761
+ metrics['i'] = i
762
+ scores.append(metrics)
763
+ return pd.DataFrame(scores).mean(axis=0), pd.DataFrame(scores).std(axis=0)
764
+
765
+ _EVALUATORS = {
766
+ 'binclass': _evaluate_binary_classification,
767
+ 'multiclass': _evaluate_multi_classification,
768
+ 'regression': _evaluate_regression
769
+ }
770
+
771
+ def get_evaluator(problem_type):
772
+ return _EVALUATORS[problem_type]
773
+
774
+
775
+ def compute_scores(train, test, synthesized_data, metadata, eval):
776
+ a, b, c = _EVALUATORS[metadata['problem_type']](train=train, test=test, fake=synthesized_data, metadata=metadata, eval=eval)
777
+ if eval is None:
778
+ return a.mean(axis=0), a.std(axis=0), a[['name','param']]
779
+ else:
780
+ return a.mean(axis=0), a.std(axis=0)
781
+
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/eval/mle/tabular_dataload.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The Google Research Authors.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ # pylint: skip-file
17
+ """Return training and evaluation/test datasets from config files."""
18
+ import torch
19
+ import numpy as np
20
+ import pandas as pd
21
+ from tabular_transformer import GeneralTransformer
22
+ import json
23
+ import logging
24
+ import os
25
+
26
+ CATEGORICAL = "categorical"
27
+ CONTINUOUS = "continuous"
28
+
29
+ LOGGER = logging.getLogger(__name__)
30
+
31
+ DATA_PATH = os.path.join(os.path.dirname(__file__), 'tabular_datasets')
32
+
33
+ def _load_json(path):
34
+ with open(path) as json_file:
35
+ return json.load(json_file)
36
+
37
+
38
+ def _load_file(filename, loader):
39
+ local_path = os.path.join(DATA_PATH, filename)
40
+
41
+ if loader == np.load:
42
+ return loader(local_path, allow_pickle=True)
43
+ return loader(local_path)
44
+
45
+
46
+ def _get_columns(metadata):
47
+ categorical_columns = list()
48
+
49
+ for column_idx, column in enumerate(metadata['columns']):
50
+ if column['type'] == CATEGORICAL:
51
+ categorical_columns.append(column_idx)
52
+
53
+ return categorical_columns
54
+
55
+
56
+ def load_data(name):
57
+ data_dir = f'data/{name}'
58
+ info_path = f'{data_dir}/info.json'
59
+
60
+ train = pd.read_csv(f'{data_dir}/train.csv').to_numpy()
61
+ test = pd.read_csv(f'{data_dir}/test.csv').to_numpy()
62
+
63
+ with open(f'{data_dir}/info.json', 'r') as f:
64
+ info = json.load(f)
65
+
66
+ task_type = info['task_type']
67
+
68
+ num_cols = info['num_col_idx']
69
+ cat_cols = info['cat_col_idx']
70
+ target_cols = info['target_col_idx']
71
+
72
+ if task_type != 'regression':
73
+ cat_cols = cat_cols + target_cols
74
+
75
+ return train, test, (cat_cols, info)
76
+
77
+
78
+ def get_dataset(FLAGS, evaluation=False):
79
+
80
+ batch_size = FLAGS.training_batch_size if not evaluation else FLAGS.eval_batch_size
81
+
82
+ if batch_size % torch.cuda.device_count() != 0:
83
+ raise ValueError(f'Batch sizes ({batch_size} must be divided by'
84
+ f'the number of devices ({torch.cuda.device_count()})')
85
+
86
+
87
+ # Create dataset builders for tabular data.
88
+ train, test, cols = load_data(FLAGS.dataname)
89
+ cols_idx = list(np.arange(train.shape[1]))
90
+ dis_idx = cols[0]
91
+ con_idx = [x for x in cols_idx if x not in dis_idx]
92
+
93
+ #split continuous and categorical
94
+ train_con = train[:,con_idx]
95
+ train_dis = train[:,dis_idx]
96
+
97
+ #new index
98
+ cat_idx_ = list(np.arange(train_dis.shape[1]))[:len(cols[0])]
99
+
100
+ transformer_con = GeneralTransformer()
101
+ transformer_dis = GeneralTransformer()
102
+
103
+ transformer_con.fit(train_con, [])
104
+ transformer_dis.fit(train_dis, cat_idx_)
105
+
106
+ train_con_data = transformer_con.transform(train_con)
107
+ train_dis_data = transformer_dis.transform(train_dis)
108
+
109
+
110
+ return train, train_con_data, train_dis_data, test, (transformer_con, transformer_dis, cols[1]), con_idx, dis_idx
111
+
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/eval/mle/tabular_transformer.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+
4
+ CATEGORICAL = "categorical"
5
+ CONTINUOUS = "continuous"
6
+
7
+ class Transformer:
8
+
9
+ @staticmethod
10
+ def get_metadata(data, categorical_columns=tuple()):
11
+ meta = []
12
+
13
+ df = pd.DataFrame(data)
14
+ for index in df:
15
+ column = df[index]
16
+
17
+ if index in categorical_columns:
18
+ mapper = column.value_counts().index.tolist()
19
+ meta.append({
20
+ "name": index,
21
+ "type": CATEGORICAL,
22
+ "size": len(mapper),
23
+ "i2s": mapper
24
+ })
25
+ else:
26
+ meta.append({
27
+ "name": index,
28
+ "type": CONTINUOUS,
29
+ "min": column.min(),
30
+ "max": column.max(),
31
+ })
32
+
33
+ return meta
34
+
35
+ def fit(self, data, categorical_columns=tuple()):
36
+ raise NotImplementedError
37
+
38
+ def transform(self, data):
39
+ raise NotImplementedError
40
+
41
+ def inverse_transform(self, data):
42
+ raise NotImplementedError
43
+
44
+
45
+ class GeneralTransformer(Transformer):
46
+
47
+ def __init__(self, act='tanh'):
48
+ self.act = act
49
+ self.meta = None
50
+ self.output_dim = None
51
+
52
+ def fit(self, data, categorical_columns=tuple()):
53
+ self.meta = self.get_metadata(data, categorical_columns)
54
+ self.output_dim = 0
55
+ for info in self.meta:
56
+ if info['type'] in [CONTINUOUS]:
57
+ self.output_dim += 1
58
+ else:
59
+ self.output_dim += info['size']
60
+
61
+ def transform(self, data):
62
+ data_t = []
63
+ self.output_info = []
64
+ for id_, info in enumerate(self.meta):
65
+ col = data[:, id_]
66
+ if info['type'] == CONTINUOUS:
67
+ col = (col - (info['min'])) / (info['max'] - info['min'])
68
+ if self.act == 'tanh':
69
+ col = col * 2 - 1
70
+ data_t.append(col.reshape([-1, 1]))
71
+ self.output_info.append((1, self.act))
72
+
73
+ else:
74
+ col_t = np.zeros([len(data), info['size']])
75
+ idx = list(map(info['i2s'].index, col))
76
+ col_t[np.arange(len(data)), idx] = 1
77
+ data_t.append(col_t)
78
+ self.output_info.append((info['size'], 'softmax'))
79
+
80
+ return np.concatenate(data_t, axis=1)
81
+
82
+ def inverse_transform(self, data):
83
+ if self.meta[1]['type'] == CONTINUOUS:
84
+ data_t = np.zeros([len(data), len(self.meta)])
85
+ else:
86
+ dtype = np.dtype('U50')
87
+ data_t = np.empty([len(data), len(self.meta)], dtype=dtype)
88
+
89
+
90
+ data = data.copy()
91
+ for id_, info in enumerate(self.meta):
92
+
93
+ if info['type'] == CONTINUOUS:
94
+ current = data[:, 0]
95
+ data = data[:, 1:]
96
+
97
+ if self.act == 'tanh':
98
+ current = (current + 1) / 2
99
+
100
+ current = np.clip(current, 0, 1)
101
+ data_t[:, id_] = current * (info['max'] - info['min']) + info['min']
102
+
103
+ else:
104
+ current = data[:, :info['size']]
105
+ data = data[:, info['size']:]
106
+ idx = np.argmax(current, axis=1)
107
+ recovered = list(map(info['i2s'].__getitem__, idx))
108
+
109
+ data_t[:, id_] = recovered
110
+ return data_t
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/eval/visualize_density.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # %%
2
+ import numpy as np
3
+ import pandas as pd
4
+ import torch
5
+ import os
6
+
7
+ import json
8
+
9
+ # Metrics
10
+ from sdmetrics.visualization import get_column_plot
11
+
12
+ import plotly.io as pio
13
+ from PIL import Image
14
+ from io import BytesIO
15
+
16
+ from tqdm import tqdm
17
+ import argparse
18
+
19
+ def main(args):
20
+ dataname = args.dataname
21
+ sample_file_name = args.sample_file_name
22
+
23
+ syn_path = f'synthetic/{dataname}/{sample_file_name}'
24
+ real_path = f'synthetic/{dataname}/real.csv'
25
+
26
+ syn_data = pd.read_csv(syn_path)
27
+ real_data = pd.read_csv(real_path)
28
+
29
+ print((real_data[:2]))
30
+
31
+ data_dir = f'data/{dataname}'
32
+ with open(f'{data_dir}/info.json', 'r') as f:
33
+ info = json.load(f)
34
+
35
+ big_img = plot_density(syn_data, real_data, info)
36
+
37
+ save_dir = f"eval/density_graphs/{dataname}"
38
+ if not os.path.exists(save_dir):
39
+ os.makedirs(save_dir)
40
+ save_path = os.path.join(save_dir, sample_file_name.replace('.csv', '.png'))
41
+ big_img.save(save_path)
42
+ print(f"Saved density graph to {save_path}")
43
+
44
+ def plot_density(syn_data, real_data, info, num_per_row=3):
45
+ column_names = info['column_names']
46
+ num_cat = len(column_names)
47
+ num_col = num_per_row
48
+ num_row = (num_cat-1)//num_col+1
49
+
50
+ imgs = []
51
+ for i, col in tqdm(enumerate(column_names), total = len(column_names)):
52
+ # plot_type = 'bar' if i in info['cat_col_idx'] else 'distplot'
53
+ plot_type = 'bar' if info['metadata']['columns'][str(i)]['sdtype'] == 'categorical' else 'distplot'
54
+ if plot_type == 'distplot' and (syn_data[col][0] == syn_data[col]).all(): # to tackle a very weird bug
55
+ # If the continuous data all aggregate at a single value, get_column_plot() cannot plot a density curve for it.
56
+ # So, we perturb one entry of the cont data by a small amount
57
+ print(f"\n ALERT: the generated samples column_{i} with name '{col}' all has the same value of {syn_data[col][0]} \n")
58
+ syn_data[col][0] += 1e-5
59
+ fig = get_column_plot(
60
+ real_data=real_data,
61
+ synthetic_data=syn_data,
62
+ column_name=col,
63
+ plot_type=plot_type
64
+ )
65
+
66
+ img_bytes = pio.to_image(fig, format='png')
67
+ img = Image.open(BytesIO(img_bytes))
68
+ imgs.append(img)
69
+
70
+ width, height = imgs[0].size
71
+ big_img = Image.new('RGB', (width * num_col, height * num_row))
72
+ for i, img in enumerate(imgs):
73
+ coordinate = (i%num_col * width, i//num_col * height)
74
+ big_img.paste(img, coordinate)
75
+ return big_img
76
+
77
+ if __name__ == '__main__':
78
+ parser = argparse.ArgumentParser()
79
+
80
+ parser.add_argument('--dataname', type=str, default='adult')
81
+ parser.add_argument('--sample_file_name', type=str, default='tabsyn.csv')
82
+
83
+ args = parser.parse_args()
84
+
85
+ main(args)
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/images/demo.jpg ADDED

Git LFS Details

  • SHA256: 25a091c4ca00d037d51b643785752cad2632b5ad747c2416489f47a25178fd38
  • Pointer size: 130 Bytes
  • Size of remote file: 91.8 kB
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/images/demo.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8b21e1773c51a89e189cbaac0aa1783be8851c6edc466f8706a33a17421e2bee
3
+ size 133585
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/main.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from ef_vfm.main import main as ef_vfm_main
3
+ import argparse
4
+
5
+ if __name__ == '__main__':
6
+ parser = argparse.ArgumentParser(description='Training of EF-VFM (TabbyFlow) for tabular data generation')
7
+
8
+ # General configs
9
+ parser.add_argument('--dataname', type=str, default='adult', help='Name dataset, one of those in data/ dir')
10
+ parser.add_argument('--mode', type=str, default='train', help='train or test')
11
+ parser.add_argument('--method', type=str, default='ef_vfm', help='Currently we only release our model EF-VFM. Baselines will be released soon.')
12
+ parser.add_argument('--gpu', type=int, default=0, help='GPU index')
13
+ parser.add_argument('--debug', action='store_true', help='Enable debug mode')
14
+ parser.add_argument('--no_wandb', action='store_true', help='disable wandb')
15
+ parser.add_argument('--exp_name', type=str, default=None, help='Experiment name, used to name log directories and the wandb run name')
16
+ parser.add_argument('--deterministic', action='store_true', help='Whether to make the entire process deterministic, i.e., fix global random seeds')
17
+
18
+ # Configs for testing ef_vfm
19
+ parser.add_argument('--num_samples_to_generate', type=int, default=None, help='Number of samples to be generated while testing')
20
+ parser.add_argument('--ckpt_path', type=str, default=None, help='Path to the model checkpoint to be tested')
21
+ parser.add_argument('--report', action='store_true', help="Report testing mode: this mode sequentially runs <num_runs> test runs and report the avg and std")
22
+ parser.add_argument('--num_runs', type=int, default=20, help="Number of runs to be averaged in the report testing mode")
23
+
24
+ args = parser.parse_args()
25
+
26
+ # check cuda
27
+ if args.gpu != -1 and torch.cuda.is_available():
28
+ args.device = f'cuda:{args.gpu}'
29
+ else:
30
+ args.device = 'cpu'
31
+
32
+ ef_vfm_main(args)
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/process_dataset.py ADDED
@@ -0,0 +1,492 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ import os
4
+ import sys
5
+ import json
6
+ import argparse
7
+
8
+ from sklearn.preprocessing import OrdinalEncoder
9
+ from sklearn import model_selection
10
+
11
+ TYPE_TRANSFORM ={
12
+ 'float', np.float32,
13
+ 'str', str,
14
+ 'int', int
15
+ }
16
+
17
+ INFO_PATH = 'data/Info'
18
+
19
+ parser = argparse.ArgumentParser(description='process dataset')
20
+
21
+ # General configs
22
+ parser.add_argument('--dataname', type=str, default=None, help='Name of dataset.')
23
+ args = parser.parse_args()
24
+
25
+ def preprocess_beijing():
26
+ with open(f'{INFO_PATH}/beijing.json', 'r') as f:
27
+ info = json.load(f)
28
+
29
+ data_path = info['raw_data_path']
30
+
31
+ data_df = pd.read_csv(data_path)
32
+ columns = data_df.columns
33
+
34
+ data_df = data_df[columns[1:]]
35
+
36
+
37
+ df_cleaned = data_df.dropna()
38
+ df_cleaned.to_csv(info['data_path'], index = False)
39
+
40
+ def preprocess_beijing_dcr():
41
+ with open(f'{INFO_PATH}/beijing_dcr.json', 'r') as f:
42
+ info = json.load(f)
43
+
44
+ data_path = info['raw_data_path']
45
+
46
+ data_df = pd.read_csv(data_path)
47
+ columns = data_df.columns
48
+
49
+ data_df = data_df[columns[1:]]
50
+
51
+ df_cleaned = data_df.dropna()
52
+ df_cleaned.to_csv(info['data_path'], index = False)
53
+
54
+ def preprocess_news(remove_cat=False):
55
+ name = 'news' if not remove_cat else 'news_nocat'
56
+ with open(f'{INFO_PATH}/{name}.json', 'r') as f:
57
+ info = json.load(f)
58
+
59
+ data_path = info['raw_data_path']
60
+ data_df = pd.read_csv(data_path)
61
+ data_df = data_df.drop('url', axis=1)
62
+
63
+ columns = np.array(data_df.columns.tolist())
64
+
65
+ cat_columns1 = columns[list(range(12,18))]
66
+ cat_columns2 = columns[list(range(30,38))]
67
+
68
+ if not remove_cat:
69
+ cat_col1 = data_df[cat_columns1].astype(int).to_numpy().argmax(axis = 1)
70
+ cat_col2 = data_df[cat_columns2].astype(int).to_numpy().argmax(axis = 1)
71
+
72
+ data_df = data_df.drop(cat_columns2, axis=1)
73
+ data_df = data_df.drop(cat_columns1, axis=1)
74
+
75
+ if not remove_cat:
76
+ data_df['data_channel'] = cat_col1
77
+ data_df['weekday'] = cat_col2
78
+
79
+ data_save_path = f'data/{name}/{name}.csv'
80
+ data_df.to_csv(f'{data_save_path}', index = False)
81
+
82
+ columns = np.array(data_df.columns.tolist())
83
+ num_columns = columns[list(range(45))]
84
+ cat_columns = ['data_channel', 'weekday'] if not remove_cat else []
85
+ target_columns = columns[[45]]
86
+
87
+ info['num_col_idx'] = list(range(45))
88
+ info['cat_col_idx'] = [46, 47] if not remove_cat else []
89
+ info['target_col_idx'] = [45]
90
+ info['data_path'] = data_save_path
91
+
92
+ with open(f'{INFO_PATH}/{name}.json', 'w') as file:
93
+ json.dump(info, file, indent=4)
94
+
95
+ def preprocess_news_dcr(remove_cat=False):
96
+ name = 'news_dcr' if not remove_cat else 'news_nocat_dcr'
97
+ with open(f'{INFO_PATH}/{name}.json', 'r') as f:
98
+ info = json.load(f)
99
+
100
+ data_path = info['raw_data_path']
101
+ data_df = pd.read_csv(data_path)
102
+ data_df = data_df.drop('url', axis=1)
103
+
104
+ columns = np.array(data_df.columns.tolist())
105
+
106
+ cat_columns1 = columns[list(range(12,18))]
107
+ cat_columns2 = columns[list(range(30,38))]
108
+
109
+ if not remove_cat:
110
+ cat_col1 = data_df[cat_columns1].astype(int).to_numpy().argmax(axis = 1)
111
+ cat_col2 = data_df[cat_columns2].astype(int).to_numpy().argmax(axis = 1)
112
+
113
+ data_df = data_df.drop(cat_columns2, axis=1)
114
+ data_df = data_df.drop(cat_columns1, axis=1)
115
+
116
+ if not remove_cat:
117
+ data_df['data_channel'] = cat_col1
118
+ data_df['weekday'] = cat_col2
119
+
120
+ data_save_path = f'data/{name}/{name}.csv'
121
+ data_df.to_csv(f'{data_save_path}', index = False)
122
+
123
+ columns = np.array(data_df.columns.tolist())
124
+ num_columns = columns[list(range(45))]
125
+ cat_columns = ['data_channel', 'weekday'] if not remove_cat else []
126
+ target_columns = columns[[45]]
127
+
128
+ info['num_col_idx'] = list(range(45))
129
+ info['cat_col_idx'] = [46, 47] if not remove_cat else []
130
+ info['target_col_idx'] = [45]
131
+ info['data_path'] = data_save_path
132
+
133
+ with open(f'{INFO_PATH}/{name}.json', 'w') as file:
134
+ json.dump(info, file, indent=4)
135
+
136
+
137
+ def get_column_name_mapping(data_df, num_col_idx, cat_col_idx, target_col_idx, column_names = None):
138
+
139
+ if not column_names:
140
+ column_names = np.array(data_df.columns.tolist())
141
+
142
+ idx_mapping = {}
143
+
144
+ curr_num_idx = 0
145
+ curr_cat_idx = len(num_col_idx)
146
+ curr_target_idx = curr_cat_idx + len(cat_col_idx)
147
+
148
+ for idx in range(len(column_names)):
149
+
150
+ if idx in num_col_idx:
151
+ idx_mapping[int(idx)] = curr_num_idx
152
+ curr_num_idx += 1
153
+ elif idx in cat_col_idx:
154
+ idx_mapping[int(idx)] = curr_cat_idx
155
+ curr_cat_idx += 1
156
+ else:
157
+ idx_mapping[int(idx)] = curr_target_idx
158
+ curr_target_idx += 1
159
+
160
+ inverse_idx_mapping = {}
161
+ for k, v in idx_mapping.items():
162
+ inverse_idx_mapping[int(v)] = k
163
+
164
+ idx_name_mapping = {}
165
+
166
+ for i in range(len(column_names)):
167
+ idx_name_mapping[int(i)] = column_names[i]
168
+
169
+ return idx_mapping, inverse_idx_mapping, idx_name_mapping
170
+
171
+
172
+ def train_val_test_split(data_df, cat_columns, num_train = 0, num_test = 0):
173
+ total_num = data_df.shape[0]
174
+ idx = np.arange(total_num)
175
+
176
+ seed = 1234
177
+
178
+ while True:
179
+ np.random.seed(seed)
180
+ np.random.shuffle(idx)
181
+
182
+ train_idx = idx[:num_train]
183
+ test_idx = idx[-num_test:]
184
+
185
+ train_df = data_df.loc[train_idx]
186
+ test_df = data_df.loc[test_idx]
187
+
188
+ flag = 0
189
+ for i in cat_columns:
190
+ if len(set(train_df[i])) != len(set(data_df[i])):
191
+ flag = 1
192
+ break
193
+
194
+ if flag == 0:
195
+ break
196
+ else:
197
+ seed += 1
198
+
199
+ return train_df, test_df, seed
200
+
201
+
202
+ def process_data(name):
203
+
204
+ if name == 'news':
205
+ preprocess_news()
206
+ elif name == 'news_nocat':
207
+ preprocess_news(remove_cat=True)
208
+ elif name == 'news_dcr':
209
+ preprocess_news_dcr()
210
+ elif name == 'beijing':
211
+ preprocess_beijing()
212
+ elif name == 'beijing_dcr':
213
+ preprocess_beijing_dcr()
214
+
215
+ with open(f'{INFO_PATH}/{name}.json', 'r') as f:
216
+ info = json.load(f)
217
+
218
+ data_path = info['data_path']
219
+ if info['file_type'] == 'csv':
220
+ data_df = pd.read_csv(data_path, header = info['header'])
221
+
222
+ elif info['file_type'] == 'xls':
223
+ data_df = pd.read_excel(data_path, sheet_name='Data', header=1)
224
+ data_df = data_df.drop('ID', axis=1)
225
+
226
+ num_data = data_df.shape[0]
227
+
228
+ column_names = info['column_names'] if info['column_names'] else data_df.columns.tolist()
229
+
230
+ num_col_idx = info['num_col_idx']
231
+ cat_col_idx = info['cat_col_idx']
232
+ target_col_idx = info['target_col_idx']
233
+
234
+ num_columns = [column_names[i] for i in num_col_idx]
235
+ cat_columns = [column_names[i] for i in cat_col_idx]
236
+ target_columns = [column_names[i] for i in target_col_idx]
237
+
238
+ idx_mapping, inverse_idx_mapping, idx_name_mapping = get_column_name_mapping(data_df, num_col_idx, cat_col_idx, target_col_idx, column_names)
239
+
240
+ has_val = bool(info['val_path'])
241
+ val_df = pd.DataFrame(columns=data_df.columns).astype(data_df.dtypes) # by default (val_path is not provided), set val_Df to be empty
242
+ if info['test_path']:
243
+
244
+ # if testing data is given
245
+ test_path = info['test_path']
246
+
247
+ if "adult" in name: # BUG: currently data saved at adult's test_path cannot be directly loaded. Consider integrate the following code to a preprocesing function for adult
248
+ with open(test_path, 'r') as f:
249
+ lines = f.readlines()[1:]
250
+ test_save_path = f'data/{name}/test.data'
251
+ if not os.path.exists(test_save_path):
252
+ with open(test_save_path, 'a') as f1:
253
+ for line in lines:
254
+ save_line = line.strip('\n').strip('.')
255
+ f1.write(f'{save_line}\n')
256
+
257
+ test_df = pd.read_csv(test_save_path, header = None)
258
+ else:
259
+ test_df = pd.read_csv(test_path, header = info['header'])
260
+
261
+ if has_val: # currently you cannot have a val path without a test path
262
+ val_path = info['val_path']
263
+ val_df = pd.read_csv(val_path, header = info['header'])
264
+
265
+ train_df = data_df
266
+
267
+ if "dcr" in name and "diabetes" not in name: # create 50/50 splits for dcr datasets; no need for this for diabetes dataset as it's done in preprocessing
268
+ complete_df = pd.concat([train_df, test_df, val_df], axis = 0, ignore_index=True)
269
+ num_data = complete_df.shape[0]
270
+ num_train = int(num_data*0.5)
271
+ num_test = num_data - num_train
272
+ complete_df.rename(columns = idx_name_mapping, inplace=True)
273
+ train_df, test_df, seed = train_val_test_split(complete_df, cat_columns, num_train, num_test)
274
+
275
+ else:
276
+ # Train/ Test Split, 90% Training (50% for dcr eval exclusively), 10% Testing (Validation set will be selected from Training set)
277
+ if "dcr" in name:
278
+ num_train = int(num_data*0.5)
279
+ else:
280
+ num_train = int(num_data*0.9)
281
+ num_test = num_data - num_train
282
+
283
+ train_df, test_df, seed = train_val_test_split(data_df, cat_columns, num_train, num_test)
284
+
285
+ complete_df = pd.concat([train_df, test_df, val_df], axis = 0)
286
+ name_idx_mapping = {val: key for key, val in idx_name_mapping.items()}
287
+ int_columns = []
288
+ int_col_idx = []
289
+ int_col_idx_wrt_num = []
290
+ for i, col_idx in enumerate(num_col_idx):
291
+ col = column_names[col_idx]
292
+ col_data = complete_df.iloc[:,col_idx]
293
+ is_int = (col_data%1 == 0).all()
294
+ if is_int:
295
+ int_columns.append(col)
296
+ int_col_idx.append(name_idx_mapping[col])
297
+ int_col_idx_wrt_num.append(i)
298
+ info['int_col_idx'] = int_col_idx
299
+ info['int_columns'] = int_columns
300
+ info['int_col_idx_wrt_num'] = int_col_idx_wrt_num
301
+
302
+ train_df.columns = range(len(train_df.columns))
303
+ test_df.columns = range(len(test_df.columns))
304
+ val_df.columns = range(len(val_df.columns))
305
+
306
+ print(name, train_df.shape, val_df.shape, test_df.shape, data_df.shape)
307
+
308
+ col_info = {}
309
+
310
+ for col_idx in num_col_idx:
311
+ col_info[col_idx] = {}
312
+ col_info['type'] = 'numerical'
313
+ col_info['max'] = float(train_df[col_idx].max())
314
+ col_info['min'] = float(train_df[col_idx].min())
315
+
316
+ for col_idx in cat_col_idx:
317
+ col_info[col_idx] = {}
318
+ col_info['type'] = 'categorical'
319
+ col_info['categorizes'] = list(set(train_df[col_idx]))
320
+
321
+ for col_idx in target_col_idx:
322
+ if info['task_type'] == 'regression':
323
+ col_info[col_idx] = {}
324
+ col_info['type'] = 'numerical'
325
+ col_info['max'] = float(train_df[col_idx].max())
326
+ col_info['min'] = float(train_df[col_idx].min())
327
+ else:
328
+ col_info[col_idx] = {}
329
+ col_info['type'] = 'categorical'
330
+ col_info['categorizes'] = list(set(train_df[col_idx]))
331
+
332
+ info['column_info'] = col_info
333
+
334
+ train_df.rename(columns = idx_name_mapping, inplace=True)
335
+ test_df.rename(columns = idx_name_mapping, inplace=True)
336
+ val_df.rename(columns = idx_name_mapping, inplace=True)
337
+
338
+ for col in num_columns:
339
+ if (train_df[col] == ' ?').sum() > 0:
340
+ print(col)
341
+ import pdb; pdb.set_trace()
342
+ if (train_df[col] == '?').sum() > 0:
343
+ print(col)
344
+ import pdb; pdb.set_trace()
345
+ train_df.loc[train_df[col] == '?', col] = np.nan
346
+ for col in cat_columns:
347
+ train_df.loc[train_df[col] == '?', col] = 'nan'
348
+ for col in num_columns:
349
+ if (test_df[col] == ' ?').sum() > 0:
350
+ print(col)
351
+ import pdb; pdb.set_trace()
352
+ if (test_df[col] == '?').sum() > 0:
353
+ print(col)
354
+ import pdb; pdb.set_trace()
355
+ test_df.loc[test_df[col] == '?', col] = np.nan
356
+ for col in cat_columns:
357
+ test_df.loc[test_df[col] == '?', col] = 'nan'
358
+ for col in num_columns:
359
+ val_df.loc[val_df[col] == '?', col] = np.nan
360
+ for col in cat_columns:
361
+ val_df.loc[val_df[col] == '?', col] = 'nan'
362
+
363
+ if train_df.isna().any().any():
364
+ print("Training data contains nan in the numerical cols")
365
+ import pdb; pdb.set_trace()
366
+
367
+ X_num_train = train_df[num_columns].to_numpy().astype(np.float32)
368
+ X_cat_train = train_df[cat_columns].to_numpy()
369
+ y_train = train_df[target_columns].to_numpy()
370
+
371
+ X_num_test = test_df[num_columns].to_numpy().astype(np.float32)
372
+ X_cat_test = test_df[cat_columns].to_numpy()
373
+ y_test = test_df[target_columns].to_numpy()
374
+
375
+ X_num_val = val_df[num_columns].to_numpy().astype(np.float32)
376
+ X_cat_val = val_df[cat_columns].to_numpy()
377
+ y_val = val_df[target_columns].to_numpy()
378
+
379
+ save_dir = f'data/{name}'
380
+ np.save(f'{save_dir}/X_num_train.npy', X_num_train)
381
+ np.save(f'{save_dir}/X_cat_train.npy', X_cat_train)
382
+ np.save(f'{save_dir}/y_train.npy', y_train)
383
+
384
+ np.save(f'{save_dir}/X_num_test.npy', X_num_test)
385
+ np.save(f'{save_dir}/X_cat_test.npy', X_cat_test)
386
+ np.save(f'{save_dir}/y_test.npy', y_test)
387
+
388
+ if has_val:
389
+ np.save(f'{save_dir}/X_num_val.npy', X_num_val)
390
+ np.save(f'{save_dir}/X_cat_val.npy', X_cat_val)
391
+ np.save(f'{save_dir}/y_val.npy', y_val)
392
+
393
+ train_df[num_columns] = train_df[num_columns].astype(np.float32)
394
+ test_df[num_columns] = test_df[num_columns].astype(np.float32)
395
+ val_df[num_columns] = val_df[num_columns].astype(np.float32)
396
+
397
+ train_df.to_csv(f'{save_dir}/train.csv', index = False)
398
+ test_df.to_csv(f'{save_dir}/test.csv', index = False)
399
+ if has_val:
400
+ val_df.to_csv(f'{save_dir}/val.csv', index = False)
401
+
402
+ if not os.path.exists(f'synthetic/{name}'):
403
+ os.makedirs(f'synthetic/{name}')
404
+
405
+ train_df.to_csv(f'synthetic/{name}/real.csv', index = False)
406
+ test_df.to_csv(f'synthetic/{name}/test.csv', index = False)
407
+
408
+ if has_val:
409
+ val_df.to_csv(f'synthetic/{name}/val.csv', index = False)
410
+
411
+ print('Numerical', X_num_train.shape)
412
+ print('Categorical', X_cat_train.shape)
413
+
414
+ info['column_names'] = column_names
415
+ info['train_num'] = train_df.shape[0]
416
+ info['test_num'] = test_df.shape[0]
417
+ info['val_num'] = val_df.shape[0]
418
+
419
+ info['idx_mapping'] = idx_mapping
420
+ info['inverse_idx_mapping'] = inverse_idx_mapping
421
+ info['idx_name_mapping'] = idx_name_mapping
422
+
423
+ metadata = {'columns': {}}
424
+ task_type = info['task_type']
425
+ num_col_idx = info['num_col_idx']
426
+ cat_col_idx = info['cat_col_idx']
427
+ target_col_idx = info['target_col_idx']
428
+
429
+ for i in num_col_idx:
430
+ metadata['columns'][i] = {}
431
+ metadata['columns'][i]['sdtype'] = 'numerical'
432
+ metadata['columns'][i]['computer_representation'] = 'Float'
433
+
434
+ for i in cat_col_idx:
435
+ metadata['columns'][i] = {}
436
+ metadata['columns'][i]['sdtype'] = 'categorical'
437
+
438
+ if task_type == 'regression':
439
+
440
+ for i in target_col_idx:
441
+ metadata['columns'][i] = {}
442
+ metadata['columns'][i]['sdtype'] = 'numerical'
443
+ metadata['columns'][i]['computer_representation'] = 'Float'
444
+
445
+ else:
446
+ for i in target_col_idx:
447
+ metadata['columns'][i] = {}
448
+ metadata['columns'][i]['sdtype'] = 'categorical'
449
+
450
+ info['metadata'] = metadata
451
+
452
+ with open(f'{save_dir}/info.json', 'w') as file:
453
+ json.dump(info, file, indent=4)
454
+
455
+ print(f'Processing and Saving {name} Successfully!')
456
+
457
+ print(name)
458
+ print('Total', info['train_num'] + info['test_num'])
459
+ print('Train', info['train_num'])
460
+ print('Val', info['val_num'])
461
+ print('Test', info['test_num'])
462
+ if info['task_type'] == 'regression':
463
+ num = len(info['num_col_idx'] + info['target_col_idx'])
464
+ cat = len(info['cat_col_idx'])
465
+ else:
466
+ cat = len(info['cat_col_idx'] + info['target_col_idx'])
467
+ num = len(info['num_col_idx'])
468
+ print('Num', num)
469
+ print('Int', len(info['int_col_idx']))
470
+ print('Cat', cat)
471
+
472
+ if __name__ == "__main__":
473
+
474
+ if args.dataname:
475
+ process_data(args.dataname)
476
+ else:
477
+ for name in [
478
+ 'adult',
479
+ 'default',
480
+ 'shoppers',
481
+ 'magic',
482
+ 'beijing',
483
+ 'news',
484
+ 'news_nocat',
485
+ 'adult_dcr',
486
+ 'default_dcr',
487
+ 'shoppers_dcr',
488
+ 'beijing_dcr',
489
+ 'news_dcr',
490
+ ]:
491
+ process_data(name)
492
+
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_runtime/pyproject.toml ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bc2d5c09fdbd3457c0f7cdd1a92c8e44ea3b2ff1316a2b718865fb7e8059da36
3
+ size 1029
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/_efvfm_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