jialinzhang commited on
Commit
e2bf942
·
1 Parent(s): f1d7e19

Add syntheticFail n12

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/_tabbyflow_train.py +24 -0
  2. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/input_snapshot.json +3 -0
  3. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/public_gate/normalized_schema_snapshot.json +3 -0
  4. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/public_gate/public_gate_report.json +3 -0
  5. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/public_gate/staged_input_manifest.json +3 -0
  6. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/run_config.json +3 -0
  7. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/runtime_result.json +3 -0
  8. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/staged/public/staged_features.json +3 -0
  9. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/staged/public/test.csv +3 -0
  10. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/staged/public/train.csv +3 -0
  11. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/staged/public/val.csv +3 -0
  12. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/staged/tabbyflow/adapter_report.json +3 -0
  13. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/staged/tabbyflow/adapter_transforms_applied.json +3 -0
  14. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/staged/tabbyflow/model_input_manifest.json +3 -0
  15. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/X_num_test.npy +3 -0
  16. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/X_num_train.npy +3 -0
  17. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/X_num_val.npy +3 -0
  18. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/info.json +3 -0
  19. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/real.csv +3 -0
  20. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/staged_features.json +3 -0
  21. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/test.csv +3 -0
  22. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/train.csv +3 -0
  23. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/val.csv +3 -0
  24. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/y_test.npy +3 -0
  25. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/y_train.npy +3 -0
  26. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/y_val.npy +3 -0
  27. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/train_20260510_202730.log +3 -0
  28. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/.gitignore +174 -0
  29. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/LICENCE +7 -0
  30. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/README.md +128 -0
  31. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/X_num_test.npy +3 -0
  32. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/X_num_train.npy +3 -0
  33. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/X_num_val.npy +3 -0
  34. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/info.json +3 -0
  35. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/real.csv +3 -0
  36. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/staged_features.json +3 -0
  37. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/test.csv +3 -0
  38. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/train.csv +3 -0
  39. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/val.csv +3 -0
  40. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/y_test.npy +3 -0
  41. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/y_train.npy +3 -0
  42. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/y_val.npy +3 -0
  43. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/download_dataset.py +49 -0
  44. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/ef_vfm/configs/ef_vfm_configs.toml +3 -0
  45. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/ef_vfm/main.py +246 -0
  46. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/ef_vfm/metrics.py +306 -0
  47. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/ef_vfm/models/flow_model.py +195 -0
  48. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/ef_vfm/modules/main_modules.py +102 -0
  49. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/ef_vfm/modules/transformer.py +269 -0
  50. syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/ef_vfm/trainer.py +557 -0
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/_tabbyflow_train.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os, shutil, subprocess, sys
3
+ root = r"/workspace/ef-vfm"
4
+ name = r"pipeline_n12"
5
+ src = r"/work/output-Benchmark-trainonly-v1/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12"
6
+ os.makedirs(os.path.join(root, "data", name), exist_ok=True)
7
+ dst_data = os.path.join(root, "data", name)
8
+ dst_syn = os.path.join(root, "synthetic", name)
9
+ shutil.rmtree(dst_data, ignore_errors=True)
10
+ shutil.copytree(src, dst_data)
11
+ os.makedirs(dst_syn, exist_ok=True)
12
+ for fn in ("real.csv", "test.csv", "val.csv"):
13
+ shutil.copy(os.path.join(src, fn), os.path.join(dst_syn, fn))
14
+ os.chdir(root)
15
+ os.environ["PYTHONPATH"] = root + os.pathsep + os.environ.get("PYTHONPATH", "")
16
+ os.environ["EFVFM_SMOKE_STEPS"] = "100"
17
+ os.environ["EFVFM_ADAPTER_TRAIN"] = "1"
18
+ os.environ.setdefault("EFVFM_SAMPLE_BATCH_SIZE", "128")
19
+ os.environ.setdefault("EFVFM_EVAL_NUM_SAMPLES", "512")
20
+ subprocess.check_call([
21
+ sys.executable, "main.py",
22
+ "--dataname", name, "--mode", "train", "--gpu", "0",
23
+ "--no_wandb", "--exp_name", r"adapter_efvfm",
24
+ ])
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/input_snapshot.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a8d27ecb4984ffedf45030368b1733997f42cc4ed7064c057d4dc9c0058ac1bc
3
+ size 1362
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/public_gate/normalized_schema_snapshot.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f557e091384db0c72c9acb9ef1549554fc2a2d69f9990d9697104a90556b8a68
3
+ size 1878
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/public_gate/public_gate_report.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2669f797a1e70611d433ac20e4b082cf45938adaeb6f5fdc85dda5e18bcfaf48
3
+ size 920
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/public_gate/staged_input_manifest.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:56d12b969fce443335acf214998f68507c8b6b57541505ff101cce5a924b00a5
3
+ size 2714
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/run_config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8190b035cfbd91cd81fa24bff02704dd07deb16f8989992aa3664d024be9db92
3
+ size 1828
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/runtime_result.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5ea6e9d4204b05490b5d889c2429053bb0d99829dc9e13824673a19b0fbc59da
3
+ size 1108
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/staged/public/staged_features.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:148b95cbf4c3da3ebc38686f20ef1e724b56b701abfa24065d77f9b417e8671e
3
+ size 382
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/staged/public/test.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4972eb2812d325c143ec99492afa470fe047141a9bdf34893ec0133a12b8dc26
3
+ size 315789
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/staged/public/train.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:728fec9c0ec06ca4b292989614be4374c308d9a15b1e0002c3daeb3a68d5d350
3
+ size 2524420
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/staged/public/val.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8931c0b2402466ccca41868fc484ab4bc6f627d68422570b20d47d1104922959
3
+ size 315663
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/staged/tabbyflow/adapter_report.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6e069bbc16920549cfabcca64aed58d99bda2e2b66e754a3ca8df6f86192188d
3
+ size 329
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/staged/tabbyflow/adapter_transforms_applied.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945
3
+ size 2
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/staged/tabbyflow/model_input_manifest.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f7db846e94452ae99b58db74ee416e8c6de8fe7ae2d7e722ffbb96f651c322d1
3
+ size 2919
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/X_num_test.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c61438cf93c656fb5cb15eaf2307b9a6762caaac9767fc58fe2952aac45fc3f5
3
+ size 294200
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/X_num_train.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:81c9f92b945e7c858dd597c0ca1c4214488b28e0235e7540729aaa6ac355e3d9
3
+ size 2352668
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/X_num_val.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:54b84a34c98bec5e63d00e8383bffc55618cc35ca19227edb8002567851a456e
3
+ size 294200
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/info.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:02559b8584b55130a4e5ba46c593a0ed67e2f2dc812b3591721763c9b1ad4d19
3
+ size 1118
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/real.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:728fec9c0ec06ca4b292989614be4374c308d9a15b1e0002c3daeb3a68d5d350
3
+ size 2524420
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/staged_features.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:148b95cbf4c3da3ebc38686f20ef1e724b56b701abfa24065d77f9b417e8671e
3
+ size 382
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/test.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4972eb2812d325c143ec99492afa470fe047141a9bdf34893ec0133a12b8dc26
3
+ size 315789
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/train.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:728fec9c0ec06ca4b292989614be4374c308d9a15b1e0002c3daeb3a68d5d350
3
+ size 2524420
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/val.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8931c0b2402466ccca41868fc484ab4bc6f627d68422570b20d47d1104922959
3
+ size 315663
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/y_test.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bf9f1e26e93a4ce529e1b2b19584b310c3dbfeb4710430cddd3ba8801a505a56
3
+ size 98152
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/y_train.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b3364a73bf996bb34a52618df06197d3b8d019bfa3f75ab7e43ed9e93ffb56ef
3
+ size 784308
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/y_val.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7871f5214b6bae4b8a0bfaf8c930995b30f34bca844dfd13c079556269d6f22d
3
+ size 98152
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/train_20260510_202730.log ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b420e7a0cff64b0aff02d3e4cb15755e3693c5ba390afb24bf2a680c104ca234
3
+ size 1176
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_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
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_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.
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_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).
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/X_num_test.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c61438cf93c656fb5cb15eaf2307b9a6762caaac9767fc58fe2952aac45fc3f5
3
+ size 294200
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/X_num_train.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:81c9f92b945e7c858dd597c0ca1c4214488b28e0235e7540729aaa6ac355e3d9
3
+ size 2352668
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/X_num_val.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:54b84a34c98bec5e63d00e8383bffc55618cc35ca19227edb8002567851a456e
3
+ size 294200
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/info.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5b8d53efcd8f5ad02da9415b33fbe1ab53bfed7a191ed60ddec769dbedd1b12d
3
+ size 1092
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/real.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:728fec9c0ec06ca4b292989614be4374c308d9a15b1e0002c3daeb3a68d5d350
3
+ size 2524420
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/staged_features.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:148b95cbf4c3da3ebc38686f20ef1e724b56b701abfa24065d77f9b417e8671e
3
+ size 382
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/test.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4972eb2812d325c143ec99492afa470fe047141a9bdf34893ec0133a12b8dc26
3
+ size 315789
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/train.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:728fec9c0ec06ca4b292989614be4374c308d9a15b1e0002c3daeb3a68d5d350
3
+ size 2524420
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/val.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8931c0b2402466ccca41868fc484ab4bc6f627d68422570b20d47d1104922959
3
+ size 315663
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/y_test.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:587fd6fe2d75caab988288d939395769ac7ea8c41a0938041ae5250bcf5e7351
3
+ size 196176
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/y_train.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:287f6835c6d89c1245143b25166673da2a55377c2ca2ead7f5bbc0e34cc03c1b
3
+ size 1568488
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/y_val.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:693dcf53a187d58d619d0193dd178f117a2f1e98296ea30d8cb5bc8dd9d48647
3
+ size 196176
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_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
+
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_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
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_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'
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_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
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_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
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_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
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_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
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_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