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

Add syntheticFail n14

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/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/.gitignore +174 -0
  2. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/LICENCE +7 -0
  3. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/README.md +128 -0
  4. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/X_num_test.npy +3 -0
  5. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/X_num_train.npy +3 -0
  6. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/X_num_val.npy +3 -0
  7. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/info.json +3 -0
  8. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/real.csv +3 -0
  9. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/staged_features.json +3 -0
  10. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/test.csv +3 -0
  11. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/train.csv +3 -0
  12. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/val.csv +3 -0
  13. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/y_test.npy +3 -0
  14. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/y_train.npy +3 -0
  15. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/y_val.npy +3 -0
  16. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/download_dataset.py +49 -0
  17. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/ef_vfm/configs/ef_vfm_configs.toml +3 -0
  18. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/ef_vfm/main.py +246 -0
  19. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/ef_vfm/metrics.py +306 -0
  20. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/ef_vfm/models/flow_model.py +195 -0
  21. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/ef_vfm/modules/main_modules.py +102 -0
  22. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/ef_vfm/modules/transformer.py +269 -0
  23. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/ef_vfm/trainer.py +557 -0
  24. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/eval/eval_quality.py +149 -0
  25. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/eval/mle/mle.py +781 -0
  26. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/eval/mle/tabular_dataload.py +111 -0
  27. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/eval/mle/tabular_transformer.py +110 -0
  28. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/eval/visualize_density.py +85 -0
  29. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/main.py +32 -0
  30. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/process_dataset.py +492 -0
  31. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/pyproject.toml +3 -0
  32. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/src/__init__.py +11 -0
  33. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/src/data.py +780 -0
  34. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/src/env.py +39 -0
  35. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/src/metrics.py +157 -0
  36. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/src/util.py +347 -0
  37. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/synthetic/pipeline_n14/real.csv +3 -0
  38. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/synthetic/pipeline_n14/test.csv +3 -0
  39. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/synthetic/pipeline_n14/val.csv +3 -0
  40. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/conftest.py +193 -0
  41. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_attention.py +51 -0
  42. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_config.py +62 -0
  43. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_flow_model.py +219 -0
  44. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_mlp.py +85 -0
  45. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_reconstructor.py +51 -0
  46. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_tokenizer.py +85 -0
  47. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_trainer.py +98 -0
  48. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_transformer.py +73 -0
  49. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_unimodmlp.py +72 -0
  50. syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_utils.py +49 -0
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_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/n14/tabbyflow/tabbyflow-n14-20260510_205357/_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/n14/tabbyflow/tabbyflow-n14-20260510_205357/_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/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/X_num_test.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e252b63332f6d0348986fa99b50bd0f50a4842a6535d987c77e35ec94dca2304
3
+ size 41132
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/X_num_train.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b976aada0f39493df222408da25c8093fae5ed29c88a963352f6c5924720bfcb
3
+ size 326528
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/X_num_val.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:43682ea64d3dccdcaf67f0c922556fe78e3cd216b7456a914a5e169e2b52f5a8
3
+ size 40724
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/info.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:575631118d21657a7a362ba5a330d6fff150a3d78c4ba038ffb878dd37c75cd5
3
+ size 9435
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/real.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c185607e5260848288c1fe3ee266131707a54e9f5e053f1234c019f315783fac
3
+ size 700663
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/staged_features.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2ceb242f15c8115703b617ca54db02ff27dff41d99dd4f9af89bb5fcb513e5bb
3
+ size 5032
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/test.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6c58f97d23ce9ec15dde2caf4ba02105c2839eb4b1e1bb7f5183e0661fec4ecd
3
+ size 88640
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/train.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c185607e5260848288c1fe3ee266131707a54e9f5e053f1234c019f315783fac
3
+ size 700663
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/val.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:efcb8ee58a24ce4397213b3c4df4826fbcc6662da77b0919ff4e1935d12e2e89
3
+ size 87578
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/y_test.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2e6b805a842cf97508b8a3789499fc698c44e659e45b100fb80d666ad2f96a74
3
+ size 1736
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/y_train.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ee738812eaaf4a819a6c9f861ee2e99873bd2842f80c68eb380cc38033938b74
3
+ size 12928
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/y_val.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0df86b75b6fc8fea3f161682beaa867a5bb7dbe36f9331e7d36176459da70720
3
+ size 1720
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_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/n14/tabbyflow/tabbyflow-n14-20260510_205357/_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/n14/tabbyflow/tabbyflow-n14-20260510_205357/_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/n14/tabbyflow/tabbyflow-n14-20260510_205357/_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/n14/tabbyflow/tabbyflow-n14-20260510_205357/_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/n14/tabbyflow/tabbyflow-n14-20260510_205357/_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/n14/tabbyflow/tabbyflow-n14-20260510_205357/_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/n14/tabbyflow/tabbyflow-n14-20260510_205357/_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
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/eval/eval_quality.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import numpy as np
3
+ import pandas as pd
4
+ import os
5
+ import sys
6
+ import json
7
+
8
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
9
+ from sklearn.preprocessing import OneHotEncoder
10
+ from synthcity.metrics import eval_statistical
11
+ from synthcity.plugins.core.dataloader import GenericDataLoader
12
+
13
+ pd.options.mode.chained_assignment = None
14
+
15
+ import argparse
16
+
17
+ parser = argparse.ArgumentParser()
18
+ parser.add_argument('--dataname', type=str)
19
+ parser.add_argument('--exp_name', type=str, default=None)
20
+
21
+
22
+ args = parser.parse_args()
23
+
24
+ def evaluate_quality(real_path, syn_path, info_path):
25
+ with open(info_path, 'r') as f:
26
+ info = json.load(f)
27
+
28
+ syn_data = pd.read_csv(syn_path)
29
+ real_data = pd.read_csv(real_path)
30
+
31
+
32
+ ''' Special treatment for default dataset and CoDi model '''
33
+
34
+ real_data.columns = range(len(real_data.columns))
35
+ syn_data.columns = range(len(syn_data.columns))
36
+
37
+ num_col_idx = info['num_col_idx']
38
+ cat_col_idx = info['cat_col_idx']
39
+ target_col_idx = info['target_col_idx']
40
+ if info['task_type'] == 'regression':
41
+ num_col_idx += target_col_idx
42
+ else:
43
+ cat_col_idx += target_col_idx
44
+
45
+ num_real_data = real_data[num_col_idx]
46
+ cat_real_data = real_data[cat_col_idx]
47
+
48
+ num_real_data_np = num_real_data.to_numpy()
49
+ cat_real_data_np = cat_real_data.to_numpy().astype('str')
50
+
51
+
52
+ num_syn_data = syn_data[num_col_idx]
53
+ cat_syn_data = syn_data[cat_col_idx]
54
+
55
+ num_syn_data_np = num_syn_data.to_numpy()
56
+
57
+ # cat_syn_data_np = np.array
58
+ cat_syn_data_np = cat_syn_data.to_numpy().astype('str')
59
+
60
+ encoder = OneHotEncoder()
61
+ encoder.fit(cat_real_data_np)
62
+
63
+
64
+ cat_real_data_oh = encoder.transform(cat_real_data_np).toarray()
65
+ cat_syn_data_oh = encoder.transform(cat_syn_data_np).toarray()
66
+
67
+ le_real_data = pd.DataFrame(np.concatenate((num_real_data_np, cat_real_data_oh), axis = 1)).astype(float)
68
+ le_real_num = pd.DataFrame(num_real_data_np).astype(float)
69
+ le_real_cat = pd.DataFrame(cat_real_data_oh).astype(float)
70
+
71
+
72
+ le_syn_data = pd.DataFrame(np.concatenate((num_syn_data_np, cat_syn_data_oh), axis = 1)).astype(float)
73
+ le_syn_num = pd.DataFrame(num_syn_data_np).astype(float)
74
+ le_syn_cat = pd.DataFrame(cat_syn_data_oh).astype(float)
75
+
76
+ # Check for nan
77
+ if le_syn_data.isnull().values.any():
78
+ nan_coordinate = np.isnan(le_syn_data.to_numpy()).nonzero()
79
+ nan_row = np.unique(nan_coordinate[0])
80
+ print(f"Synthetic data contains NaN at row {nan_row}: ")
81
+ print(le_syn_data.iloc[nan_row])
82
+ return None, None
83
+
84
+
85
+ np.set_printoptions(precision=4)
86
+
87
+ result = []
88
+
89
+ print('=========== All Features ===========')
90
+ print('Data shape: ', le_syn_data.shape)
91
+
92
+ X_syn_loader = GenericDataLoader(le_syn_data)
93
+ X_real_loader = GenericDataLoader(le_real_data)
94
+
95
+ quality_evaluator = eval_statistical.AlphaPrecision()
96
+ qual_res = quality_evaluator.evaluate(X_real_loader, X_syn_loader)
97
+ qual_res = {
98
+ k: v for (k, v) in qual_res.items() if "naive" in k
99
+ } # use the naive implementation of AlphaPrecision
100
+ qual_score = np.mean(list(qual_res.values()))
101
+
102
+ print('alpha precision: {:.6f}, beta recall: {:.6f}'.format(qual_res['delta_precision_alpha_naive'], qual_res['delta_coverage_beta_naive'] ))
103
+
104
+ Alpha_Precision_all = qual_res['delta_precision_alpha_naive']
105
+ Beta_Recall_all = qual_res['delta_coverage_beta_naive']
106
+
107
+ return Alpha_Precision_all, Beta_Recall_all
108
+
109
+ if __name__ == '__main__':
110
+ exp_name = args.exp_name
111
+ assert exp_name is not None, "Experiment name must be provided"
112
+ dataname = args.dataname
113
+ data_dir = f'data/{dataname}'
114
+ info_path = f'{data_dir}/info.json'
115
+ real_path = f'synthetic/{dataname}/real.csv'
116
+
117
+ sample_dir = f"eval/report_runs/{exp_name}/{dataname}/all_samples"
118
+ sample_paths = glob.glob(os.path.join(sample_dir, "*.csv"))
119
+ print(f"{len(sample_paths )} samples loaded from {sample_dir}")
120
+
121
+ alphas, betas = [], []
122
+ for syn_path in sample_paths:
123
+ alpha_precision, beta_recall = evaluate_quality(real_path, syn_path, info_path)
124
+ if (alpha_precision is None) or (beta_recall is None):
125
+ continue
126
+ alphas.append(alpha_precision)
127
+ betas.append(beta_recall)
128
+
129
+ alphas = np.array(alphas)
130
+ betas = np.array(betas)
131
+ alpha_percent = alphas * 100
132
+ beta_percent = betas * 100
133
+
134
+ quality = pd.DataFrame({
135
+ 'alpha': alpha_percent,
136
+ 'beta': beta_percent
137
+ })
138
+ avg = quality.mean(axis=0).round(2)
139
+ std = quality.std(axis=0).round(2)
140
+ quality_avg_std = pd.concat([avg, std], axis=1, ignore_index=True)
141
+ quality_avg_std.columns = ["avg", "std"]
142
+ quality_avg_std.index = ["alpha", "beta"]
143
+
144
+ save_dir = os.path.dirname(sample_dir)
145
+ quality.to_csv(os.path.join(save_dir, "quality.csv"), index=True)
146
+ avg_std = pd.read_csv(os.path.join(save_dir, "avg_std.csv"), index_col=0)
147
+ avg_std = pd.concat([avg_std, quality_avg_std])
148
+ print(avg_std)
149
+ avg_std.to_csv(os.path.join(save_dir, "avg_std.csv"), index=True)
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/eval/mle/mle.py ADDED
@@ -0,0 +1,781 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ from xgboost import XGBClassifier, XGBRegressor
4
+ from sklearn.ensemble import AdaBoostClassifier, RandomForestClassifier, RandomForestRegressor
5
+ from sklearn.linear_model import LogisticRegression, LinearRegression
6
+ from sklearn.neural_network import MLPClassifier, MLPRegressor
7
+ from sklearn.preprocessing import OneHotEncoder, LabelEncoder
8
+ from sklearn.tree import DecisionTreeClassifier
9
+ from sklearn.metrics import classification_report, accuracy_score, f1_score, precision_score, recall_score, roc_auc_score
10
+ from sklearn.metrics import explained_variance_score, mean_squared_error, mean_absolute_error, r2_score
11
+ from sklearn.model_selection import ParameterGrid
12
+ from sklearn.utils._testing import ignore_warnings
13
+ from sklearn.exceptions import ConvergenceWarning
14
+ import logging
15
+ from prdc import compute_prdc
16
+ from tqdm import tqdm
17
+
18
+ CATEGORICAL = "categorical"
19
+ CONTINUOUS = "continuous"
20
+
21
+ _MODELS = {
22
+ 'binclass': [ # 184
23
+ # {
24
+ # 'class': DecisionTreeClassifier, # 48
25
+ # 'kwargs': {
26
+ # 'max_depth': [4, 8, 16, 32],
27
+ # 'min_samples_split': [2, 4, 8],
28
+ # 'min_samples_leaf': [1, 2, 4, 8]
29
+ # }
30
+ # },
31
+ # {
32
+ # 'class': AdaBoostClassifier, # 4
33
+ # 'kwargs': {
34
+ # 'n_estimators': [10, 50, 100, 200]
35
+ # }
36
+ # },
37
+ # {
38
+ # 'class': LogisticRegression, # 36
39
+ # 'kwargs': {
40
+ # 'solver': ['lbfgs'],
41
+ # 'n_jobs': [-1],
42
+ # 'max_iter': [10, 50, 100, 200],
43
+ # 'C': [0.01, 0.1, 1.0],
44
+ # 'tol': [1e-01, 1e-02, 1e-04]
45
+ # }
46
+ # },
47
+ # {
48
+ # 'class': MLPClassifier, # 12
49
+ # 'kwargs': {
50
+ # 'hidden_layer_sizes': [(100, ), (200, ), (100, 100)],
51
+ # 'max_iter': [50, 100],
52
+ # 'alpha': [0.0001, 0.001]
53
+ # }
54
+ # },
55
+ # {
56
+ # 'class': RandomForestClassifier, # 48
57
+ # 'kwargs': {
58
+ # 'max_depth': [8, 16, None],
59
+ # 'min_samples_split': [2, 4, 8],
60
+ # 'min_samples_leaf': [1, 2, 4, 8],
61
+ # 'n_jobs': [-1]
62
+
63
+ # }
64
+ # },
65
+ {
66
+ 'class': XGBClassifier, # 36
67
+ 'kwargs': {
68
+ 'n_estimators': [10, 50, 100],
69
+ 'min_child_weight': [1, 10],
70
+ 'max_depth': [5, 10, 20],
71
+ 'gamma': [0.0, 1.0],
72
+ 'objective': ['binary:logistic'],
73
+ 'nthread': [-1],
74
+ 'tree_method': ['gpu_hist']
75
+ },
76
+ }
77
+
78
+ ],
79
+ 'multiclass': [ # 132
80
+
81
+ # {
82
+ # 'class': MLPClassifier, # 12
83
+ # 'kwargs': {
84
+ # 'hidden_layer_sizes': [(100, ), (200, ), (100, 100)],
85
+ # 'max_iter': [50, 100],
86
+ # 'alpha': [0.0001, 0.001]
87
+ # }
88
+ # },
89
+ # {
90
+ # 'class': DecisionTreeClassifier, # 48
91
+ # 'kwargs': {
92
+ # 'max_depth': [4, 8, 16, 32],
93
+ # 'min_samples_split': [2, 4, 8],
94
+ # 'min_samples_leaf': [1, 2, 4, 8]
95
+ # }
96
+ # },
97
+ # {
98
+ # 'class': RandomForestClassifier, # 36
99
+ # 'kwargs': {
100
+ # 'max_depth': [8, 16, None],
101
+ # 'min_samples_split': [2, 4, 8],
102
+ # 'min_samples_leaf': [1, 2, 4, 8],
103
+ # 'n_jobs': [-1]
104
+
105
+ # }
106
+ # },
107
+ {
108
+ 'class': XGBClassifier, # 36
109
+ 'kwargs': {
110
+ 'n_estimators': [10, 50, 100],
111
+ 'min_child_weight': [1, 10],
112
+ 'max_depth': [5, 10, 20],
113
+ 'gamma': [0.0, 1.0],
114
+ 'objective': ['binary:logistic'],
115
+ 'nthread': [-1],
116
+ 'tree_method': ['gpu_hist']
117
+ }
118
+ }
119
+
120
+ ],
121
+ 'regression': [ # 84
122
+ # {
123
+ # 'class': LinearRegression,
124
+ # },
125
+ # {
126
+ # 'class': MLPRegressor, # 12
127
+ # 'kwargs': {
128
+ # 'hidden_layer_sizes': [(100, ), (200, ), (100, 100)],
129
+ # 'max_iter': [50, 100],
130
+ # 'alpha': [0.0001, 0.001]
131
+ # }
132
+ #},
133
+ {
134
+ 'class': XGBRegressor, # 36
135
+ 'kwargs': {
136
+ 'n_estimators': [10, 50, 100],
137
+ 'min_child_weight': [1, 10],
138
+ 'max_depth': [5, 10, 20],
139
+ 'gamma': [0.0, 1.0],
140
+ 'objective': ['reg:linear'],
141
+ 'nthread': [-1],
142
+ 'tree_method': ['gpu_hist']
143
+ }
144
+ },
145
+ # {
146
+ # 'class': RandomForestRegressor, # 36
147
+ # 'kwargs': {
148
+ # 'max_depth': [8, 16, None],
149
+ # 'min_samples_split': [2, 4, 8],
150
+ # 'min_samples_leaf': [1, 2, 4, 8],
151
+ # 'n_jobs': [-1]
152
+ # }
153
+ # }
154
+ ]
155
+ }
156
+
157
+ def feat_transform(data, info, label_encoder = None, encoders = None, cmax = None, cmin = None):
158
+ num_col_idx = info['num_col_idx']
159
+ cat_col_idx = info['cat_col_idx']
160
+ target_col_idx = info['target_col_idx']
161
+
162
+ num_cols = len(num_col_idx + cat_col_idx + target_col_idx)
163
+ features = []
164
+
165
+ if not encoders:
166
+ encoders = dict()
167
+ for idx in range(num_cols):
168
+ col = data[:, idx]
169
+
170
+ if idx in target_col_idx:
171
+
172
+ if info['task_type'] != 'regression':
173
+
174
+ if not label_encoder:
175
+ label_encoder = LabelEncoder()
176
+ label_encoder.fit(col)
177
+
178
+ encoded_labels = label_encoder.transform(col)
179
+ labels = encoded_labels
180
+ else:
181
+ col = col.astype(np.float32)
182
+ labels = col.astype(np.float32)
183
+
184
+ continue
185
+
186
+ if idx in num_col_idx:
187
+ col = col.astype(np.float32)
188
+
189
+ if not cmin:
190
+ cmin = col.min()
191
+
192
+ if not cmax:
193
+ cmax = col.max()
194
+
195
+ if cmin >= 0 and cmax >= 1e3:
196
+ feature = np.log(np.maximum(col, 1e-2))
197
+
198
+ else:
199
+ feature = (col - cmin) / (cmax - cmin) * 5
200
+
201
+ elif idx in cat_col_idx:
202
+ encoder = encoders.get(idx)
203
+ col = col.reshape(-1, 1)
204
+ if encoder:
205
+ feature = encoder.transform(col)
206
+ else:
207
+ # encoder = OneHotEncoder(sparse=False, handle_unknown='ignore')
208
+ encoder = OneHotEncoder(sparse_output=False, handle_unknown='ignore') # New in version 1.2: sparse was renamed to sparse_output
209
+ encoders[idx] = encoder
210
+ feature = encoder.fit_transform(col)
211
+
212
+
213
+ features.append(feature)
214
+ features = np.column_stack(features)
215
+ return features, labels, label_encoder, encoders, cmax, cmin
216
+
217
+
218
+ def prepare_ml_problem(train, test, info, val=None):
219
+ # test_X, test_y, label_encoder, encoders = feat_transform(test, info)
220
+ # train_X, train_y, _, _ = feat_transform(train, info, label_encoder, encoders)
221
+
222
+ train_X, train_y, label_encoder, encoders, cmax, cmin = feat_transform(train, info)
223
+ test_X, test_y, _, _ , _, _ = feat_transform(test, info, label_encoder, encoders, cmax, cmin)
224
+
225
+ if val is not None:
226
+ val_X, val_y, _, _, _, _ = feat_transform(val, info, label_encoder, encoders, cmax, cmin)
227
+ else:
228
+ total_train_num = train_X.shape[0]
229
+ val_num = int(total_train_num / 9)
230
+
231
+ total_train_idx = np.arange(total_train_num)
232
+ np.random.shuffle(total_train_idx)
233
+ train_idx = total_train_idx[val_num:]
234
+ val_idx = total_train_idx[:val_num]
235
+
236
+
237
+
238
+ # val_X, val_y = train_X[val_idx], train_y[val_idx]
239
+ # train_X, train_y = train_X[train_idx], train_y[train_idx]
240
+
241
+ # model = _MODELS[info['task_type']]
242
+
243
+ # return train_X, train_y, train_X, train_y, test_X, test_y, model
244
+
245
+
246
+
247
+ val_X, val_y = train_X[val_idx], train_y[val_idx]
248
+ train_X, train_y = train_X[train_idx], train_y[train_idx]
249
+
250
+ model = _MODELS[info['task_type']]
251
+
252
+ return train_X, train_y, val_X, val_y, test_X, test_y, model
253
+
254
+ class FeatureMaker:
255
+
256
+ def __init__(self, metadata, label_column='label', label_type='int', sample=50000):
257
+ self.columns = metadata['columns']
258
+ self.label_column = label_column
259
+ self.label_type = label_type
260
+ self.sample = sample
261
+ self.encoders = dict()
262
+
263
+ def make_features(self, data):
264
+ data = data.copy()
265
+ np.random.shuffle(data)
266
+ data = data[:self.sample]
267
+
268
+ features = []
269
+ labels = []
270
+
271
+ for index, cinfo in enumerate(self.columns):
272
+ col = data[:, index]
273
+ if cinfo['name'] == self.label_column:
274
+ if self.label_type == 'int':
275
+ labels = col.astype(int)
276
+ elif self.label_type == 'float':
277
+ labels = col.astype(float)
278
+ else:
279
+ assert 0, 'unkown label type'
280
+ continue
281
+
282
+ if cinfo['type'] == CONTINUOUS:
283
+ cmin = cinfo['min']
284
+ cmax = cinfo['max']
285
+ if cmin >= 0 and cmax >= 1e3:
286
+ feature = np.log(np.maximum(col, 1e-2))
287
+
288
+ else:
289
+ feature = (col - cmin) / (cmax - cmin) * 5
290
+
291
+ else:
292
+ if cinfo['size'] <= 2:
293
+ feature = col
294
+
295
+ else:
296
+ encoder = self.encoders.get(index)
297
+ col = col.reshape(-1, 1)
298
+ if encoder:
299
+ feature = encoder.transform(col)
300
+ else:
301
+ encoder = OneHotEncoder(sparse=False, handle_unknown='ignore')
302
+ self.encoders[index] = encoder
303
+ feature = encoder.fit_transform(col)
304
+
305
+ features.append(feature)
306
+
307
+ features = np.column_stack(features)
308
+
309
+ return features, labels
310
+
311
+
312
+ def _prepare_ml_problem(train, val, test, metadata, eval):
313
+ fm = FeatureMaker(metadata)
314
+ x_trains, y_trains = [], []
315
+
316
+ for i in train:
317
+ x_train, y_train = fm.make_features(i)
318
+ x_trains.append(x_train)
319
+ y_trains.append(y_train)
320
+
321
+ x_val, y_val = fm.make_features(val)
322
+ if eval is None:
323
+ x_test = None
324
+ y_test = None
325
+ else:
326
+ x_test, y_test = fm.make_features(test)
327
+ model = _MODELS[metadata['problem_type']]
328
+
329
+ return x_trains, y_trains, x_val, y_val, x_test, y_test, model
330
+
331
+
332
+ def _weighted_f1(y_test, pred):
333
+ report = classification_report(y_test, pred, output_dict=True)
334
+ classes = list(report.keys())[:-3]
335
+ proportion = [ report[i]['support'] / len(y_test) for i in classes]
336
+ weighted_f1 = np.sum(list(map(lambda i, prop: report[i]['f1-score']* (1-prop)/(len(classes)-1), classes, proportion)))
337
+ return weighted_f1
338
+
339
+
340
+ @ignore_warnings(category=ConvergenceWarning)
341
+ def _evaluate_multi_classification(train, test, info, val=None):
342
+ x_trains, y_trains, x_valid, y_valid, x_test, y_test, classifiers = prepare_ml_problem(train, test, info, val=val)
343
+ best_f1_scores = []
344
+ unique_labels = np.unique(y_trains)
345
+
346
+
347
+ best_f1_scores = []
348
+ best_weighted_scores = []
349
+ best_auroc_scores = []
350
+ best_acc_scores = []
351
+ best_avg_scores = []
352
+
353
+ for model_spec in classifiers:
354
+ model_class = model_spec['class']
355
+ model_kwargs = model_spec.get('kwargs', dict())
356
+ model_repr = model_class.__name__
357
+
358
+ unique_labels = np.unique(y_trains)
359
+
360
+ param_set = list(ParameterGrid(model_kwargs))
361
+
362
+ results = []
363
+ for param in tqdm(param_set):
364
+ model = model_class(**param)
365
+
366
+ try:
367
+ model.fit(x_trains, y_trains)
368
+ except:
369
+ pass
370
+
371
+ if len(unique_labels) != len(np.unique(y_valid)):
372
+ pred = [unique_labels[0]] * len(x_valid)
373
+ pred_prob = np.array([1.] * len(x_valid))
374
+ else:
375
+ pred = model.predict(x_valid)
376
+ pred_prob = model.predict_proba(x_valid)
377
+
378
+ macro_f1 = f1_score(y_valid, pred, average='macro')
379
+ weighted_f1 = _weighted_f1(y_valid, pred)
380
+ acc = accuracy_score(y_valid, pred)
381
+
382
+ # 3. auroc
383
+ # size = [a["size"] for a in metadata["columns"] if a["name"] == "label"][0]
384
+ size = len(set(unique_labels))
385
+ rest_label = set(range(size)) - set(unique_labels)
386
+ tmp = []
387
+ j = 0
388
+ for i in range(size):
389
+ if i in rest_label:
390
+ tmp.append(np.array([0] * y_valid.shape[0])[:,np.newaxis])
391
+ else:
392
+ try:
393
+ tmp.append(pred_prob[:,[j]])
394
+ except:
395
+ tmp.append(pred_prob[:, np.newaxis])
396
+ j += 1
397
+
398
+ roc_auc = roc_auc_score(np.eye(size)[y_valid], np.hstack(tmp), multi_class='ovr')
399
+
400
+ results.append(
401
+ {
402
+ "name": model_repr,
403
+ "param": param,
404
+ "macro_f1": macro_f1,
405
+ "weighted_f1": weighted_f1,
406
+ "roc_auc": roc_auc,
407
+ "accuracy": acc
408
+ }
409
+ )
410
+
411
+ results = pd.DataFrame(results)
412
+ results['avg'] = results.loc[:, ['macro_f1', 'weighted_f1', 'roc_auc']].mean(axis=1)
413
+ best_f1_param = results.param[results.macro_f1.idxmax()]
414
+ best_weighted_param = results.param[results.weighted_f1.idxmax()]
415
+ best_auroc_param = results.param[results.roc_auc.idxmax()]
416
+ best_acc_param = results.param[results.accuracy.idxmax()]
417
+ best_avg_param = results.param[results.avg.idxmax()]
418
+
419
+
420
+ # test the best model
421
+ results = pd.DataFrame(results)
422
+ # best_param = results.param[results.macro_f1.idxmax()]
423
+
424
+ def _calc(best_model):
425
+ best_scores = []
426
+
427
+ x_train = x_trains
428
+ y_train = y_trains
429
+
430
+ try:
431
+ best_model.fit(x_train, y_train)
432
+ except:
433
+ pass
434
+
435
+ if len(unique_labels) != len(np.unique(y_test)):
436
+ pred = [unique_labels[0]] * len(x_test)
437
+ pred_prob = np.array([1.] * len(x_test))
438
+ else:
439
+ pred = best_model.predict(x_test)
440
+ pred_prob = best_model.predict_proba(x_test)
441
+
442
+ macro_f1 = f1_score(y_test, pred, average='macro')
443
+ weighted_f1 = _weighted_f1(y_test, pred)
444
+ acc = accuracy_score(y_test, pred)
445
+
446
+ # 3. auroc
447
+ size = len(set(unique_labels))
448
+ rest_label = set(range(size)) - set(unique_labels)
449
+ tmp = []
450
+ j = 0
451
+ for i in range(size):
452
+ if i in rest_label:
453
+ tmp.append(np.array([0] * y_test.shape[0])[:,np.newaxis])
454
+ else:
455
+ try:
456
+ tmp.append(pred_prob[:,[j]])
457
+ except:
458
+ tmp.append(pred_prob[:, np.newaxis])
459
+ j += 1
460
+ roc_auc = roc_auc_score(np.eye(size)[y_test], np.hstack(tmp), multi_class='ovr')
461
+
462
+ best_scores.append(
463
+ {
464
+ "name": model_repr,
465
+ "macro_f1": macro_f1,
466
+ "weighted_f1": weighted_f1,
467
+ "roc_auc": roc_auc,
468
+ "accuracy": acc
469
+ }
470
+ )
471
+ return pd.DataFrame(best_scores)
472
+
473
+ def _df(dataframe):
474
+ return {
475
+ "name": model_repr,
476
+ "macro_f1": dataframe.macro_f1.values[0],
477
+ "roc_auc": dataframe.roc_auc.values[0],
478
+ "weighted_f1": dataframe.weighted_f1.values[0],
479
+ "accuracy": dataframe.accuracy.values[0],
480
+ }
481
+
482
+ best_f1_scores.append(_df(_calc(model_class(**best_f1_param))))
483
+ best_weighted_scores.append(_df(_calc(model_class(**best_weighted_param))))
484
+ best_auroc_scores.append(_df(_calc(model_class(**best_auroc_param))))
485
+ best_acc_scores.append(_df(_calc(model_class(**best_acc_param))))
486
+ best_avg_scores.append(_df(_calc(model_class(**best_avg_param))))
487
+
488
+ return best_f1_scores, best_weighted_scores, best_auroc_scores, best_acc_scores, best_avg_scores
489
+
490
+ @ignore_warnings(category=ConvergenceWarning)
491
+ def _evaluate_binary_classification(train, test, info, val=None):
492
+ x_trains, y_trains, x_valid, y_valid, x_test, y_test, classifiers = prepare_ml_problem(train, test, info, val=val)
493
+
494
+ unique_labels = np.unique(y_trains)
495
+
496
+ best_f1_scores = []
497
+ best_weighted_scores = []
498
+ best_auroc_scores = []
499
+ best_acc_scores = []
500
+ best_avg_scores = []
501
+
502
+ for model_spec in classifiers:
503
+
504
+ model_class = model_spec['class']
505
+ model_kwargs = model_spec.get('kwargs', dict())
506
+ model_repr = model_class.__name__
507
+
508
+ unique_labels = np.unique(y_trains)
509
+
510
+ param_set = list(ParameterGrid(model_kwargs))
511
+
512
+ results = []
513
+ for param in tqdm(param_set):
514
+ model = model_class(**param)
515
+
516
+ try:
517
+ model.fit(x_trains, y_trains)
518
+ except ValueError:
519
+ pass
520
+
521
+ if len(unique_labels) == 1:
522
+ pred = [unique_labels[0]] * len(x_valid)
523
+ pred_prob = np.array([1.] * len(x_valid))
524
+ else:
525
+ pred = model.predict(x_valid)
526
+ pred_prob = model.predict_proba(x_valid)
527
+
528
+ binary_f1 = f1_score(y_valid, pred, average='binary')
529
+ weighted_f1 = _weighted_f1(y_valid, pred)
530
+ acc = accuracy_score(y_valid, pred)
531
+ precision = precision_score(y_valid, pred, average='binary')
532
+ recall = recall_score(y_valid, pred, average='binary')
533
+ macro_f1 = f1_score(y_valid, pred, average='macro')
534
+
535
+ # auroc
536
+ size = 2
537
+ rest_label = set(range(size)) - set(unique_labels)
538
+ tmp = []
539
+ j = 0
540
+ for i in range(size):
541
+ if i in rest_label:
542
+ tmp.append(np.array([0] * y_valid.shape[0])[:,np.newaxis])
543
+ else:
544
+ try:
545
+ tmp.append(pred_prob[:,[j]])
546
+ except:
547
+ tmp.append(pred_prob[:, np.newaxis])
548
+ j += 1
549
+ roc_auc = roc_auc_score(np.eye(size)[y_valid], np.hstack(tmp))
550
+
551
+ results.append(
552
+ {
553
+ "name": model_repr,
554
+ "param": param,
555
+ "binary_f1": binary_f1,
556
+ "weighted_f1": weighted_f1,
557
+ "roc_auc": roc_auc,
558
+ "accuracy": acc,
559
+ "precision": precision,
560
+ "recall": recall,
561
+ "macro_f1": macro_f1
562
+ }
563
+ )
564
+
565
+
566
+ # test the best model
567
+ results = pd.DataFrame(results)
568
+ results['avg'] = results.loc[:, ['binary_f1', 'weighted_f1', 'roc_auc']].mean(axis=1)
569
+ best_f1_param = results.param[results.binary_f1.idxmax()]
570
+ best_weighted_param = results.param[results.weighted_f1.idxmax()]
571
+ best_auroc_param = results.param[results.roc_auc.idxmax()]
572
+ best_acc_param = results.param[results.accuracy.idxmax()]
573
+ best_avg_param = results.param[results.avg.idxmax()]
574
+
575
+
576
+ def _calc(best_model):
577
+ best_scores = []
578
+
579
+ best_model.fit(x_trains, y_trains)
580
+
581
+ if len(unique_labels) == 1:
582
+ pred = [unique_labels[0]] * len(x_test)
583
+ pred_prob = np.array([1.] * len(x_test))
584
+ else:
585
+ pred = best_model.predict(x_test)
586
+ pred_prob = best_model.predict_proba(x_test)
587
+
588
+ binary_f1 = f1_score(y_test, pred, average='binary')
589
+ weighted_f1 = _weighted_f1(y_test, pred)
590
+ acc = accuracy_score(y_test, pred)
591
+ precision = precision_score(y_test, pred, average='binary')
592
+ recall = recall_score(y_test, pred, average='binary')
593
+ macro_f1 = f1_score(y_test, pred, average='macro')
594
+
595
+ # auroc
596
+ size = 2
597
+ rest_label = set(range(size)) - set(unique_labels)
598
+ tmp = []
599
+ j = 0
600
+ for i in range(size):
601
+ if i in rest_label:
602
+ tmp.append(np.array([0] * y_test.shape[0])[:,np.newaxis])
603
+ else:
604
+ try:
605
+ tmp.append(pred_prob[:,[j]])
606
+ except:
607
+ tmp.append(pred_prob[:, np.newaxis])
608
+ j += 1
609
+ try:
610
+ roc_auc = roc_auc_score(np.eye(size)[y_test], np.hstack(tmp))
611
+ except ValueError:
612
+ tmp[1] = tmp[1].reshape(20000, 1)
613
+ roc_auc = roc_auc_score(np.eye(size)[y_test], np.hstack(tmp))
614
+
615
+ best_scores.append(
616
+ {
617
+ "name": model_repr,
618
+ # "param": param,
619
+ "binary_f1": binary_f1,
620
+ "weighted_f1": weighted_f1,
621
+ "roc_auc": roc_auc,
622
+ "accuracy": acc,
623
+ "precision": precision,
624
+ "recall": recall,
625
+ "macro_f1": macro_f1
626
+ }
627
+ )
628
+
629
+ return pd.DataFrame(best_scores)
630
+ def _df(dataframe):
631
+ return {
632
+ "name": model_repr,
633
+ "binary_f1": dataframe.binary_f1.values[0],
634
+ "roc_auc": dataframe.roc_auc.values[0],
635
+ "weighted_f1": dataframe.weighted_f1.values[0],
636
+ "accuracy": dataframe.accuracy.values[0],
637
+ }
638
+
639
+ best_f1_scores.append(_df(_calc(model_class(**best_f1_param))))
640
+ best_weighted_scores.append(_df(_calc(model_class(**best_weighted_param))))
641
+ best_auroc_scores.append(_df(_calc(model_class(**best_auroc_param))))
642
+ best_acc_scores.append(_df(_calc(model_class(**best_acc_param))))
643
+ best_avg_scores.append(_df(_calc(model_class(**best_avg_param))))
644
+
645
+ return best_f1_scores, best_weighted_scores, best_auroc_scores, best_acc_scores, best_avg_scores
646
+
647
+ @ignore_warnings(category=ConvergenceWarning)
648
+ def _evaluate_regression(train, test, info, val=None):
649
+
650
+ x_trains, y_trains, x_valid, y_valid, x_test, y_test, regressors = prepare_ml_problem(train, test, info, val=val)
651
+
652
+
653
+ best_r2_scores = []
654
+ best_ev_scores = []
655
+ best_mae_scores = []
656
+ best_rmse_scores = []
657
+ best_avg_scores = []
658
+
659
+ y_trains = np.log(np.clip(y_trains, 1, 20000))
660
+ y_test = np.log(np.clip(y_test, 1, 20000))
661
+
662
+ for model_spec in regressors:
663
+ model_class = model_spec['class']
664
+ model_kwargs = model_spec.get('kwargs', dict())
665
+ model_repr = model_class.__name__
666
+
667
+ param_set = list(ParameterGrid(model_kwargs))
668
+
669
+ results = []
670
+ for param in tqdm(param_set):
671
+ model = model_class(**param)
672
+ model.fit(x_trains, y_trains)
673
+ pred = model.predict(x_valid)
674
+
675
+ r2 = r2_score(y_valid, pred)
676
+ explained_variance = explained_variance_score(y_valid, pred)
677
+ mean_squared = mean_squared_error(y_valid, pred)
678
+ root_mean_squared = np.sqrt(mean_squared)
679
+ mean_absolute = mean_absolute_error(y_valid, pred)
680
+
681
+ results.append(
682
+ {
683
+ "name": model_repr,
684
+ "param": param,
685
+ "r2": r2,
686
+ "explained_variance": explained_variance,
687
+ "mean_squared": mean_squared,
688
+ "mean_absolute": mean_absolute,
689
+ "rmse": root_mean_squared
690
+ }
691
+ )
692
+
693
+ results = pd.DataFrame(results)
694
+ # results['avg'] = results.loc[:, ['r2', 'rmse']].mean(axis=1)
695
+ best_r2_param = results.param[results.r2.idxmax()]
696
+ best_ev_param = results.param[results.explained_variance.idxmax()]
697
+ best_mae_param = results.param[results.mean_absolute.idxmin()]
698
+ best_rmse_param = results.param[results.rmse.idxmin()]
699
+ # best_avg_param = results.param[results.avg.idxmax()]
700
+
701
+ def _calc(best_model):
702
+ best_scores = []
703
+ x_train, y_train = x_trains, y_trains
704
+
705
+ best_model.fit(x_train, y_train)
706
+ pred = best_model.predict(x_test)
707
+
708
+ r2 = r2_score(y_test, pred)
709
+ explained_variance = explained_variance_score(y_test, pred)
710
+ mean_squared = mean_squared_error(y_test, pred)
711
+ root_mean_squared = np.sqrt(mean_squared)
712
+ mean_absolute = mean_absolute_error(y_test, pred)
713
+
714
+ best_scores.append(
715
+ {
716
+ "name": model_repr,
717
+ "param": param,
718
+ "r2": r2,
719
+ "explained_variance": explained_variance,
720
+ "mean_squared": mean_squared,
721
+ "mean_absolute": mean_absolute,
722
+ "rmse": root_mean_squared
723
+ }
724
+ )
725
+
726
+ return pd.DataFrame(best_scores)
727
+
728
+ def _df(dataframe):
729
+ return {
730
+ "name": model_repr,
731
+ "r2": dataframe.r2.values[0].astype(float),
732
+ "explained_variance": dataframe.explained_variance.values[0].astype(float),
733
+ "MAE": dataframe.mean_absolute.values[0].astype(float),
734
+ "RMSE": dataframe.rmse.values[0].astype(float),
735
+ }
736
+
737
+ best_r2_scores.append(_df(_calc(model_class(**best_r2_param))))
738
+ best_ev_scores.append(_df(_calc(model_class(**best_ev_param))))
739
+ best_mae_scores.append(_df(_calc(model_class(**best_mae_param))))
740
+ best_rmse_scores.append(_df(_calc(model_class(**best_rmse_param))))
741
+
742
+ return best_r2_scores, best_rmse_scores
743
+
744
+ @ignore_warnings(category=ConvergenceWarning)
745
+ def compute_diversity(train, fake):
746
+ nearest_k = 5
747
+ if train.shape[0] >= 50000:
748
+ num = np.random.randint(0, train.shape[0], 50000)
749
+ real_features = train[num]
750
+ fake_features_lst = [i[num] for i in fake]
751
+ else:
752
+ num = train.shape[0]
753
+ real_features = train[:num]
754
+ fake_features_lst = [i[:num] for i in fake]
755
+ scores = []
756
+ for i, data in enumerate(fake_features_lst):
757
+ fake_features = data
758
+ metrics = compute_prdc(real_features=real_features,
759
+ fake_features=fake_features,
760
+ nearest_k=nearest_k)
761
+ metrics['i'] = i
762
+ scores.append(metrics)
763
+ return pd.DataFrame(scores).mean(axis=0), pd.DataFrame(scores).std(axis=0)
764
+
765
+ _EVALUATORS = {
766
+ 'binclass': _evaluate_binary_classification,
767
+ 'multiclass': _evaluate_multi_classification,
768
+ 'regression': _evaluate_regression
769
+ }
770
+
771
+ def get_evaluator(problem_type):
772
+ return _EVALUATORS[problem_type]
773
+
774
+
775
+ def compute_scores(train, test, synthesized_data, metadata, eval):
776
+ a, b, c = _EVALUATORS[metadata['problem_type']](train=train, test=test, fake=synthesized_data, metadata=metadata, eval=eval)
777
+ if eval is None:
778
+ return a.mean(axis=0), a.std(axis=0), a[['name','param']]
779
+ else:
780
+ return a.mean(axis=0), a.std(axis=0)
781
+
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/eval/mle/tabular_dataload.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The Google Research Authors.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ # pylint: skip-file
17
+ """Return training and evaluation/test datasets from config files."""
18
+ import torch
19
+ import numpy as np
20
+ import pandas as pd
21
+ from tabular_transformer import GeneralTransformer
22
+ import json
23
+ import logging
24
+ import os
25
+
26
+ CATEGORICAL = "categorical"
27
+ CONTINUOUS = "continuous"
28
+
29
+ LOGGER = logging.getLogger(__name__)
30
+
31
+ DATA_PATH = os.path.join(os.path.dirname(__file__), 'tabular_datasets')
32
+
33
+ def _load_json(path):
34
+ with open(path) as json_file:
35
+ return json.load(json_file)
36
+
37
+
38
+ def _load_file(filename, loader):
39
+ local_path = os.path.join(DATA_PATH, filename)
40
+
41
+ if loader == np.load:
42
+ return loader(local_path, allow_pickle=True)
43
+ return loader(local_path)
44
+
45
+
46
+ def _get_columns(metadata):
47
+ categorical_columns = list()
48
+
49
+ for column_idx, column in enumerate(metadata['columns']):
50
+ if column['type'] == CATEGORICAL:
51
+ categorical_columns.append(column_idx)
52
+
53
+ return categorical_columns
54
+
55
+
56
+ def load_data(name):
57
+ data_dir = f'data/{name}'
58
+ info_path = f'{data_dir}/info.json'
59
+
60
+ train = pd.read_csv(f'{data_dir}/train.csv').to_numpy()
61
+ test = pd.read_csv(f'{data_dir}/test.csv').to_numpy()
62
+
63
+ with open(f'{data_dir}/info.json', 'r') as f:
64
+ info = json.load(f)
65
+
66
+ task_type = info['task_type']
67
+
68
+ num_cols = info['num_col_idx']
69
+ cat_cols = info['cat_col_idx']
70
+ target_cols = info['target_col_idx']
71
+
72
+ if task_type != 'regression':
73
+ cat_cols = cat_cols + target_cols
74
+
75
+ return train, test, (cat_cols, info)
76
+
77
+
78
+ def get_dataset(FLAGS, evaluation=False):
79
+
80
+ batch_size = FLAGS.training_batch_size if not evaluation else FLAGS.eval_batch_size
81
+
82
+ if batch_size % torch.cuda.device_count() != 0:
83
+ raise ValueError(f'Batch sizes ({batch_size} must be divided by'
84
+ f'the number of devices ({torch.cuda.device_count()})')
85
+
86
+
87
+ # Create dataset builders for tabular data.
88
+ train, test, cols = load_data(FLAGS.dataname)
89
+ cols_idx = list(np.arange(train.shape[1]))
90
+ dis_idx = cols[0]
91
+ con_idx = [x for x in cols_idx if x not in dis_idx]
92
+
93
+ #split continuous and categorical
94
+ train_con = train[:,con_idx]
95
+ train_dis = train[:,dis_idx]
96
+
97
+ #new index
98
+ cat_idx_ = list(np.arange(train_dis.shape[1]))[:len(cols[0])]
99
+
100
+ transformer_con = GeneralTransformer()
101
+ transformer_dis = GeneralTransformer()
102
+
103
+ transformer_con.fit(train_con, [])
104
+ transformer_dis.fit(train_dis, cat_idx_)
105
+
106
+ train_con_data = transformer_con.transform(train_con)
107
+ train_dis_data = transformer_dis.transform(train_dis)
108
+
109
+
110
+ return train, train_con_data, train_dis_data, test, (transformer_con, transformer_dis, cols[1]), con_idx, dis_idx
111
+
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/eval/mle/tabular_transformer.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+
4
+ CATEGORICAL = "categorical"
5
+ CONTINUOUS = "continuous"
6
+
7
+ class Transformer:
8
+
9
+ @staticmethod
10
+ def get_metadata(data, categorical_columns=tuple()):
11
+ meta = []
12
+
13
+ df = pd.DataFrame(data)
14
+ for index in df:
15
+ column = df[index]
16
+
17
+ if index in categorical_columns:
18
+ mapper = column.value_counts().index.tolist()
19
+ meta.append({
20
+ "name": index,
21
+ "type": CATEGORICAL,
22
+ "size": len(mapper),
23
+ "i2s": mapper
24
+ })
25
+ else:
26
+ meta.append({
27
+ "name": index,
28
+ "type": CONTINUOUS,
29
+ "min": column.min(),
30
+ "max": column.max(),
31
+ })
32
+
33
+ return meta
34
+
35
+ def fit(self, data, categorical_columns=tuple()):
36
+ raise NotImplementedError
37
+
38
+ def transform(self, data):
39
+ raise NotImplementedError
40
+
41
+ def inverse_transform(self, data):
42
+ raise NotImplementedError
43
+
44
+
45
+ class GeneralTransformer(Transformer):
46
+
47
+ def __init__(self, act='tanh'):
48
+ self.act = act
49
+ self.meta = None
50
+ self.output_dim = None
51
+
52
+ def fit(self, data, categorical_columns=tuple()):
53
+ self.meta = self.get_metadata(data, categorical_columns)
54
+ self.output_dim = 0
55
+ for info in self.meta:
56
+ if info['type'] in [CONTINUOUS]:
57
+ self.output_dim += 1
58
+ else:
59
+ self.output_dim += info['size']
60
+
61
+ def transform(self, data):
62
+ data_t = []
63
+ self.output_info = []
64
+ for id_, info in enumerate(self.meta):
65
+ col = data[:, id_]
66
+ if info['type'] == CONTINUOUS:
67
+ col = (col - (info['min'])) / (info['max'] - info['min'])
68
+ if self.act == 'tanh':
69
+ col = col * 2 - 1
70
+ data_t.append(col.reshape([-1, 1]))
71
+ self.output_info.append((1, self.act))
72
+
73
+ else:
74
+ col_t = np.zeros([len(data), info['size']])
75
+ idx = list(map(info['i2s'].index, col))
76
+ col_t[np.arange(len(data)), idx] = 1
77
+ data_t.append(col_t)
78
+ self.output_info.append((info['size'], 'softmax'))
79
+
80
+ return np.concatenate(data_t, axis=1)
81
+
82
+ def inverse_transform(self, data):
83
+ if self.meta[1]['type'] == CONTINUOUS:
84
+ data_t = np.zeros([len(data), len(self.meta)])
85
+ else:
86
+ dtype = np.dtype('U50')
87
+ data_t = np.empty([len(data), len(self.meta)], dtype=dtype)
88
+
89
+
90
+ data = data.copy()
91
+ for id_, info in enumerate(self.meta):
92
+
93
+ if info['type'] == CONTINUOUS:
94
+ current = data[:, 0]
95
+ data = data[:, 1:]
96
+
97
+ if self.act == 'tanh':
98
+ current = (current + 1) / 2
99
+
100
+ current = np.clip(current, 0, 1)
101
+ data_t[:, id_] = current * (info['max'] - info['min']) + info['min']
102
+
103
+ else:
104
+ current = data[:, :info['size']]
105
+ data = data[:, info['size']:]
106
+ idx = np.argmax(current, axis=1)
107
+ recovered = list(map(info['i2s'].__getitem__, idx))
108
+
109
+ data_t[:, id_] = recovered
110
+ return data_t
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/eval/visualize_density.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # %%
2
+ import numpy as np
3
+ import pandas as pd
4
+ import torch
5
+ import os
6
+
7
+ import json
8
+
9
+ # Metrics
10
+ from sdmetrics.visualization import get_column_plot
11
+
12
+ import plotly.io as pio
13
+ from PIL import Image
14
+ from io import BytesIO
15
+
16
+ from tqdm import tqdm
17
+ import argparse
18
+
19
+ def main(args):
20
+ dataname = args.dataname
21
+ sample_file_name = args.sample_file_name
22
+
23
+ syn_path = f'synthetic/{dataname}/{sample_file_name}'
24
+ real_path = f'synthetic/{dataname}/real.csv'
25
+
26
+ syn_data = pd.read_csv(syn_path)
27
+ real_data = pd.read_csv(real_path)
28
+
29
+ print((real_data[:2]))
30
+
31
+ data_dir = f'data/{dataname}'
32
+ with open(f'{data_dir}/info.json', 'r') as f:
33
+ info = json.load(f)
34
+
35
+ big_img = plot_density(syn_data, real_data, info)
36
+
37
+ save_dir = f"eval/density_graphs/{dataname}"
38
+ if not os.path.exists(save_dir):
39
+ os.makedirs(save_dir)
40
+ save_path = os.path.join(save_dir, sample_file_name.replace('.csv', '.png'))
41
+ big_img.save(save_path)
42
+ print(f"Saved density graph to {save_path}")
43
+
44
+ def plot_density(syn_data, real_data, info, num_per_row=3):
45
+ column_names = info['column_names']
46
+ num_cat = len(column_names)
47
+ num_col = num_per_row
48
+ num_row = (num_cat-1)//num_col+1
49
+
50
+ imgs = []
51
+ for i, col in tqdm(enumerate(column_names), total = len(column_names)):
52
+ # plot_type = 'bar' if i in info['cat_col_idx'] else 'distplot'
53
+ plot_type = 'bar' if info['metadata']['columns'][str(i)]['sdtype'] == 'categorical' else 'distplot'
54
+ if plot_type == 'distplot' and (syn_data[col][0] == syn_data[col]).all(): # to tackle a very weird bug
55
+ # If the continuous data all aggregate at a single value, get_column_plot() cannot plot a density curve for it.
56
+ # So, we perturb one entry of the cont data by a small amount
57
+ print(f"\n ALERT: the generated samples column_{i} with name '{col}' all has the same value of {syn_data[col][0]} \n")
58
+ syn_data[col][0] += 1e-5
59
+ fig = get_column_plot(
60
+ real_data=real_data,
61
+ synthetic_data=syn_data,
62
+ column_name=col,
63
+ plot_type=plot_type
64
+ )
65
+
66
+ img_bytes = pio.to_image(fig, format='png')
67
+ img = Image.open(BytesIO(img_bytes))
68
+ imgs.append(img)
69
+
70
+ width, height = imgs[0].size
71
+ big_img = Image.new('RGB', (width * num_col, height * num_row))
72
+ for i, img in enumerate(imgs):
73
+ coordinate = (i%num_col * width, i//num_col * height)
74
+ big_img.paste(img, coordinate)
75
+ return big_img
76
+
77
+ if __name__ == '__main__':
78
+ parser = argparse.ArgumentParser()
79
+
80
+ parser.add_argument('--dataname', type=str, default='adult')
81
+ parser.add_argument('--sample_file_name', type=str, default='tabsyn.csv')
82
+
83
+ args = parser.parse_args()
84
+
85
+ main(args)
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/main.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from ef_vfm.main import main as ef_vfm_main
3
+ import argparse
4
+
5
+ if __name__ == '__main__':
6
+ parser = argparse.ArgumentParser(description='Training of EF-VFM (TabbyFlow) for tabular data generation')
7
+
8
+ # General configs
9
+ parser.add_argument('--dataname', type=str, default='adult', help='Name dataset, one of those in data/ dir')
10
+ parser.add_argument('--mode', type=str, default='train', help='train or test')
11
+ parser.add_argument('--method', type=str, default='ef_vfm', help='Currently we only release our model EF-VFM. Baselines will be released soon.')
12
+ parser.add_argument('--gpu', type=int, default=0, help='GPU index')
13
+ parser.add_argument('--debug', action='store_true', help='Enable debug mode')
14
+ parser.add_argument('--no_wandb', action='store_true', help='disable wandb')
15
+ parser.add_argument('--exp_name', type=str, default=None, help='Experiment name, used to name log directories and the wandb run name')
16
+ parser.add_argument('--deterministic', action='store_true', help='Whether to make the entire process deterministic, i.e., fix global random seeds')
17
+
18
+ # Configs for testing ef_vfm
19
+ parser.add_argument('--num_samples_to_generate', type=int, default=None, help='Number of samples to be generated while testing')
20
+ parser.add_argument('--ckpt_path', type=str, default=None, help='Path to the model checkpoint to be tested')
21
+ parser.add_argument('--report', action='store_true', help="Report testing mode: this mode sequentially runs <num_runs> test runs and report the avg and std")
22
+ parser.add_argument('--num_runs', type=int, default=20, help="Number of runs to be averaged in the report testing mode")
23
+
24
+ args = parser.parse_args()
25
+
26
+ # check cuda
27
+ if args.gpu != -1 and torch.cuda.is_available():
28
+ args.device = f'cuda:{args.gpu}'
29
+ else:
30
+ args.device = 'cpu'
31
+
32
+ ef_vfm_main(args)
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/process_dataset.py ADDED
@@ -0,0 +1,492 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ import os
4
+ import sys
5
+ import json
6
+ import argparse
7
+
8
+ from sklearn.preprocessing import OrdinalEncoder
9
+ from sklearn import model_selection
10
+
11
+ TYPE_TRANSFORM ={
12
+ 'float', np.float32,
13
+ 'str', str,
14
+ 'int', int
15
+ }
16
+
17
+ INFO_PATH = 'data/Info'
18
+
19
+ parser = argparse.ArgumentParser(description='process dataset')
20
+
21
+ # General configs
22
+ parser.add_argument('--dataname', type=str, default=None, help='Name of dataset.')
23
+ args = parser.parse_args()
24
+
25
+ def preprocess_beijing():
26
+ with open(f'{INFO_PATH}/beijing.json', 'r') as f:
27
+ info = json.load(f)
28
+
29
+ data_path = info['raw_data_path']
30
+
31
+ data_df = pd.read_csv(data_path)
32
+ columns = data_df.columns
33
+
34
+ data_df = data_df[columns[1:]]
35
+
36
+
37
+ df_cleaned = data_df.dropna()
38
+ df_cleaned.to_csv(info['data_path'], index = False)
39
+
40
+ def preprocess_beijing_dcr():
41
+ with open(f'{INFO_PATH}/beijing_dcr.json', 'r') as f:
42
+ info = json.load(f)
43
+
44
+ data_path = info['raw_data_path']
45
+
46
+ data_df = pd.read_csv(data_path)
47
+ columns = data_df.columns
48
+
49
+ data_df = data_df[columns[1:]]
50
+
51
+ df_cleaned = data_df.dropna()
52
+ df_cleaned.to_csv(info['data_path'], index = False)
53
+
54
+ def preprocess_news(remove_cat=False):
55
+ name = 'news' if not remove_cat else 'news_nocat'
56
+ with open(f'{INFO_PATH}/{name}.json', 'r') as f:
57
+ info = json.load(f)
58
+
59
+ data_path = info['raw_data_path']
60
+ data_df = pd.read_csv(data_path)
61
+ data_df = data_df.drop('url', axis=1)
62
+
63
+ columns = np.array(data_df.columns.tolist())
64
+
65
+ cat_columns1 = columns[list(range(12,18))]
66
+ cat_columns2 = columns[list(range(30,38))]
67
+
68
+ if not remove_cat:
69
+ cat_col1 = data_df[cat_columns1].astype(int).to_numpy().argmax(axis = 1)
70
+ cat_col2 = data_df[cat_columns2].astype(int).to_numpy().argmax(axis = 1)
71
+
72
+ data_df = data_df.drop(cat_columns2, axis=1)
73
+ data_df = data_df.drop(cat_columns1, axis=1)
74
+
75
+ if not remove_cat:
76
+ data_df['data_channel'] = cat_col1
77
+ data_df['weekday'] = cat_col2
78
+
79
+ data_save_path = f'data/{name}/{name}.csv'
80
+ data_df.to_csv(f'{data_save_path}', index = False)
81
+
82
+ columns = np.array(data_df.columns.tolist())
83
+ num_columns = columns[list(range(45))]
84
+ cat_columns = ['data_channel', 'weekday'] if not remove_cat else []
85
+ target_columns = columns[[45]]
86
+
87
+ info['num_col_idx'] = list(range(45))
88
+ info['cat_col_idx'] = [46, 47] if not remove_cat else []
89
+ info['target_col_idx'] = [45]
90
+ info['data_path'] = data_save_path
91
+
92
+ with open(f'{INFO_PATH}/{name}.json', 'w') as file:
93
+ json.dump(info, file, indent=4)
94
+
95
+ def preprocess_news_dcr(remove_cat=False):
96
+ name = 'news_dcr' if not remove_cat else 'news_nocat_dcr'
97
+ with open(f'{INFO_PATH}/{name}.json', 'r') as f:
98
+ info = json.load(f)
99
+
100
+ data_path = info['raw_data_path']
101
+ data_df = pd.read_csv(data_path)
102
+ data_df = data_df.drop('url', axis=1)
103
+
104
+ columns = np.array(data_df.columns.tolist())
105
+
106
+ cat_columns1 = columns[list(range(12,18))]
107
+ cat_columns2 = columns[list(range(30,38))]
108
+
109
+ if not remove_cat:
110
+ cat_col1 = data_df[cat_columns1].astype(int).to_numpy().argmax(axis = 1)
111
+ cat_col2 = data_df[cat_columns2].astype(int).to_numpy().argmax(axis = 1)
112
+
113
+ data_df = data_df.drop(cat_columns2, axis=1)
114
+ data_df = data_df.drop(cat_columns1, axis=1)
115
+
116
+ if not remove_cat:
117
+ data_df['data_channel'] = cat_col1
118
+ data_df['weekday'] = cat_col2
119
+
120
+ data_save_path = f'data/{name}/{name}.csv'
121
+ data_df.to_csv(f'{data_save_path}', index = False)
122
+
123
+ columns = np.array(data_df.columns.tolist())
124
+ num_columns = columns[list(range(45))]
125
+ cat_columns = ['data_channel', 'weekday'] if not remove_cat else []
126
+ target_columns = columns[[45]]
127
+
128
+ info['num_col_idx'] = list(range(45))
129
+ info['cat_col_idx'] = [46, 47] if not remove_cat else []
130
+ info['target_col_idx'] = [45]
131
+ info['data_path'] = data_save_path
132
+
133
+ with open(f'{INFO_PATH}/{name}.json', 'w') as file:
134
+ json.dump(info, file, indent=4)
135
+
136
+
137
+ def get_column_name_mapping(data_df, num_col_idx, cat_col_idx, target_col_idx, column_names = None):
138
+
139
+ if not column_names:
140
+ column_names = np.array(data_df.columns.tolist())
141
+
142
+ idx_mapping = {}
143
+
144
+ curr_num_idx = 0
145
+ curr_cat_idx = len(num_col_idx)
146
+ curr_target_idx = curr_cat_idx + len(cat_col_idx)
147
+
148
+ for idx in range(len(column_names)):
149
+
150
+ if idx in num_col_idx:
151
+ idx_mapping[int(idx)] = curr_num_idx
152
+ curr_num_idx += 1
153
+ elif idx in cat_col_idx:
154
+ idx_mapping[int(idx)] = curr_cat_idx
155
+ curr_cat_idx += 1
156
+ else:
157
+ idx_mapping[int(idx)] = curr_target_idx
158
+ curr_target_idx += 1
159
+
160
+ inverse_idx_mapping = {}
161
+ for k, v in idx_mapping.items():
162
+ inverse_idx_mapping[int(v)] = k
163
+
164
+ idx_name_mapping = {}
165
+
166
+ for i in range(len(column_names)):
167
+ idx_name_mapping[int(i)] = column_names[i]
168
+
169
+ return idx_mapping, inverse_idx_mapping, idx_name_mapping
170
+
171
+
172
+ def train_val_test_split(data_df, cat_columns, num_train = 0, num_test = 0):
173
+ total_num = data_df.shape[0]
174
+ idx = np.arange(total_num)
175
+
176
+ seed = 1234
177
+
178
+ while True:
179
+ np.random.seed(seed)
180
+ np.random.shuffle(idx)
181
+
182
+ train_idx = idx[:num_train]
183
+ test_idx = idx[-num_test:]
184
+
185
+ train_df = data_df.loc[train_idx]
186
+ test_df = data_df.loc[test_idx]
187
+
188
+ flag = 0
189
+ for i in cat_columns:
190
+ if len(set(train_df[i])) != len(set(data_df[i])):
191
+ flag = 1
192
+ break
193
+
194
+ if flag == 0:
195
+ break
196
+ else:
197
+ seed += 1
198
+
199
+ return train_df, test_df, seed
200
+
201
+
202
+ def process_data(name):
203
+
204
+ if name == 'news':
205
+ preprocess_news()
206
+ elif name == 'news_nocat':
207
+ preprocess_news(remove_cat=True)
208
+ elif name == 'news_dcr':
209
+ preprocess_news_dcr()
210
+ elif name == 'beijing':
211
+ preprocess_beijing()
212
+ elif name == 'beijing_dcr':
213
+ preprocess_beijing_dcr()
214
+
215
+ with open(f'{INFO_PATH}/{name}.json', 'r') as f:
216
+ info = json.load(f)
217
+
218
+ data_path = info['data_path']
219
+ if info['file_type'] == 'csv':
220
+ data_df = pd.read_csv(data_path, header = info['header'])
221
+
222
+ elif info['file_type'] == 'xls':
223
+ data_df = pd.read_excel(data_path, sheet_name='Data', header=1)
224
+ data_df = data_df.drop('ID', axis=1)
225
+
226
+ num_data = data_df.shape[0]
227
+
228
+ column_names = info['column_names'] if info['column_names'] else data_df.columns.tolist()
229
+
230
+ num_col_idx = info['num_col_idx']
231
+ cat_col_idx = info['cat_col_idx']
232
+ target_col_idx = info['target_col_idx']
233
+
234
+ num_columns = [column_names[i] for i in num_col_idx]
235
+ cat_columns = [column_names[i] for i in cat_col_idx]
236
+ target_columns = [column_names[i] for i in target_col_idx]
237
+
238
+ idx_mapping, inverse_idx_mapping, idx_name_mapping = get_column_name_mapping(data_df, num_col_idx, cat_col_idx, target_col_idx, column_names)
239
+
240
+ has_val = bool(info['val_path'])
241
+ val_df = pd.DataFrame(columns=data_df.columns).astype(data_df.dtypes) # by default (val_path is not provided), set val_Df to be empty
242
+ if info['test_path']:
243
+
244
+ # if testing data is given
245
+ test_path = info['test_path']
246
+
247
+ if "adult" in name: # BUG: currently data saved at adult's test_path cannot be directly loaded. Consider integrate the following code to a preprocesing function for adult
248
+ with open(test_path, 'r') as f:
249
+ lines = f.readlines()[1:]
250
+ test_save_path = f'data/{name}/test.data'
251
+ if not os.path.exists(test_save_path):
252
+ with open(test_save_path, 'a') as f1:
253
+ for line in lines:
254
+ save_line = line.strip('\n').strip('.')
255
+ f1.write(f'{save_line}\n')
256
+
257
+ test_df = pd.read_csv(test_save_path, header = None)
258
+ else:
259
+ test_df = pd.read_csv(test_path, header = info['header'])
260
+
261
+ if has_val: # currently you cannot have a val path without a test path
262
+ val_path = info['val_path']
263
+ val_df = pd.read_csv(val_path, header = info['header'])
264
+
265
+ train_df = data_df
266
+
267
+ if "dcr" in name and "diabetes" not in name: # create 50/50 splits for dcr datasets; no need for this for diabetes dataset as it's done in preprocessing
268
+ complete_df = pd.concat([train_df, test_df, val_df], axis = 0, ignore_index=True)
269
+ num_data = complete_df.shape[0]
270
+ num_train = int(num_data*0.5)
271
+ num_test = num_data - num_train
272
+ complete_df.rename(columns = idx_name_mapping, inplace=True)
273
+ train_df, test_df, seed = train_val_test_split(complete_df, cat_columns, num_train, num_test)
274
+
275
+ else:
276
+ # Train/ Test Split, 90% Training (50% for dcr eval exclusively), 10% Testing (Validation set will be selected from Training set)
277
+ if "dcr" in name:
278
+ num_train = int(num_data*0.5)
279
+ else:
280
+ num_train = int(num_data*0.9)
281
+ num_test = num_data - num_train
282
+
283
+ train_df, test_df, seed = train_val_test_split(data_df, cat_columns, num_train, num_test)
284
+
285
+ complete_df = pd.concat([train_df, test_df, val_df], axis = 0)
286
+ name_idx_mapping = {val: key for key, val in idx_name_mapping.items()}
287
+ int_columns = []
288
+ int_col_idx = []
289
+ int_col_idx_wrt_num = []
290
+ for i, col_idx in enumerate(num_col_idx):
291
+ col = column_names[col_idx]
292
+ col_data = complete_df.iloc[:,col_idx]
293
+ is_int = (col_data%1 == 0).all()
294
+ if is_int:
295
+ int_columns.append(col)
296
+ int_col_idx.append(name_idx_mapping[col])
297
+ int_col_idx_wrt_num.append(i)
298
+ info['int_col_idx'] = int_col_idx
299
+ info['int_columns'] = int_columns
300
+ info['int_col_idx_wrt_num'] = int_col_idx_wrt_num
301
+
302
+ train_df.columns = range(len(train_df.columns))
303
+ test_df.columns = range(len(test_df.columns))
304
+ val_df.columns = range(len(val_df.columns))
305
+
306
+ print(name, train_df.shape, val_df.shape, test_df.shape, data_df.shape)
307
+
308
+ col_info = {}
309
+
310
+ for col_idx in num_col_idx:
311
+ col_info[col_idx] = {}
312
+ col_info['type'] = 'numerical'
313
+ col_info['max'] = float(train_df[col_idx].max())
314
+ col_info['min'] = float(train_df[col_idx].min())
315
+
316
+ for col_idx in cat_col_idx:
317
+ col_info[col_idx] = {}
318
+ col_info['type'] = 'categorical'
319
+ col_info['categorizes'] = list(set(train_df[col_idx]))
320
+
321
+ for col_idx in target_col_idx:
322
+ if info['task_type'] == 'regression':
323
+ col_info[col_idx] = {}
324
+ col_info['type'] = 'numerical'
325
+ col_info['max'] = float(train_df[col_idx].max())
326
+ col_info['min'] = float(train_df[col_idx].min())
327
+ else:
328
+ col_info[col_idx] = {}
329
+ col_info['type'] = 'categorical'
330
+ col_info['categorizes'] = list(set(train_df[col_idx]))
331
+
332
+ info['column_info'] = col_info
333
+
334
+ train_df.rename(columns = idx_name_mapping, inplace=True)
335
+ test_df.rename(columns = idx_name_mapping, inplace=True)
336
+ val_df.rename(columns = idx_name_mapping, inplace=True)
337
+
338
+ for col in num_columns:
339
+ if (train_df[col] == ' ?').sum() > 0:
340
+ print(col)
341
+ import pdb; pdb.set_trace()
342
+ if (train_df[col] == '?').sum() > 0:
343
+ print(col)
344
+ import pdb; pdb.set_trace()
345
+ train_df.loc[train_df[col] == '?', col] = np.nan
346
+ for col in cat_columns:
347
+ train_df.loc[train_df[col] == '?', col] = 'nan'
348
+ for col in num_columns:
349
+ if (test_df[col] == ' ?').sum() > 0:
350
+ print(col)
351
+ import pdb; pdb.set_trace()
352
+ if (test_df[col] == '?').sum() > 0:
353
+ print(col)
354
+ import pdb; pdb.set_trace()
355
+ test_df.loc[test_df[col] == '?', col] = np.nan
356
+ for col in cat_columns:
357
+ test_df.loc[test_df[col] == '?', col] = 'nan'
358
+ for col in num_columns:
359
+ val_df.loc[val_df[col] == '?', col] = np.nan
360
+ for col in cat_columns:
361
+ val_df.loc[val_df[col] == '?', col] = 'nan'
362
+
363
+ if train_df.isna().any().any():
364
+ print("Training data contains nan in the numerical cols")
365
+ import pdb; pdb.set_trace()
366
+
367
+ X_num_train = train_df[num_columns].to_numpy().astype(np.float32)
368
+ X_cat_train = train_df[cat_columns].to_numpy()
369
+ y_train = train_df[target_columns].to_numpy()
370
+
371
+ X_num_test = test_df[num_columns].to_numpy().astype(np.float32)
372
+ X_cat_test = test_df[cat_columns].to_numpy()
373
+ y_test = test_df[target_columns].to_numpy()
374
+
375
+ X_num_val = val_df[num_columns].to_numpy().astype(np.float32)
376
+ X_cat_val = val_df[cat_columns].to_numpy()
377
+ y_val = val_df[target_columns].to_numpy()
378
+
379
+ save_dir = f'data/{name}'
380
+ np.save(f'{save_dir}/X_num_train.npy', X_num_train)
381
+ np.save(f'{save_dir}/X_cat_train.npy', X_cat_train)
382
+ np.save(f'{save_dir}/y_train.npy', y_train)
383
+
384
+ np.save(f'{save_dir}/X_num_test.npy', X_num_test)
385
+ np.save(f'{save_dir}/X_cat_test.npy', X_cat_test)
386
+ np.save(f'{save_dir}/y_test.npy', y_test)
387
+
388
+ if has_val:
389
+ np.save(f'{save_dir}/X_num_val.npy', X_num_val)
390
+ np.save(f'{save_dir}/X_cat_val.npy', X_cat_val)
391
+ np.save(f'{save_dir}/y_val.npy', y_val)
392
+
393
+ train_df[num_columns] = train_df[num_columns].astype(np.float32)
394
+ test_df[num_columns] = test_df[num_columns].astype(np.float32)
395
+ val_df[num_columns] = val_df[num_columns].astype(np.float32)
396
+
397
+ train_df.to_csv(f'{save_dir}/train.csv', index = False)
398
+ test_df.to_csv(f'{save_dir}/test.csv', index = False)
399
+ if has_val:
400
+ val_df.to_csv(f'{save_dir}/val.csv', index = False)
401
+
402
+ if not os.path.exists(f'synthetic/{name}'):
403
+ os.makedirs(f'synthetic/{name}')
404
+
405
+ train_df.to_csv(f'synthetic/{name}/real.csv', index = False)
406
+ test_df.to_csv(f'synthetic/{name}/test.csv', index = False)
407
+
408
+ if has_val:
409
+ val_df.to_csv(f'synthetic/{name}/val.csv', index = False)
410
+
411
+ print('Numerical', X_num_train.shape)
412
+ print('Categorical', X_cat_train.shape)
413
+
414
+ info['column_names'] = column_names
415
+ info['train_num'] = train_df.shape[0]
416
+ info['test_num'] = test_df.shape[0]
417
+ info['val_num'] = val_df.shape[0]
418
+
419
+ info['idx_mapping'] = idx_mapping
420
+ info['inverse_idx_mapping'] = inverse_idx_mapping
421
+ info['idx_name_mapping'] = idx_name_mapping
422
+
423
+ metadata = {'columns': {}}
424
+ task_type = info['task_type']
425
+ num_col_idx = info['num_col_idx']
426
+ cat_col_idx = info['cat_col_idx']
427
+ target_col_idx = info['target_col_idx']
428
+
429
+ for i in num_col_idx:
430
+ metadata['columns'][i] = {}
431
+ metadata['columns'][i]['sdtype'] = 'numerical'
432
+ metadata['columns'][i]['computer_representation'] = 'Float'
433
+
434
+ for i in cat_col_idx:
435
+ metadata['columns'][i] = {}
436
+ metadata['columns'][i]['sdtype'] = 'categorical'
437
+
438
+ if task_type == 'regression':
439
+
440
+ for i in target_col_idx:
441
+ metadata['columns'][i] = {}
442
+ metadata['columns'][i]['sdtype'] = 'numerical'
443
+ metadata['columns'][i]['computer_representation'] = 'Float'
444
+
445
+ else:
446
+ for i in target_col_idx:
447
+ metadata['columns'][i] = {}
448
+ metadata['columns'][i]['sdtype'] = 'categorical'
449
+
450
+ info['metadata'] = metadata
451
+
452
+ with open(f'{save_dir}/info.json', 'w') as file:
453
+ json.dump(info, file, indent=4)
454
+
455
+ print(f'Processing and Saving {name} Successfully!')
456
+
457
+ print(name)
458
+ print('Total', info['train_num'] + info['test_num'])
459
+ print('Train', info['train_num'])
460
+ print('Val', info['val_num'])
461
+ print('Test', info['test_num'])
462
+ if info['task_type'] == 'regression':
463
+ num = len(info['num_col_idx'] + info['target_col_idx'])
464
+ cat = len(info['cat_col_idx'])
465
+ else:
466
+ cat = len(info['cat_col_idx'] + info['target_col_idx'])
467
+ num = len(info['num_col_idx'])
468
+ print('Num', num)
469
+ print('Int', len(info['int_col_idx']))
470
+ print('Cat', cat)
471
+
472
+ if __name__ == "__main__":
473
+
474
+ if args.dataname:
475
+ process_data(args.dataname)
476
+ else:
477
+ for name in [
478
+ 'adult',
479
+ 'default',
480
+ 'shoppers',
481
+ 'magic',
482
+ 'beijing',
483
+ 'news',
484
+ 'news_nocat',
485
+ 'adult_dcr',
486
+ 'default_dcr',
487
+ 'shoppers_dcr',
488
+ 'beijing_dcr',
489
+ 'news_dcr',
490
+ ]:
491
+ process_data(name)
492
+
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/pyproject.toml ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bc2d5c09fdbd3457c0f7cdd1a92c8e44ea3b2ff1316a2b718865fb7e8059da36
3
+ size 1029
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/src/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from icecream import install
3
+
4
+ torch.set_num_threads(1)
5
+ install()
6
+
7
+ from . import env # noqa
8
+ from .data import * # noqa
9
+ from .env import * # noqa
10
+ from .metrics import * # noqa
11
+ from .util import * # noqa
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/src/data.py ADDED
@@ -0,0 +1,780 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ from collections import Counter
3
+ from copy import deepcopy
4
+ from dataclasses import astuple, dataclass, replace
5
+ from importlib.resources import path
6
+ from pathlib import Path
7
+ from typing import Any, Literal, Optional, Union, cast, Tuple, Dict, List
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+ from sklearn.model_selection import train_test_split
12
+ from sklearn.pipeline import make_pipeline
13
+ import sklearn.preprocessing
14
+ import torch
15
+ import os
16
+ from category_encoders import LeaveOneOutEncoder
17
+ from sklearn.impute import SimpleImputer
18
+ from sklearn.preprocessing import StandardScaler
19
+ from scipy.spatial.distance import cdist
20
+
21
+ from . import env, util
22
+ from .metrics import calculate_metrics as calculate_metrics_
23
+ from .util import TaskType, load_json
24
+
25
+ ArrayDict = Dict[str, np.ndarray]
26
+ TensorDict = Dict[str, torch.Tensor]
27
+
28
+
29
+ CAT_MISSING_VALUE = 'nan'
30
+ CAT_RARE_VALUE = '__rare__'
31
+ Normalization = Literal['standard', 'quantile', 'minmax']
32
+ NumNanPolicy = Literal['drop-rows', 'mean']
33
+ CatNanPolicy = Literal['most_frequent']
34
+ CatEncoding = Literal['one-hot', 'counter']
35
+ YPolicy = Literal['default']
36
+ DEQUANT_DIST = Literal['uniform', 'beta', 'round', 'none']
37
+
38
+
39
+ class StandardScaler1d(StandardScaler):
40
+ def partial_fit(self, X, *args, **kwargs):
41
+ assert X.ndim == 1
42
+ return super().partial_fit(X[:, None], *args, **kwargs)
43
+
44
+ def transform(self, X, *args, **kwargs):
45
+ assert X.ndim == 1
46
+ return super().transform(X[:, None], *args, **kwargs).squeeze(1)
47
+
48
+ def inverse_transform(self, X, *args, **kwargs):
49
+ assert X.ndim == 1
50
+ return super().inverse_transform(X[:, None], *args, **kwargs).squeeze(1)
51
+
52
+
53
+ def get_category_sizes(X: Union[torch.Tensor, np.ndarray]) -> List[int]:
54
+ XT = X.T.cpu().tolist() if isinstance(X, torch.Tensor) else X.T.tolist()
55
+ return [len(set(x)) for x in XT]
56
+
57
+
58
+ @dataclass(frozen=False)
59
+ class Dataset:
60
+ X_num: Optional[ArrayDict]
61
+ X_cat: Optional[ArrayDict]
62
+ y: ArrayDict
63
+ int_col_idx_wrt_num: list
64
+ y_info: Dict[str, Any]
65
+ task_type: TaskType
66
+ n_classes: Optional[int]
67
+
68
+ @classmethod
69
+ def from_dir(cls, dir_: Union[Path, str]) -> 'Dataset':
70
+ dir_ = Path(dir_)
71
+ splits = [k for k in ['train', 'test'] if dir_.joinpath(f'y_{k}.npy').exists()]
72
+
73
+ def load(item) -> ArrayDict:
74
+ return {
75
+ x: cast(np.ndarray, np.load(dir_ / f'{item}_{x}.npy', allow_pickle=True)) # type: ignore[code]
76
+ for x in splits
77
+ }
78
+
79
+ if Path(dir_ / 'info.json').exists():
80
+ info = util.load_json(dir_ / 'info.json')
81
+ else:
82
+ info = None
83
+ return Dataset(
84
+ load('X_num') if dir_.joinpath('X_num_train.npy').exists() else None,
85
+ load('X_cat') if dir_.joinpath('X_cat_train.npy').exists() else None,
86
+ load('y'),
87
+ {},
88
+ TaskType(info['task_type']),
89
+ info.get('n_classes'),
90
+ )
91
+
92
+ @property
93
+ def is_binclass(self) -> bool:
94
+ return self.task_type == TaskType.BINCLASS
95
+
96
+ @property
97
+ def is_multiclass(self) -> bool:
98
+ return self.task_type == TaskType.MULTICLASS
99
+
100
+ @property
101
+ def is_regression(self) -> bool:
102
+ return self.task_type == TaskType.REGRESSION
103
+
104
+ @property
105
+ def n_num_features(self) -> int:
106
+ return 0 if self.X_num is None else self.X_num['train'].shape[1]
107
+
108
+ @property
109
+ def n_cat_features(self) -> int:
110
+ return 0 if self.X_cat is None else self.X_cat['train'].shape[1]
111
+
112
+ @property
113
+ def n_features(self) -> int:
114
+ return self.n_num_features + self.n_cat_features
115
+
116
+ def size(self, part: Optional[str]) -> int:
117
+ return sum(map(len, self.y.values())) if part is None else len(self.y[part])
118
+
119
+ @property
120
+ def nn_output_dim(self) -> int:
121
+ if self.is_multiclass:
122
+ assert self.n_classes is not None
123
+ return self.n_classes
124
+ else:
125
+ return 1
126
+
127
+ def get_category_sizes(self, part: str) -> List[int]:
128
+ return [] if self.X_cat is None else get_category_sizes(self.X_cat[part])
129
+
130
+ def calculate_metrics(
131
+ self,
132
+ predictions: Dict[str, np.ndarray],
133
+ prediction_type: Optional[str],
134
+ ) -> Dict[str, Any]:
135
+ metrics = {
136
+ x: calculate_metrics_(
137
+ self.y[x], predictions[x], self.task_type, prediction_type, self.y_info
138
+ )
139
+ for x in predictions
140
+ }
141
+ if self.task_type == TaskType.REGRESSION:
142
+ score_key = 'rmse'
143
+ score_sign = -1
144
+ else:
145
+ score_key = 'accuracy'
146
+ score_sign = 1
147
+ for part_metrics in metrics.values():
148
+ part_metrics['score'] = score_sign * part_metrics[score_key]
149
+ return metrics
150
+
151
+ def change_val(dataset: Dataset, val_size: float = 0.2):
152
+ # should be done before transformations
153
+
154
+ y = np.concatenate([dataset.y['train'], dataset.y['val']], axis=0)
155
+
156
+ ixs = np.arange(y.shape[0])
157
+ if dataset.is_regression:
158
+ train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777)
159
+ else:
160
+ train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777, stratify=y)
161
+
162
+ dataset.y['train'] = y[train_ixs]
163
+ dataset.y['val'] = y[val_ixs]
164
+
165
+ if dataset.X_num is not None:
166
+ X_num = np.concatenate([dataset.X_num['train'], dataset.X_num['val']], axis=0)
167
+ dataset.X_num['train'] = X_num[train_ixs]
168
+ dataset.X_num['val'] = X_num[val_ixs]
169
+
170
+ if dataset.X_cat is not None:
171
+ X_cat = np.concatenate([dataset.X_cat['train'], dataset.X_cat['val']], axis=0)
172
+ dataset.X_cat['train'] = X_cat[train_ixs]
173
+ dataset.X_cat['val'] = X_cat[val_ixs]
174
+
175
+ return dataset
176
+
177
+ def num_process_nans(dataset: Dataset, policy: Optional[NumNanPolicy]) -> Dataset:
178
+
179
+ assert dataset.X_num is not None
180
+ nan_masks = {k: np.isnan(v) for k, v in dataset.X_num.items()}
181
+ if not any(x.any() for x in nan_masks.values()): # type: ignore[code]
182
+ # assert policy is None
183
+ print('No NaNs in numerical features, skipping')
184
+ return dataset
185
+
186
+ assert policy is not None
187
+ if policy == 'drop-rows':
188
+ valid_masks = {k: ~v.any(1) for k, v in nan_masks.items()}
189
+ assert valid_masks[
190
+ 'test'
191
+ ].all(), 'Cannot drop test rows, since this will affect the final metrics.'
192
+ new_data = {}
193
+ for data_name in ['X_num', 'X_cat', 'y']:
194
+ data_dict = getattr(dataset, data_name)
195
+ if data_dict is not None:
196
+ new_data[data_name] = {
197
+ k: v[valid_masks[k]] for k, v in data_dict.items()
198
+ }
199
+ dataset = replace(dataset, **new_data)
200
+ elif policy == 'mean':
201
+ new_values = np.nanmean(dataset.X_num['train'], axis=0)
202
+ X_num = deepcopy(dataset.X_num)
203
+ for k, v in X_num.items():
204
+ num_nan_indices = np.where(nan_masks[k])
205
+ v[num_nan_indices] = np.take(new_values, num_nan_indices[1])
206
+ dataset = replace(dataset, X_num=X_num)
207
+ else:
208
+ assert util.raise_unknown('policy', policy)
209
+ return dataset
210
+
211
+
212
+ # Inspired by: https://github.com/yandex-research/rtdl/blob/a4c93a32b334ef55d2a0559a4407c8306ffeeaee/lib/data.py#L20
213
+ def normalize(
214
+ X: ArrayDict, normalization: Normalization, seed: Optional[int], return_normalizer : bool = False
215
+ ) -> ArrayDict:
216
+ X_train = X['train']
217
+ if normalization == 'standard':
218
+ normalizer = sklearn.preprocessing.StandardScaler()
219
+ elif normalization == 'minmax':
220
+ normalizer = sklearn.preprocessing.MinMaxScaler()
221
+ elif normalization == 'quantile':
222
+ normalizer = sklearn.preprocessing.QuantileTransformer(
223
+ output_distribution='normal',
224
+ n_quantiles=max(min(X['train'].shape[0] // 30, 1000), 10),
225
+ subsample=int(1e9),
226
+ random_state=seed,
227
+ )
228
+ # noise = 1e-3
229
+ # if noise > 0:
230
+ # assert seed is not None
231
+ # stds = np.std(X_train, axis=0, keepdims=True)
232
+ # noise_std = noise / np.maximum(stds, noise) # type: ignore[code]
233
+ # X_train = X_train + noise_std * np.random.default_rng(seed).standard_normal(
234
+ # X_train.shape
235
+ # )
236
+ else:
237
+ util.raise_unknown('normalization', normalization)
238
+
239
+ normalizer.fit(X_train)
240
+ if return_normalizer:
241
+ return {k: normalizer.transform(v) for k, v in X.items()}, normalizer
242
+ return {k: normalizer.transform(v) for k, v in X.items()}
243
+
244
+ class dequantizer:
245
+ def __init__(
246
+ self,
247
+ dequant_dist: DEQUANT_DIST,
248
+ int_col_idx_wrt_num: list,
249
+ int_dequant_factor: float,
250
+ # return_dequantizer: bool = False
251
+ ):
252
+ self.dequant_dist = dequant_dist
253
+ self.int_col_idx_wrt_num = int_col_idx_wrt_num
254
+ self.int_dequant_factor = int_dequant_factor
255
+ def transform(self, X):
256
+ X_int = X[:, self.int_col_idx_wrt_num]
257
+ if self.dequant_dist == 'uniform':
258
+ X[:, self.int_col_idx_wrt_num] = X_int+ np.random.uniform(size=X_int.shape) * self.int_dequant_factor
259
+ elif self.dequant_dist == 'beta':
260
+ X[:, self.int_col_idx_wrt_num] = X_int + np.random.beta(self.int_dequant_factor, self.int_dequant_factor, size=X_int.shape) - 0.5
261
+ elif self.dequant_dist in ['round', 'none']:
262
+ pass
263
+ return X
264
+ def inverse_transform(self, X):
265
+ X_int = X[:, self.int_col_idx_wrt_num]
266
+ if self.dequant_dist == 'uniform':
267
+ X[:, self.int_col_idx_wrt_num] = np.floor(X_int)
268
+ elif self.dequant_dist == 'beta':
269
+ X[:, self.int_col_idx_wrt_num] = np.rint(X_int)
270
+ elif self.dequant_dist == 'round':
271
+ X[:, self.int_col_idx_wrt_num] = np.rint(X_int)
272
+ elif self.dequant_dist == 'none':
273
+ pass
274
+ return X
275
+
276
+
277
+ # if return_dequantizer:
278
+ # return {k: transform(v) for k, v in X.items()}, inverse_transform
279
+ # return {k: transform(v) for k, v in X.items()}
280
+
281
+ def cat_process_nans(X: ArrayDict, policy: Optional[CatNanPolicy]) -> ArrayDict:
282
+ assert X is not None
283
+ nan_masks = {k: v == CAT_MISSING_VALUE for k, v in X.items()}
284
+ if any(x.any() for x in nan_masks.values()): # type: ignore[code]
285
+ if policy is None:
286
+ X_new = X
287
+ elif policy == 'most_frequent':
288
+ imputer = SimpleImputer(missing_values=CAT_MISSING_VALUE, strategy=policy) # type: ignore[code]
289
+ imputer.fit(X['train'])
290
+ X_new = {k: cast(np.ndarray, imputer.transform(v)) for k, v in X.items()}
291
+ else:
292
+ util.raise_unknown('categorical NaN policy', policy)
293
+ else:
294
+ assert policy is None
295
+ X_new = X
296
+ return X_new
297
+
298
+
299
+ def cat_drop_rare(X: ArrayDict, min_frequency: float) -> ArrayDict:
300
+ assert 0.0 < min_frequency < 1.0
301
+ min_count = round(len(X['train']) * min_frequency)
302
+ X_new = {x: [] for x in X}
303
+ for column_idx in range(X['train'].shape[1]):
304
+ counter = Counter(X['train'][:, column_idx].tolist())
305
+ popular_categories = {k for k, v in counter.items() if v >= min_count}
306
+ for part in X_new:
307
+ X_new[part].append(
308
+ [
309
+ (x if x in popular_categories else CAT_RARE_VALUE)
310
+ for x in X[part][:, column_idx].tolist()
311
+ ]
312
+ )
313
+ return {k: np.array(v).T for k, v in X_new.items()}
314
+
315
+
316
+ def cat_encode(
317
+ X: ArrayDict,
318
+ encoding: Optional[CatEncoding],
319
+ y_train: Optional[np.ndarray],
320
+ seed: Optional[int],
321
+ return_encoder : bool = False
322
+ ) -> Tuple[ArrayDict, bool, Optional[Any]]: # (X, is_converted_to_numerical)
323
+ if encoding != 'counter':
324
+ y_train = None
325
+
326
+ # Step 1. Map strings to 0-based ranges
327
+
328
+ if encoding is None:
329
+ unknown_value = np.iinfo('int64').max - 3
330
+ oe = sklearn.preprocessing.OrdinalEncoder(
331
+ handle_unknown='use_encoded_value', # type: ignore[code]
332
+ unknown_value=unknown_value, # type: ignore[code]
333
+ dtype='int64', # type: ignore[code]
334
+ ).fit(X['train'])
335
+ encoder = make_pipeline(oe)
336
+ encoder.fit(X['train'])
337
+ X = {k: encoder.transform(v) for k, v in X.items()}
338
+ max_values = X['train'].max(axis=0)
339
+ for part in X.keys():
340
+ if part == 'train': continue
341
+ for column_idx in range(X[part].shape[1]):
342
+ X[part][X[part][:, column_idx] == unknown_value, column_idx] = (
343
+ max_values[column_idx] + 1
344
+ )
345
+ if return_encoder:
346
+ return (X, False, encoder)
347
+ return (X, False)
348
+
349
+ # Step 2. Encode.
350
+
351
+ elif encoding == 'one-hot':
352
+ ohe = sklearn.preprocessing.OneHotEncoder(
353
+ handle_unknown='ignore', sparse_output=False, dtype=np.float32 # type: ignore[code]
354
+ )
355
+ encoder = make_pipeline(ohe)
356
+
357
+ # encoder.steps.append(('ohe', ohe))
358
+ encoder.fit(X['train'])
359
+ X = {k: encoder.transform(v) for k, v in X.items()}
360
+
361
+ elif encoding == 'counter':
362
+ assert y_train is not None
363
+ assert seed is not None
364
+ loe = LeaveOneOutEncoder(sigma=0.1, random_state=seed, return_df=False)
365
+ encoder.steps.append(('loe', loe))
366
+ encoder.fit(X['train'], y_train)
367
+ X = {k: encoder.transform(v).astype('float32') for k, v in X.items()} # type: ignore[code]
368
+ if not isinstance(X['train'], pd.DataFrame):
369
+ X = {k: v.values for k, v in X.items()} # type: ignore[code]
370
+ else:
371
+ util.raise_unknown('encoding', encoding)
372
+
373
+ if return_encoder:
374
+ return X, True, encoder # type: ignore[code]
375
+ return (X, True)
376
+
377
+
378
+ def build_target(
379
+ y: ArrayDict, policy: Optional[YPolicy], task_type: TaskType
380
+ ) -> Tuple[ArrayDict, Dict[str, Any]]:
381
+ info: Dict[str, Any] = {'policy': policy}
382
+ if policy is None:
383
+ pass
384
+ elif policy == 'default':
385
+ if task_type == TaskType.REGRESSION:
386
+ mean, std = float(y['train'].mean()), float(y['train'].std())
387
+ y = {k: (v - mean) / std for k, v in y.items()}
388
+ info['mean'] = mean
389
+ info['std'] = std
390
+ else:
391
+ util.raise_unknown('policy', policy)
392
+ return y, info
393
+
394
+
395
+ @dataclass(frozen=True)
396
+ class Transformations:
397
+ seed: int = 0
398
+ normalization: Optional[Normalization] = None
399
+ num_nan_policy: Optional[NumNanPolicy] = None
400
+ cat_nan_policy: Optional[CatNanPolicy] = None
401
+ cat_min_frequency: Optional[float] = None
402
+ cat_encoding: Optional[CatEncoding] = None
403
+ y_policy: Optional[YPolicy] = 'default'
404
+ dequant_dist: Optional[DEQUANT_DIST] = None
405
+ int_dequant_factor: Optional[float] = 0.0
406
+
407
+
408
+ def transform_dataset(
409
+ dataset: Dataset,
410
+ transformations: Transformations,
411
+ cache_dir: Optional[Path],
412
+ return_transforms: bool = False
413
+ ) -> Dataset:
414
+ # WARNING: the order of transformations matters. Moreover, the current
415
+ # implementation is not ideal in that sense.
416
+ if cache_dir is not None:
417
+ transformations_md5 = hashlib.md5(
418
+ str(transformations).encode('utf-8')
419
+ ).hexdigest()
420
+ transformations_str = '__'.join(map(str, astuple(transformations)))
421
+ cache_path = (
422
+ cache_dir / f'cache__{transformations_str}__{transformations_md5}.pickle'
423
+ )
424
+ if cache_path.exists():
425
+ cache_transformations, value = util.load_pickle(cache_path)
426
+ if transformations == cache_transformations:
427
+ print(
428
+ f"Using cached features: {cache_dir.name + '/' + cache_path.name}"
429
+ )
430
+ return value
431
+ else:
432
+ raise RuntimeError(f'Hash collision for {cache_path}')
433
+ else:
434
+ cache_path = None
435
+
436
+ if dataset.X_num is not None:
437
+ dataset = num_process_nans(dataset, transformations.num_nan_policy)
438
+
439
+ num_transform = None
440
+ int_transform = None
441
+ cat_transform = None
442
+ X_num = dataset.X_num
443
+
444
+ int_col_idx_wrt_num = dataset.int_col_idx_wrt_num
445
+ if X_num is not None and int_col_idx_wrt_num and transformations.dequant_dist is not None:
446
+ int_transform = dequantizer(
447
+ transformations.dequant_dist,
448
+ int_col_idx_wrt_num,
449
+ transformations.int_dequant_factor,
450
+ )
451
+ X_num = {k: int_transform.transform(v) for k, v in X_num.items()}
452
+
453
+ if X_num is not None and transformations.normalization is not None:
454
+ has_num = all([x.shape[1]>0 for x in dataset.X_num.values()])
455
+ if has_num:
456
+ X_num, num_transform = normalize(
457
+ X_num,
458
+ transformations.normalization,
459
+ transformations.seed,
460
+ return_normalizer=True
461
+ )
462
+ num_transform = num_transform
463
+
464
+ if dataset.X_cat is None:
465
+ assert transformations.cat_nan_policy is None
466
+ assert transformations.cat_min_frequency is None
467
+ # assert transformations.cat_encoding is None
468
+ X_cat = None
469
+ else:
470
+ has_cat = all([x.shape[1]>0 for x in dataset.X_cat.values()])
471
+ if not has_cat:
472
+ assert transformations.cat_nan_policy is None
473
+ assert transformations.cat_min_frequency is None
474
+ X_cat = dataset.X_cat
475
+ for split in X_cat.keys(): # a patch to make sure that the empty array is transformed into int dtype
476
+ X_cat[split] = X_cat[split].astype(np.int64)
477
+ else:
478
+ X_cat = cat_process_nans(dataset.X_cat, transformations.cat_nan_policy)
479
+
480
+ if transformations.cat_min_frequency is not None:
481
+ X_cat = cat_drop_rare(X_cat, transformations.cat_min_frequency)
482
+ X_cat, is_num, cat_transform = cat_encode(
483
+ X_cat,
484
+ transformations.cat_encoding,
485
+ dataset.y['train'],
486
+ transformations.seed,
487
+ return_encoder=True
488
+ )
489
+
490
+ if is_num:
491
+ X_num = (
492
+ X_cat
493
+ if X_num is None
494
+ else {x: np.hstack([X_num[x], X_cat[x]]) for x in X_num}
495
+ )
496
+ X_cat = None
497
+
498
+
499
+ y, y_info = build_target(dataset.y, transformations.y_policy, dataset.task_type)
500
+
501
+ dataset = replace(dataset, X_num=X_num, X_cat=X_cat, y=y, y_info=y_info)
502
+ dataset.num_transform = num_transform
503
+ dataset.int_transform = int_transform
504
+ dataset.cat_transform = cat_transform
505
+
506
+ if cache_path is not None:
507
+ util.dump_pickle((transformations, dataset), cache_path)
508
+ # if return_transforms:
509
+ # return dataset, num_transform, cat_transform
510
+ return dataset
511
+
512
+
513
+ def build_dataset(
514
+ path: Union[str, Path],
515
+ transformations: Transformations,
516
+ cache: bool
517
+ ) -> Dataset:
518
+ path = Path(path)
519
+ dataset = Dataset.from_dir(path)
520
+ return transform_dataset(dataset, transformations, path if cache else None)
521
+
522
+
523
+ def prepare_tensors(
524
+ dataset: Dataset, device: Union[str, torch.device]
525
+ ) -> Tuple[Optional[TensorDict], Optional[TensorDict], TensorDict]:
526
+ X_num, X_cat, Y = (
527
+ None if x is None else {k: torch.as_tensor(v) for k, v in x.items()}
528
+ for x in [dataset.X_num, dataset.X_cat, dataset.y]
529
+ )
530
+ if device.type != 'cpu':
531
+ X_num, X_cat, Y = (
532
+ None if x is None else {k: v.to(device) for k, v in x.items()}
533
+ for x in [X_num, X_cat, Y]
534
+ )
535
+ assert X_num is not None
536
+ assert Y is not None
537
+ if not dataset.is_multiclass:
538
+ Y = {k: v.float() for k, v in Y.items()}
539
+ return X_num, X_cat, Y
540
+
541
+ ###############
542
+ ## DataLoader##
543
+ ###############
544
+
545
+ class TabDataset(torch.utils.data.Dataset):
546
+ def __init__(
547
+ self, dataset : Dataset, split : Literal['train', 'val', 'test']
548
+ ):
549
+ super().__init__()
550
+
551
+ self.X_num = torch.from_numpy(dataset.X_num[split]) if dataset.X_num is not None else None
552
+ self.X_cat = torch.from_numpy(dataset.X_cat[split]) if dataset.X_cat is not None else None
553
+ self.y = torch.from_numpy(dataset.y[split])
554
+
555
+ assert self.y is not None
556
+ assert self.X_num is not None or self.X_cat is not None
557
+
558
+ def __len__(self):
559
+ return len(self.y)
560
+
561
+ def __getitem__(self, idx):
562
+ out_dict = {
563
+ 'y': self.y[idx].long() if self.y is not None else None,
564
+ }
565
+
566
+ x = np.empty((0,))
567
+ if self.X_num is not None:
568
+ x = self.X_num[idx]
569
+ if self.X_cat is not None:
570
+ x = torch.cat([x, self.X_cat[idx]], dim=0)
571
+ return x.float(), out_dict
572
+
573
+ def prepare_dataloader(
574
+ dataset : Dataset,
575
+ split : str,
576
+ batch_size: int,
577
+ ):
578
+
579
+ torch_dataset = TabDataset(dataset, split)
580
+ loader = torch.utils.data.DataLoader(
581
+ torch_dataset,
582
+ batch_size=batch_size,
583
+ shuffle=(split == 'train'),
584
+ num_workers=1,
585
+ )
586
+ while True:
587
+ yield from loader
588
+
589
+ def prepare_torch_dataloader(
590
+ dataset : Dataset,
591
+ split : str,
592
+ shuffle : bool,
593
+ batch_size: int,
594
+ ) -> torch.utils.data.DataLoader:
595
+
596
+ torch_dataset = TabDataset(dataset, split)
597
+ loader = torch.utils.data.DataLoader(torch_dataset, batch_size=batch_size, shuffle=shuffle, num_workers=1)
598
+
599
+ return loader
600
+
601
+ def dataset_from_csv(paths : Dict[str, str], cat_features, target, T):
602
+ assert 'train' in paths
603
+ y = {}
604
+ X_num = {}
605
+ X_cat = {} if len(cat_features) else None
606
+ for split in paths.keys():
607
+ df = pd.read_csv(paths[split])
608
+ y[split] = df[target].to_numpy().astype(float)
609
+ if X_cat is not None:
610
+ X_cat[split] = df[cat_features].to_numpy().astype(str)
611
+ X_num[split] = df.drop(cat_features + [target], axis=1).to_numpy().astype(float)
612
+
613
+ dataset = Dataset(X_num, X_cat, y, {}, None, len(np.unique(y['train'])))
614
+ return transform_dataset(dataset, T, None)
615
+
616
+ class FastTensorDataLoader:
617
+ """
618
+ A DataLoader-like object for a set of tensors that can be much faster than
619
+ TensorDataset + DataLoader because dataloader grabs individual indices of
620
+ the dataset and calls cat (slow).
621
+ Source: https://discuss.pytorch.org/t/dataloader-much-slower-than-manual-batching/27014/6
622
+ """
623
+ def __init__(self, *tensors, batch_size=32, shuffle=False):
624
+ """
625
+ Initialize a FastTensorDataLoader.
626
+ :param *tensors: tensors to store. Must have the same length @ dim 0.
627
+ :param batch_size: batch size to load.
628
+ :param shuffle: if True, shuffle the data *in-place* whenever an
629
+ iterator is created out of this object.
630
+ :returns: A FastTensorDataLoader.
631
+ """
632
+ assert all(t.shape[0] == tensors[0].shape[0] for t in tensors)
633
+ self.tensors = tensors
634
+
635
+ self.dataset_len = self.tensors[0].shape[0]
636
+ self.batch_size = batch_size
637
+ self.shuffle = shuffle
638
+
639
+ # Calculate # batches
640
+ n_batches, remainder = divmod(self.dataset_len, self.batch_size)
641
+ if remainder > 0:
642
+ n_batches += 1
643
+ self.n_batches = n_batches
644
+ def __iter__(self):
645
+ if self.shuffle:
646
+ r = torch.randperm(self.dataset_len)
647
+ self.tensors = [t[r] for t in self.tensors]
648
+ self.i = 0
649
+ return self
650
+
651
+ def __next__(self):
652
+ if self.i >= self.dataset_len:
653
+ raise StopIteration
654
+ batch = tuple(t[self.i:self.i+self.batch_size] for t in self.tensors)
655
+ self.i += self.batch_size
656
+ return batch
657
+
658
+ def __len__(self):
659
+ return self.n_batches
660
+
661
+ def prepare_fast_dataloader(
662
+ D : Dataset,
663
+ split : str,
664
+ batch_size: int
665
+ ):
666
+
667
+ X = torch.from_numpy(np.concatenate([D.X_num[split], D.X_cat[split]], axis=1)).float()
668
+ dataloader = FastTensorDataLoader(X, batch_size=batch_size, shuffle=(split=='train'))
669
+ while True:
670
+ yield from dataloader
671
+
672
+ def prepare_fast_torch_dataloader(
673
+ D : Dataset,
674
+ split : str,
675
+ batch_size: int
676
+ ):
677
+ if D.X_cat is not None:
678
+ X = torch.from_numpy(np.concatenate([D.X_num[split], D.X_cat[split]], axis=1)).float()
679
+ else:
680
+ X = torch.from_numpy(D.X_num[split]).float()
681
+ y = torch.from_numpy(D.y[split])
682
+ dataloader = FastTensorDataLoader(X, y, batch_size=batch_size, shuffle=(split=='train'))
683
+ return dataloader
684
+
685
+ def round_columns(X_real, X_synth, columns):
686
+ for col in columns:
687
+ uniq = np.unique(X_real[:,col])
688
+ dist = cdist(X_synth[:, col][:, np.newaxis].astype(float), uniq[:, np.newaxis].astype(float))
689
+ X_synth[:, col] = uniq[dist.argmin(axis=1)]
690
+ return X_synth
691
+
692
+ def concat_features(D : Dataset):
693
+ if D.X_num is None:
694
+ assert D.X_cat is not None
695
+ X = {k: pd.DataFrame(v, columns=range(D.n_features)) for k, v in D.X_cat.items()}
696
+ elif D.X_cat is None:
697
+ assert D.X_num is not None
698
+ X = {k: pd.DataFrame(v, columns=range(D.n_features)) for k, v in D.X_num.items()}
699
+ else:
700
+ X = {
701
+ part: pd.concat(
702
+ [
703
+ pd.DataFrame(D.X_num[part], columns=range(D.n_num_features)),
704
+ pd.DataFrame(
705
+ D.X_cat[part],
706
+ columns=range(D.n_num_features, D.n_features),
707
+ ),
708
+ ],
709
+ axis=1,
710
+ )
711
+ for part in D.y.keys()
712
+ }
713
+
714
+ return X
715
+
716
+ def concat_to_pd(X_num, X_cat, y):
717
+ if X_num is None:
718
+ return pd.concat([
719
+ pd.DataFrame(X_cat, columns=list(range(X_cat.shape[1]))),
720
+ pd.DataFrame(y, columns=['y'])
721
+ ], axis=1)
722
+ if X_cat is not None:
723
+ return pd.concat([
724
+ pd.DataFrame(X_num, columns=list(range(X_num.shape[1]))),
725
+ pd.DataFrame(X_cat, columns=list(range(X_num.shape[1], X_num.shape[1] + X_cat.shape[1]))),
726
+ pd.DataFrame(y, columns=['y'])
727
+ ], axis=1)
728
+ return pd.concat([
729
+ pd.DataFrame(X_num, columns=list(range(X_num.shape[1]))),
730
+ pd.DataFrame(y, columns=['y'])
731
+ ], axis=1)
732
+
733
+ def read_pure_data(path, split='train'):
734
+ y = np.load(os.path.join(path, f'y_{split}.npy'), allow_pickle=True)
735
+ X_num = None
736
+ X_cat = None
737
+ if os.path.exists(os.path.join(path, f'X_num_{split}.npy')):
738
+ X_num = np.load(os.path.join(path, f'X_num_{split}.npy'), allow_pickle=True)
739
+ if os.path.exists(os.path.join(path, f'X_cat_{split}.npy')):
740
+ X_cat = np.load(os.path.join(path, f'X_cat_{split}.npy'), allow_pickle=True)
741
+
742
+ return X_num, X_cat, y
743
+
744
+ def read_changed_val(path, val_size=0.2):
745
+ path = Path(path)
746
+ X_num_train, X_cat_train, y_train = read_pure_data(path, 'train')
747
+ X_num_val, X_cat_val, y_val = read_pure_data(path, 'val')
748
+ is_regression = load_json(path / 'info.json')['task_type'] == 'regression'
749
+
750
+ y = np.concatenate([y_train, y_val], axis=0)
751
+
752
+ ixs = np.arange(y.shape[0])
753
+ if is_regression:
754
+ train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777)
755
+ else:
756
+ train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777, stratify=y)
757
+ y_train = y[train_ixs]
758
+ y_val = y[val_ixs]
759
+
760
+ if X_num_train is not None:
761
+ X_num = np.concatenate([X_num_train, X_num_val], axis=0)
762
+ X_num_train = X_num[train_ixs]
763
+ X_num_val = X_num[val_ixs]
764
+
765
+ if X_cat_train is not None:
766
+ X_cat = np.concatenate([X_cat_train, X_cat_val], axis=0)
767
+ X_cat_train = X_cat[train_ixs]
768
+ X_cat_val = X_cat[val_ixs]
769
+
770
+ return X_num_train, X_cat_train, y_train, X_num_val, X_cat_val, y_val
771
+
772
+ #############
773
+
774
+ def load_dataset_info(dataset_dir_name: str) -> Dict[str, Any]:
775
+ path = Path("data/" + dataset_dir_name)
776
+ info = util.load_json(path / 'info.json')
777
+ info['size'] = info['train_size'] + info['val_size'] + info['test_size']
778
+ info['n_features'] = info['n_num_features'] + info['n_cat_features']
779
+ info['path'] = path
780
+ return info
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/src/env.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Have not used in TabDDPM project.
3
+ """
4
+
5
+ import datetime
6
+ import os
7
+ import shutil
8
+ import typing as ty
9
+ from pathlib import Path
10
+
11
+ PROJ = Path('tab-ddpm/').absolute().resolve()
12
+ EXP = PROJ / 'exp'
13
+ DATA = PROJ / 'data'
14
+
15
+
16
+ def get_path(path: ty.Union[str, Path]) -> Path:
17
+ if isinstance(path, str):
18
+ path = Path(path)
19
+ if not path.is_absolute():
20
+ path = PROJ / path
21
+ return path.resolve()
22
+
23
+
24
+ def get_relative_path(path: ty.Union[str, Path]) -> Path:
25
+ return get_path(path).relative_to(PROJ)
26
+
27
+
28
+ def duplicate_path(
29
+ src: ty.Union[str, Path], alternative_project_dir: ty.Union[str, Path]
30
+ ) -> None:
31
+ src = get_path(src)
32
+ alternative_project_dir = get_path(alternative_project_dir)
33
+ dst = alternative_project_dir / src.relative_to(PROJ)
34
+ dst.parent.mkdir(parents=True, exist_ok=True)
35
+ if dst.exists():
36
+ dst = dst.with_name(
37
+ dst.name + '_' + datetime.datetime.now().strftime('%Y%m%dT%H%M%S')
38
+ )
39
+ (shutil.copytree if src.is_dir() else shutil.copyfile)(src, dst)
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/src/metrics.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import enum
2
+ from typing import Any, Optional, Tuple, Dict, Union, cast
3
+ from functools import partial
4
+
5
+ import numpy as np
6
+ import scipy.special
7
+ import sklearn.metrics as skm
8
+
9
+ from . import util
10
+ from .util import TaskType
11
+
12
+
13
+ class PredictionType(enum.Enum):
14
+ LOGITS = 'logits'
15
+ PROBS = 'probs'
16
+
17
+ class MetricsReport:
18
+ def __init__(self, report: dict, task_type: TaskType):
19
+ self._res = {k: {} for k in report.keys()}
20
+ if task_type in (TaskType.BINCLASS, TaskType.MULTICLASS):
21
+ self._metrics_names = ["acc", "f1"]
22
+ for k in report.keys():
23
+ self._res[k]["acc"] = report[k]["accuracy"]
24
+ self._res[k]["f1"] = report[k]["macro avg"]["f1-score"]
25
+ if task_type == TaskType.BINCLASS:
26
+ self._res[k]["roc_auc"] = report[k]["roc_auc"]
27
+ self._metrics_names.append("roc_auc")
28
+
29
+ elif task_type == TaskType.REGRESSION:
30
+ self._metrics_names = ["r2", "rmse"]
31
+ for k in report.keys():
32
+ self._res[k]["r2"] = report[k]["r2"]
33
+ self._res[k]["rmse"] = report[k]["rmse"]
34
+ else:
35
+ raise "Unknown TaskType!"
36
+
37
+ def get_splits_names(self) -> list[str]:
38
+ return self._res.keys()
39
+
40
+ def get_metrics_names(self) -> list[str]:
41
+ return self._metrics_names
42
+
43
+ def get_metric(self, split: str, metric: str) -> float:
44
+ return self._res[split][metric]
45
+
46
+ def get_val_score(self) -> float:
47
+ return self._res["val"]["r2"] if "r2" in self._res["val"] else self._res["val"]["f1"]
48
+
49
+ def get_test_score(self) -> float:
50
+ return self._res["test"]["r2"] if "r2" in self._res["test"] else self._res["test"]["f1"]
51
+
52
+ def print_metrics(self) -> None:
53
+ res = {
54
+ "val": {k: np.around(self._res["val"][k], 4) for k in self._res["val"]},
55
+ "test": {k: np.around(self._res["test"][k], 4) for k in self._res["test"]}
56
+ }
57
+
58
+ print("*"*100)
59
+ print("[val]")
60
+ print(res["val"])
61
+ print("[test]")
62
+ print(res["test"])
63
+
64
+ return res
65
+
66
+ class SeedsMetricsReport:
67
+ def __init__(self):
68
+ self._reports = []
69
+
70
+ def add_report(self, report: MetricsReport) -> None:
71
+ self._reports.append(report)
72
+
73
+ def get_mean_std(self) -> dict:
74
+ res = {k: {} for k in ["train", "val", "test"]}
75
+ for split in self._reports[0].get_splits_names():
76
+ for metric in self._reports[0].get_metrics_names():
77
+ res[split][metric] = [x.get_metric(split, metric) for x in self._reports]
78
+
79
+ agg_res = {k: {} for k in ["train", "val", "test"]}
80
+ for split in self._reports[0].get_splits_names():
81
+ for metric in self._reports[0].get_metrics_names():
82
+ for k, f in [("count", len), ("mean", np.mean), ("std", np.std)]:
83
+ agg_res[split][f"{metric}-{k}"] = f(res[split][metric])
84
+ self._res = res
85
+ self._agg_res = agg_res
86
+
87
+ return agg_res
88
+
89
+ def print_result(self) -> dict:
90
+ res = {split: {k: float(np.around(self._agg_res[split][k], 4)) for k in self._agg_res[split]} for split in ["val", "test"]}
91
+ print("="*100)
92
+ print("EVAL RESULTS:")
93
+ print("[val]")
94
+ print(res["val"])
95
+ print("[test]")
96
+ print(res["test"])
97
+ print("="*100)
98
+ return res
99
+
100
+ def calculate_rmse(
101
+ y_true: np.ndarray, y_pred: np.ndarray, std = None) -> float:
102
+ rmse = skm.mean_squared_error(y_true, y_pred) ** 0.5
103
+ if std is not None:
104
+ rmse *= std
105
+ return rmse
106
+
107
+
108
+ def _get_labels_and_probs(
109
+ y_pred: np.ndarray, task_type: TaskType, prediction_type: Optional[PredictionType]
110
+ ) -> Tuple[np.ndarray, Optional[np.ndarray]]:
111
+ assert task_type in (TaskType.BINCLASS, TaskType.MULTICLASS)
112
+
113
+ if prediction_type is None:
114
+ return y_pred, None
115
+
116
+ if prediction_type == PredictionType.LOGITS:
117
+ probs = (
118
+ scipy.special.expit(y_pred)
119
+ if task_type == TaskType.BINCLASS
120
+ else scipy.special.softmax(y_pred, axis=1)
121
+ )
122
+ elif prediction_type == PredictionType.PROBS:
123
+ probs = y_pred
124
+ else:
125
+ util.raise_unknown('prediction_type', prediction_type)
126
+
127
+ assert probs is not None
128
+ labels = np.round(probs) if task_type == TaskType.BINCLASS else probs.argmax(axis=1)
129
+ return labels.astype('int64'), probs
130
+
131
+
132
+ def calculate_metrics(
133
+ y_true: np.ndarray,
134
+ y_pred: np.ndarray,
135
+ task_type: Union[str, TaskType],
136
+ prediction_type: Optional[Union[str, PredictionType]],
137
+ y_info: Dict[str, Any],
138
+ ) -> Dict[str, Any]:
139
+ # Example: calculate_metrics(y_true, y_pred, 'binclass', 'logits', {})
140
+ task_type = TaskType(task_type)
141
+ if prediction_type is not None:
142
+ prediction_type = PredictionType(prediction_type)
143
+
144
+ if task_type == TaskType.REGRESSION:
145
+ assert prediction_type is None
146
+ assert 'std' in y_info
147
+ rmse = calculate_rmse(y_true, y_pred, y_info['std'])
148
+ r2 = skm.r2_score(y_true, y_pred)
149
+ result = {'rmse': rmse, 'r2': r2}
150
+ else:
151
+ labels, probs = _get_labels_and_probs(y_pred, task_type, prediction_type)
152
+ result = cast(
153
+ Dict[str, Any], skm.classification_report(y_true, labels, output_dict=True)
154
+ )
155
+ if task_type == TaskType.BINCLASS:
156
+ result['roc_auc'] = skm.roc_auc_score(y_true, probs)
157
+ return result
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/src/util.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import atexit
3
+ import enum
4
+ import json
5
+ import os
6
+ import pickle
7
+ import shutil
8
+ import sys
9
+ import time
10
+ import uuid
11
+ from copy import deepcopy
12
+ from dataclasses import asdict, fields, is_dataclass
13
+ from pathlib import Path
14
+ from pprint import pprint
15
+ from typing import Any, Callable, List, Dict, Type, Optional, Tuple, TypeVar, Union, cast, get_args, get_origin
16
+
17
+ import __main__
18
+ import numpy as np
19
+ import tomli
20
+ import tomli_w
21
+ import torch
22
+ import typing as ty
23
+
24
+ from . import env
25
+
26
+ RawConfig = Dict[str, Any]
27
+ Report = Dict[str, Any]
28
+ T = TypeVar('T')
29
+
30
+
31
+ class Part(enum.Enum):
32
+ TRAIN = 'train'
33
+ VAL = 'val'
34
+ TEST = 'test'
35
+
36
+ def __str__(self) -> str:
37
+ return self.value
38
+
39
+
40
+ class TaskType(enum.Enum):
41
+ BINCLASS = 'binclass'
42
+ MULTICLASS = 'multiclass'
43
+ REGRESSION = 'regression'
44
+
45
+ def __str__(self) -> str:
46
+ return self.value
47
+
48
+
49
+
50
+ def update_training_log(training_log, data, metrics):
51
+ def _update(log_part, data_part):
52
+ for k, v in data_part.items():
53
+ if isinstance(v, dict):
54
+ _update(log_part.setdefault(k, {}), v)
55
+ elif isinstance(v, list):
56
+ log_part.setdefault(k, []).extend(v)
57
+ else:
58
+ log_part.setdefault(k, []).append(v)
59
+
60
+ _update(training_log, data)
61
+ transposed_metrics = {}
62
+ for part, part_metrics in metrics.items():
63
+ for metric_name, value in part_metrics.items():
64
+ transposed_metrics.setdefault(metric_name, {})[part] = value
65
+ _update(training_log, transposed_metrics)
66
+
67
+
68
+ def raise_unknown(unknown_what: str, unknown_value: Any):
69
+ raise ValueError(f'Unknown {unknown_what}: {unknown_value}')
70
+
71
+
72
+ def _replace(data, condition, value):
73
+ def do(x):
74
+ if isinstance(x, dict):
75
+ return {k: do(v) for k, v in x.items()}
76
+ elif isinstance(x, list):
77
+ return [do(y) for y in x]
78
+ else:
79
+ return value if condition(x) else x
80
+
81
+ return do(data)
82
+
83
+
84
+ _CONFIG_NONE = '__none__'
85
+
86
+
87
+ def unpack_config(config: RawConfig) -> RawConfig:
88
+ config = cast(RawConfig, _replace(config, lambda x: x == _CONFIG_NONE, None))
89
+ return config
90
+
91
+
92
+ def pack_config(config: RawConfig) -> RawConfig:
93
+ config = cast(RawConfig, _replace(config, lambda x: x is None, _CONFIG_NONE))
94
+ return config
95
+
96
+
97
+ def load_config(path: Union[Path, str]) -> Any:
98
+ with open(path, 'rb') as f:
99
+ return unpack_config(tomli.load(f))
100
+
101
+
102
+ def dump_config(config: Any, path: Union[Path, str]) -> None:
103
+ with open(path, 'wb') as f:
104
+ tomli_w.dump(pack_config(config), f)
105
+ # check that there are no bugs in all these "pack/unpack" things
106
+ assert config == load_config(path)
107
+
108
+
109
+ def load_json(path: Union[Path, str], **kwargs) -> Any:
110
+ return json.loads(Path(path).read_text(), **kwargs)
111
+
112
+
113
+ def dump_json(x: Any, path: Union[Path, str], **kwargs) -> None:
114
+ kwargs.setdefault('indent', 4)
115
+ Path(path).write_text(json.dumps(x, **kwargs) + '\n')
116
+
117
+
118
+ def load_pickle(path: Union[Path, str], **kwargs) -> Any:
119
+ return pickle.loads(Path(path).read_bytes(), **kwargs)
120
+
121
+
122
+ def dump_pickle(x: Any, path: Union[Path, str], **kwargs) -> None:
123
+ Path(path).write_bytes(pickle.dumps(x, **kwargs))
124
+
125
+
126
+ def load(path: Union[Path, str], **kwargs) -> Any:
127
+ return globals()[f'load_{Path(path).suffix[1:]}'](Path(path), **kwargs)
128
+
129
+
130
+ def dump(x: Any, path: Union[Path, str], **kwargs) -> Any:
131
+ return globals()[f'dump_{Path(path).suffix[1:]}'](x, Path(path), **kwargs)
132
+
133
+
134
+ def _get_output_item_path(
135
+ path: Union[str, Path], filename: str, must_exist: bool
136
+ ) -> Path:
137
+ path = env.get_path(path)
138
+ if path.suffix == '.toml':
139
+ path = path.with_suffix('')
140
+ if path.is_dir():
141
+ path = path / filename
142
+ else:
143
+ assert path.name == filename
144
+ assert path.parent.exists()
145
+ if must_exist:
146
+ assert path.exists()
147
+ return path
148
+
149
+
150
+ def load_report(path: Path) -> Report:
151
+ return load_json(_get_output_item_path(path, 'report.json', True))
152
+
153
+
154
+ def dump_report(report: dict, path: Path) -> None:
155
+ dump_json(report, _get_output_item_path(path, 'report.json', False))
156
+
157
+
158
+ def load_predictions(path: Path) -> Dict[str, np.ndarray]:
159
+ with np.load(_get_output_item_path(path, 'predictions.npz', True)) as predictions:
160
+ return {x: predictions[x] for x in predictions}
161
+
162
+
163
+ def dump_predictions(predictions: Dict[str, np.ndarray], path: Path) -> None:
164
+ np.savez(_get_output_item_path(path, 'predictions.npz', False), **predictions)
165
+
166
+
167
+ def dump_metrics(metrics: Dict[str, Any], path: Path) -> None:
168
+ dump_json(metrics, _get_output_item_path(path, 'metrics.json', False))
169
+
170
+
171
+ def load_checkpoint(path: Path, *args, **kwargs) -> Dict[str, np.ndarray]:
172
+ return torch.load(
173
+ _get_output_item_path(path, 'checkpoint.pt', True), *args, **kwargs
174
+ )
175
+
176
+
177
+ def get_device() -> torch.device:
178
+ if torch.cuda.is_available():
179
+ assert os.environ.get('CUDA_VISIBLE_DEVICES') is not None
180
+ return torch.device('cuda:0')
181
+ else:
182
+ return torch.device('cpu')
183
+
184
+
185
+ def _print_sep(c, size=100):
186
+ print(c * size)
187
+
188
+
189
+ _LAST_SNAPSHOT_TIME = None
190
+
191
+
192
+ def backup_output(output_dir: Path) -> None:
193
+ backup_dir = os.environ.get('TMP_OUTPUT_PATH')
194
+ snapshot_dir = os.environ.get('SNAPSHOT_PATH')
195
+ if backup_dir is None:
196
+ assert snapshot_dir is None
197
+ return
198
+ assert snapshot_dir is not None
199
+
200
+ try:
201
+ relative_output_dir = output_dir.relative_to(env.PROJ)
202
+ except ValueError:
203
+ return
204
+
205
+ for dir_ in [backup_dir, snapshot_dir]:
206
+ new_output_dir = dir_ / relative_output_dir
207
+ prev_backup_output_dir = new_output_dir.with_name(new_output_dir.name + '_prev')
208
+ new_output_dir.parent.mkdir(exist_ok=True, parents=True)
209
+ if new_output_dir.exists():
210
+ new_output_dir.rename(prev_backup_output_dir)
211
+ shutil.copytree(output_dir, new_output_dir)
212
+ # the case for evaluate.py which automatically creates configs
213
+ if output_dir.with_suffix('.toml').exists():
214
+ shutil.copyfile(
215
+ output_dir.with_suffix('.toml'), new_output_dir.with_suffix('.toml')
216
+ )
217
+ if prev_backup_output_dir.exists():
218
+ shutil.rmtree(prev_backup_output_dir)
219
+
220
+ global _LAST_SNAPSHOT_TIME
221
+ if _LAST_SNAPSHOT_TIME is None or time.time() - _LAST_SNAPSHOT_TIME > 10 * 60:
222
+ import nirvana_dl.snapshot # type: ignore[code]
223
+
224
+ nirvana_dl.snapshot.dump_snapshot()
225
+ _LAST_SNAPSHOT_TIME = time.time()
226
+ print('The snapshot was saved!')
227
+
228
+
229
+ def _get_scores(metrics: Dict[str, Dict[str, Any]]) -> Optional[Dict[str, float]]:
230
+ return (
231
+ {k: v['score'] for k, v in metrics.items()}
232
+ if 'score' in next(iter(metrics.values()))
233
+ else None
234
+ )
235
+
236
+
237
+ def format_scores(metrics: Dict[str, Dict[str, Any]]) -> str:
238
+ return ' '.join(
239
+ f"[{x}] {metrics[x]['score']:.3f}"
240
+ for x in ['test', 'val', 'train']
241
+ if x in metrics
242
+ )
243
+
244
+
245
+ def finish(output_dir: Path, report: dict) -> None:
246
+ print()
247
+ _print_sep('=')
248
+
249
+ metrics = report.get('metrics')
250
+ if metrics is not None:
251
+ scores = _get_scores(metrics)
252
+ if scores is not None:
253
+ dump_json(scores, output_dir / 'scores.json')
254
+ print(format_scores(metrics))
255
+ _print_sep('-')
256
+
257
+ dump_report(report, output_dir)
258
+ json_output_path = os.environ.get('JSON_OUTPUT_FILE')
259
+ if json_output_path:
260
+ try:
261
+ key = str(output_dir.relative_to(env.PROJ))
262
+ except ValueError:
263
+ pass
264
+ else:
265
+ json_output_path = Path(json_output_path)
266
+ try:
267
+ json_data = json.loads(json_output_path.read_text())
268
+ except (FileNotFoundError, json.decoder.JSONDecodeError):
269
+ json_data = {}
270
+ json_data[key] = load_json(output_dir / 'report.json')
271
+ json_output_path.write_text(json.dumps(json_data, indent=4))
272
+ shutil.copyfile(
273
+ json_output_path,
274
+ os.path.join(os.environ['SNAPSHOT_PATH'], 'json_output.json'),
275
+ )
276
+
277
+ output_dir.joinpath('DONE').touch()
278
+ backup_output(output_dir)
279
+ print(f'Done! | {report.get("time")} | {output_dir}')
280
+ _print_sep('=')
281
+ print()
282
+
283
+
284
+ def from_dict(datacls: Type[T], data: dict) -> T:
285
+ assert is_dataclass(datacls)
286
+ data = deepcopy(data)
287
+ for field in fields(datacls):
288
+ if field.name not in data:
289
+ continue
290
+ if is_dataclass(field.type):
291
+ data[field.name] = from_dict(field.type, data[field.name])
292
+ elif (
293
+ get_origin(field.type) is Union
294
+ and len(get_args(field.type)) == 2
295
+ and get_args(field.type)[1] is type(None)
296
+ and is_dataclass(get_args(field.type)[0])
297
+ ):
298
+ if data[field.name] is not None:
299
+ data[field.name] = from_dict(get_args(field.type)[0], data[field.name])
300
+ return datacls(**data)
301
+
302
+
303
+ def replace_factor_with_value(
304
+ config: RawConfig,
305
+ key: str,
306
+ reference_value: int,
307
+ bounds: Tuple[float, float],
308
+ ) -> None:
309
+ factor_key = key + '_factor'
310
+ if factor_key not in config:
311
+ assert key in config
312
+ else:
313
+ assert key not in config
314
+ factor = config.pop(factor_key)
315
+ assert bounds[0] <= factor <= bounds[1]
316
+ config[key] = int(factor * reference_value)
317
+
318
+
319
+ def get_temporary_copy(path: Union[str, Path]) -> Path:
320
+ path = env.get_path(path)
321
+ assert not path.is_dir() and not path.is_symlink()
322
+ tmp_path = path.with_name(
323
+ path.stem + '___' + str(uuid.uuid4()).replace('-', '') + path.suffix
324
+ )
325
+ shutil.copyfile(path, tmp_path)
326
+ atexit.register(lambda: tmp_path.unlink())
327
+ return tmp_path
328
+
329
+
330
+ def get_python():
331
+ python = Path('python3.9')
332
+ return str(python) if python.exists() else 'python'
333
+
334
+ def get_catboost_config(real_data_path, is_cv=False):
335
+ ds_name = Path(real_data_path).name
336
+ C = load_json(f'tuned_models/catboost/{ds_name}_cv.json')
337
+ return C
338
+
339
+ def get_categories(X_train_cat):
340
+ return (
341
+ None
342
+ if X_train_cat is None
343
+ else [
344
+ len(set(X_train_cat[:, i]))
345
+ for i in range(X_train_cat.shape[1])
346
+ ]
347
+ )
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/synthetic/pipeline_n14/real.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c185607e5260848288c1fe3ee266131707a54e9f5e053f1234c019f315783fac
3
+ size 700663
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/synthetic/pipeline_n14/test.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6c58f97d23ce9ec15dde2caf4ba02105c2839eb4b1e1bb7f5183e0661fec4ecd
3
+ size 88640
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/synthetic/pipeline_n14/val.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:efcb8ee58a24ce4397213b3c4df4826fbcc6662da77b0919ff4e1935d12e2e89
3
+ size 87578
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/conftest.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import numpy as np
3
+ import torch
4
+ import torch.nn.functional as F
5
+ from unittest.mock import MagicMock
6
+
7
+
8
+ # --------------- dimension configs ---------------
9
+
10
+ @pytest.fixture
11
+ def dims():
12
+ """Standard mixed-data dimensions."""
13
+ return {"d_numerical": 4, "categories": np.array([3, 5, 2]), "batch_size": 8, "d_token": 16}
14
+
15
+
16
+ @pytest.fixture
17
+ def dims_numerical_only():
18
+ """Numerical-only scenario (no categorical features)."""
19
+ return {"d_numerical": 5, "categories": None, "batch_size": 8, "d_token": 16}
20
+
21
+
22
+ @pytest.fixture
23
+ def dims_single():
24
+ """Minimal scenario: 1 numerical, 1 categorical with 2 classes."""
25
+ return {"d_numerical": 1, "categories": np.array([2]), "batch_size": 4, "d_token": 8}
26
+
27
+
28
+ # --------------- dummy input factory ---------------
29
+
30
+ @pytest.fixture
31
+ def make_dummy_inputs():
32
+ """Factory: returns (x_num, x_cat_onehot, x_cat_int, timesteps) from any dims."""
33
+ def _make(d_numerical, categories, batch_size):
34
+ torch.manual_seed(42)
35
+ x_num = torch.randn(batch_size, d_numerical)
36
+ if categories is not None and len(categories) > 0:
37
+ cat_parts = []
38
+ for k in categories:
39
+ indices = torch.randint(0, k, (batch_size,))
40
+ cat_parts.append(F.one_hot(indices, k).float())
41
+ x_cat_onehot = torch.cat(cat_parts, dim=1)
42
+ x_cat_int = torch.stack(
43
+ [torch.randint(0, k, (batch_size,)) for k in categories], dim=1
44
+ )
45
+ else:
46
+ x_cat_onehot = None
47
+ x_cat_int = None
48
+ timesteps = torch.rand(batch_size)
49
+ return x_num, x_cat_onehot, x_cat_int, timesteps
50
+ return _make
51
+
52
+
53
+ # --------------- model factories ---------------
54
+
55
+ @pytest.fixture
56
+ def make_tokenizer():
57
+ from ef_vfm.modules.transformer import Tokenizer
58
+ def _make(d_numerical, categories, d_token, bias=True):
59
+ cats = list(categories) if categories is not None else None
60
+ return Tokenizer(d_numerical, cats, d_token, bias)
61
+ return _make
62
+
63
+
64
+ @pytest.fixture
65
+ def make_transformer():
66
+ from ef_vfm.modules.transformer import Transformer
67
+ def _make(d_token, n_layers=2, n_heads=1, d_ffn_factor=4, activation='gelu'):
68
+ return Transformer(n_layers, d_token, n_heads, d_token, d_ffn_factor, activation=activation)
69
+ return _make
70
+
71
+
72
+ @pytest.fixture
73
+ def make_reconstructor():
74
+ from ef_vfm.modules.transformer import Reconstructor
75
+ def _make(d_numerical, categories, d_token):
76
+ cats = list(categories) if categories is not None else []
77
+ return Reconstructor(d_numerical, cats, d_token)
78
+ return _make
79
+
80
+
81
+ @pytest.fixture
82
+ def make_mlp():
83
+ from ef_vfm.modules.main_modules import MLP
84
+ def _make(d_in, dim_t=128, use_mlp=True):
85
+ return MLP(d_in, dim_t=dim_t, use_mlp=use_mlp)
86
+ return _make
87
+
88
+
89
+ @pytest.fixture
90
+ def make_unimodmlp():
91
+ from ef_vfm.modules.main_modules import UniModMLP
92
+ def _make(d_numerical, categories, d_token=16, n_layers=1, n_head=1,
93
+ factor=4, dim_t=64, activation='gelu'):
94
+ cats = list(categories) if categories is not None else []
95
+ return UniModMLP(
96
+ d_numerical, cats, n_layers, d_token,
97
+ n_head=n_head, factor=factor, dim_t=dim_t, activation=activation,
98
+ )
99
+ return _make
100
+
101
+
102
+ @pytest.fixture
103
+ def make_flow_model():
104
+ from ef_vfm.modules.main_modules import UniModMLP
105
+ from ef_vfm.models.flow_model import ExpVFM
106
+ def _make(d_numerical, categories, d_token=16, n_layers=1, dim_t=64):
107
+ cats_list = list(categories) if categories is not None else []
108
+ cats_np = np.array(cats_list)
109
+ model = UniModMLP(
110
+ d_numerical, cats_list, n_layers, d_token,
111
+ n_head=1, factor=4, dim_t=dim_t, activation='gelu',
112
+ )
113
+ flow = ExpVFM(
114
+ num_classes=cats_np,
115
+ num_numerical_features=d_numerical,
116
+ vf_fn=model,
117
+ device=torch.device('cpu'),
118
+ )
119
+ return flow
120
+ return _make
121
+
122
+
123
+ @pytest.fixture
124
+ def make_trainer():
125
+ """Factory: creates a minimal Trainer with mocked external dependencies."""
126
+ from ef_vfm.modules.main_modules import UniModMLP
127
+ from ef_vfm.models.flow_model import ExpVFM
128
+ from ef_vfm.trainer import Trainer
129
+
130
+ def _make(d_numerical=4, categories=np.array([3, 5, 2]),
131
+ lr=0.001, max_grad_norm=1.0, warmup_epochs=0,
132
+ lr_scheduler='reduce_lr_on_plateau', steps=10, tmp_path=None):
133
+
134
+ cats_list = list(categories) if categories is not None else []
135
+ cats_np = np.array(cats_list)
136
+
137
+ model = UniModMLP(
138
+ d_numerical, cats_list, 1, 16,
139
+ n_head=1, factor=4, dim_t=64, activation='gelu',
140
+ )
141
+ flow = ExpVFM(
142
+ num_classes=cats_np,
143
+ num_numerical_features=d_numerical,
144
+ vf_fn=model,
145
+ device=torch.device('cpu'),
146
+ )
147
+
148
+ # Build a small synthetic dataset: [N, d_num + len(cats)] with int cat indices
149
+ n_samples = 32
150
+ x_num = torch.randn(n_samples, d_numerical)
151
+ if len(cats_list) > 0:
152
+ x_cat = torch.stack(
153
+ [torch.randint(0, k, (n_samples,)) for k in cats_list], dim=1
154
+ ).float()
155
+ data = torch.cat([x_num, x_cat], dim=1)
156
+ else:
157
+ data = x_num
158
+
159
+ dataset = torch.utils.data.TensorDataset(data)
160
+ train_iter = torch.utils.data.DataLoader(dataset, batch_size=8, shuffle=False)
161
+ # DataLoader wraps in tuples; Trainer expects raw tensors, so use a wrapper
162
+ class _UnwrapLoader:
163
+ def __init__(self, loader):
164
+ self._loader = loader
165
+ def __iter__(self):
166
+ for (batch,) in self._loader:
167
+ yield batch
168
+ def __len__(self):
169
+ return len(self._loader)
170
+
171
+ save_path = str(tmp_path) if tmp_path else "/tmp"
172
+ trainer = Trainer(
173
+ flow=flow,
174
+ train_iter=_UnwrapLoader(train_iter),
175
+ dataset=MagicMock(),
176
+ test_dataset=MagicMock(),
177
+ metrics=MagicMock(),
178
+ logger=MagicMock(),
179
+ lr=lr,
180
+ weight_decay=0,
181
+ steps=steps,
182
+ batch_size=8,
183
+ check_val_every=steps + 1, # never evaluate during test
184
+ sample_batch_size=8,
185
+ model_save_path=save_path,
186
+ result_save_path=save_path,
187
+ lr_scheduler=lr_scheduler,
188
+ max_grad_norm=max_grad_norm,
189
+ warmup_epochs=warmup_epochs,
190
+ device=torch.device('cpu'),
191
+ )
192
+ return trainer
193
+ return _make
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_attention.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import torch
3
+ from ef_vfm.modules.transformer import MultiheadAttention
4
+
5
+
6
+ def test_output_shape_single_head():
7
+ attn = MultiheadAttention(d=16, n_heads=1, dropout=0.0)
8
+ x = torch.randn(4, 5, 16)
9
+ out = attn(x, x)
10
+ assert out.shape == (4, 5, 16)
11
+
12
+
13
+ def test_output_shape_multi_head():
14
+ attn = MultiheadAttention(d=16, n_heads=4, dropout=0.0)
15
+ x = torch.randn(4, 5, 16)
16
+ out = attn(x, x)
17
+ assert out.shape == (4, 5, 16)
18
+
19
+
20
+ def test_no_W_out_single_head():
21
+ attn = MultiheadAttention(d=16, n_heads=1, dropout=0.0)
22
+ assert attn.W_out is None
23
+
24
+
25
+ def test_W_out_exists_multi_head():
26
+ attn = MultiheadAttention(d=16, n_heads=4, dropout=0.0)
27
+ assert attn.W_out is not None
28
+
29
+
30
+ def test_cross_attention_diff_seq_len():
31
+ attn = MultiheadAttention(d=16, n_heads=1, dropout=0.0)
32
+ x_q = torch.randn(4, 3, 16)
33
+ x_kv = torch.randn(4, 7, 16)
34
+ out = attn(x_q, x_kv)
35
+ assert out.shape == (4, 3, 16) # output seq_len matches query
36
+
37
+
38
+ def test_invalid_d_nheads_raises():
39
+ with pytest.raises(AssertionError):
40
+ MultiheadAttention(d=15, n_heads=4, dropout=0.0)
41
+
42
+
43
+ def test_gradient_flows():
44
+ attn = MultiheadAttention(d=16, n_heads=2, dropout=0.0)
45
+ x = torch.randn(4, 5, 16, requires_grad=True)
46
+ out = attn(x, x)
47
+ out.sum().backward()
48
+ assert x.grad is not None and x.grad.abs().sum() > 0
49
+ for name in ['W_q', 'W_k', 'W_v']:
50
+ param = getattr(attn, name)
51
+ assert param.weight.grad is not None and param.weight.grad.abs().sum() > 0
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_config.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+
4
+ from src.util import load_config
5
+ from ef_vfm.modules.main_modules import UniModMLP
6
+
7
+
8
+ CONFIG_PATH = Path(__file__).resolve().parent.parent / "ef_vfm" / "configs" / "ef_vfm_configs.toml"
9
+
10
+
11
+ def test_load_config_returns_dict():
12
+ config = load_config(CONFIG_PATH)
13
+ assert isinstance(config, dict)
14
+
15
+
16
+ def test_config_has_expected_sections():
17
+ config = load_config(CONFIG_PATH)
18
+ for key in ['data', 'unimodmlp_params', 'train', 'sample']:
19
+ assert key in config, f"Missing section '{key}'"
20
+
21
+
22
+ def test_unimodmlp_params_complete():
23
+ config = load_config(CONFIG_PATH)
24
+ params = config['unimodmlp_params']
25
+ required = ['num_layers', 'd_token', 'n_head', 'factor', 'bias', 'dim_t', 'use_mlp', 'activation']
26
+ for key in required:
27
+ assert key in params, f"Missing param '{key}' in unimodmlp_params"
28
+
29
+
30
+ def test_activation_value_is_valid():
31
+ config = load_config(CONFIG_PATH)
32
+ activation = config['unimodmlp_params']['activation']
33
+ assert activation in ('relu', 'gelu', 'silu'), f"Invalid activation '{activation}'"
34
+
35
+
36
+ def test_train_main_has_new_params():
37
+ """Verify the recently added config params are present."""
38
+ config = load_config(CONFIG_PATH)
39
+ train = config['train']['main']
40
+ assert 'max_grad_norm' in train
41
+ assert 'warmup_epochs' in train
42
+ assert isinstance(train['max_grad_norm'], (int, float))
43
+ assert isinstance(train['warmup_epochs'], (int, float))
44
+
45
+
46
+ def test_config_values_create_model():
47
+ config = load_config(CONFIG_PATH)
48
+ params = config['unimodmlp_params']
49
+ # Use dummy dimensions; the point is that config params are valid for the constructor
50
+ model = UniModMLP(
51
+ d_numerical=4,
52
+ categories=[3, 5, 2],
53
+ num_layers=params['num_layers'],
54
+ d_token=params['d_token'],
55
+ n_head=params['n_head'],
56
+ factor=params['factor'],
57
+ bias=params['bias'],
58
+ dim_t=params['dim_t'],
59
+ use_mlp=params['use_mlp'],
60
+ activation=params['activation'],
61
+ )
62
+ assert model is not None
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_flow_model.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ from unittest.mock import patch
4
+
5
+ from ef_vfm.models.flow_model import ExpVFM, Velocity
6
+ from ef_vfm.modules.main_modules import UniModMLP
7
+
8
+
9
+ # ---- mixed_loss tests ----
10
+
11
+ def test_mixed_loss_returns_two_scalars(make_flow_model, make_dummy_inputs, dims):
12
+ d = dims
13
+ flow = make_flow_model(d["d_numerical"], d["categories"])
14
+ _, _, x_cat_int, _ = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"])
15
+ x_num = torch.randn(d["batch_size"], d["d_numerical"])
16
+ x = torch.cat([x_num, x_cat_int.float()], dim=1)
17
+ d_loss, c_loss = flow.mixed_loss(x)
18
+ assert d_loss.dim() == 0 or d_loss.numel() == 1
19
+ assert c_loss.dim() == 0 or c_loss.numel() == 1
20
+
21
+
22
+ def test_mixed_loss_finite(make_flow_model, make_dummy_inputs, dims):
23
+ d = dims
24
+ flow = make_flow_model(d["d_numerical"], d["categories"])
25
+ _, _, x_cat_int, _ = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"])
26
+ x_num = torch.randn(d["batch_size"], d["d_numerical"])
27
+ x = torch.cat([x_num, x_cat_int.float()], dim=1)
28
+ d_loss, c_loss = flow.mixed_loss(x)
29
+ assert torch.isfinite(d_loss).all()
30
+ assert torch.isfinite(c_loss).all()
31
+
32
+
33
+ def test_mixed_loss_gradients_flow(make_flow_model, make_dummy_inputs, dims):
34
+ d = dims
35
+ flow = make_flow_model(d["d_numerical"], d["categories"])
36
+ _, _, x_cat_int, _ = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"])
37
+ x_num = torch.randn(d["batch_size"], d["d_numerical"])
38
+ x = torch.cat([x_num, x_cat_int.float()], dim=1)
39
+ d_loss, c_loss = flow.mixed_loss(x)
40
+ total = d_loss + c_loss
41
+ total.backward()
42
+ grads = [p.grad for p in flow.parameters() if p.grad is not None]
43
+ assert len(grads) > 0
44
+
45
+
46
+ def test_mixed_loss_numerical_only(make_flow_model, make_dummy_inputs, dims_numerical_only):
47
+ d = dims_numerical_only
48
+ flow = make_flow_model(d["d_numerical"], d["categories"])
49
+ x = torch.randn(d["batch_size"], d["d_numerical"])
50
+ d_loss, c_loss = flow.mixed_loss(x)
51
+ assert d_loss.item() == 0.0 # no discrete features
52
+ assert c_loss.item() > 0.0
53
+
54
+
55
+ # ---- sample tests (with mocked odeint) ----
56
+
57
+ def _make_flow(d_numerical, categories):
58
+ cats_list = list(categories) if categories is not None else []
59
+ cats_np = np.array(cats_list)
60
+ model = UniModMLP(d_numerical, cats_list, 1, 16, n_head=1, factor=4, dim_t=64, activation='gelu')
61
+ return ExpVFM(cats_np, d_numerical, model, device=torch.device('cpu'))
62
+
63
+
64
+ def test_sample_output_shape(dims):
65
+ d = dims
66
+ flow = _make_flow(d["d_numerical"], d["categories"])
67
+ d_in = d["d_numerical"] + sum(d["categories"])
68
+ n = 5
69
+ fake_trajectory = torch.randn(2, n, d_in)
70
+ with patch("ef_vfm.models.flow_model.odeint", return_value=fake_trajectory):
71
+ result = flow.sample(n)
72
+ d_out = d["d_numerical"] + len(d["categories"])
73
+ assert result.shape == (n, d_out)
74
+
75
+
76
+ def test_sample_categorical_in_range(dims):
77
+ d = dims
78
+ flow = _make_flow(d["d_numerical"], d["categories"])
79
+ d_in = d["d_numerical"] + sum(d["categories"])
80
+ n = 16
81
+ fake_trajectory = torch.randn(2, n, d_in)
82
+ with patch("ef_vfm.models.flow_model.odeint", return_value=fake_trajectory):
83
+ result = flow.sample(n)
84
+ for i, k in enumerate(d["categories"]):
85
+ col = d["d_numerical"] + i
86
+ assert (result[:, col] >= 0).all()
87
+ assert (result[:, col] < k).all()
88
+
89
+
90
+ def test_sample_returns_cpu(dims):
91
+ d = dims
92
+ flow = _make_flow(d["d_numerical"], d["categories"])
93
+ d_in = d["d_numerical"] + sum(d["categories"])
94
+ fake_trajectory = torch.randn(2, 4, d_in)
95
+ with patch("ef_vfm.models.flow_model.odeint", return_value=fake_trajectory):
96
+ result = flow.sample(4)
97
+ assert result.device == torch.device('cpu')
98
+
99
+
100
+ def test_sample_single_sample(dims):
101
+ d = dims
102
+ flow = _make_flow(d["d_numerical"], d["categories"])
103
+ d_in = d["d_numerical"] + sum(d["categories"])
104
+ fake_trajectory = torch.randn(2, 1, d_in)
105
+ with patch("ef_vfm.models.flow_model.odeint", return_value=fake_trajectory):
106
+ result = flow.sample(1)
107
+ d_out = d["d_numerical"] + len(d["categories"])
108
+ assert result.shape == (1, d_out)
109
+
110
+
111
+ # ---- to_one_hot tests ----
112
+
113
+ def test_to_one_hot_shape(dims):
114
+ d = dims
115
+ flow = _make_flow(d["d_numerical"], d["categories"])
116
+ cats = d["categories"]
117
+ x_cat = torch.stack([torch.randint(0, k, (8,)) for k in cats], dim=1)
118
+ oh = flow.to_one_hot(x_cat)
119
+ assert oh.shape == (8, sum(cats))
120
+
121
+
122
+ def test_to_one_hot_roundtrip(dims):
123
+ d = dims
124
+ flow = _make_flow(d["d_numerical"], d["categories"])
125
+ cats = d["categories"]
126
+ x_cat = torch.stack([torch.randint(0, k, (8,)) for k in cats], dim=1)
127
+ oh = flow.to_one_hot(x_cat)
128
+ # Recover indices via argmax per category slice
129
+ idx = 0
130
+ for i, k in enumerate(cats):
131
+ recovered = oh[:, idx:idx + k].argmax(dim=1)
132
+ assert torch.equal(recovered, x_cat[:, i])
133
+ idx += k
134
+
135
+
136
+ def test_to_one_hot_binary_values(dims):
137
+ d = dims
138
+ flow = _make_flow(d["d_numerical"], d["categories"])
139
+ cats = d["categories"]
140
+ x_cat = torch.stack([torch.randint(0, k, (8,)) for k in cats], dim=1)
141
+ oh = flow.to_one_hot(x_cat)
142
+ assert set(oh.unique().tolist()).issubset({0, 1})
143
+
144
+
145
+ # ---- Regression tests ----
146
+
147
+ def test_regression_d_in_no_extra_len():
148
+ """d_in must be num_numerical + sum(num_classes), NOT + len(num_classes)."""
149
+ d_numerical = 4
150
+ categories = np.array([3, 5, 2])
151
+ flow = _make_flow(d_numerical, categories)
152
+ expected_d_in = d_numerical + sum(categories) # 14, not 17
153
+ assert flow.num_numerical_features + sum(flow.num_classes) == expected_d_in
154
+
155
+
156
+ def test_regression_sampling_indices_correct():
157
+ """Categorical argmax must go to columns [d_num, d_num+1, ...], not [0, 1, ...]."""
158
+ d_numerical = 4
159
+ categories = np.array([3, 5, 2])
160
+ n = 10
161
+ d_in = d_numerical + sum(categories)
162
+ d_out = d_numerical + len(categories)
163
+
164
+ # Simulate the post-processing from sample()
165
+ out = torch.randn(n, d_in)
166
+ sample = torch.zeros(n, d_out)
167
+ sample[:, :d_numerical] = out[:, :d_numerical]
168
+
169
+ idx = d_numerical # correct starting index
170
+ for i, val in enumerate(categories):
171
+ col = d_numerical + i # correct column
172
+ sample[:, col] = torch.argmax(out[:, idx:idx + val], dim=1)
173
+ idx += val
174
+
175
+ # Numerical columns must be untouched
176
+ assert torch.allclose(sample[:, :d_numerical], out[:, :d_numerical])
177
+ # Categorical columns at correct positions
178
+ for i, val in enumerate(categories):
179
+ col = d_numerical + i
180
+ assert (sample[:, col] >= 0).all()
181
+ assert (sample[:, col] < val).all()
182
+
183
+
184
+ def test_regression_d_out_correct():
185
+ """d_out must be d_num + len(categories)."""
186
+ d_numerical = 4
187
+ categories = np.array([3, 5, 2])
188
+ flow = _make_flow(d_numerical, categories)
189
+ expected_d_out = d_numerical + len(categories) # 7
190
+ assert expected_d_out == 7
191
+
192
+
193
+ # ---- Velocity tests ----
194
+
195
+ def test_velocity_output_shape(dims):
196
+ d = dims
197
+ cats_list = list(d["categories"])
198
+ model = UniModMLP(d["d_numerical"], cats_list, 1, d["d_token"],
199
+ n_head=1, factor=4, dim_t=64, activation='gelu')
200
+ vel = Velocity(model)
201
+ d_in = d["d_numerical"] + sum(d["categories"])
202
+ x = torch.randn(d["batch_size"], d_in)
203
+ t = torch.tensor(0.5)
204
+ out = vel(t, x)
205
+ assert out.shape == (d["batch_size"], d_in)
206
+
207
+
208
+ def test_velocity_scalar_t_broadcast(dims):
209
+ d = dims
210
+ cats_list = list(d["categories"])
211
+ model = UniModMLP(d["d_numerical"], cats_list, 1, d["d_token"],
212
+ n_head=1, factor=4, dim_t=64, activation='gelu')
213
+ vel = Velocity(model)
214
+ d_in = d["d_numerical"] + sum(d["categories"])
215
+ x = torch.randn(d["batch_size"], d_in)
216
+ # Scalar t should work (gets broadcast internally)
217
+ t = torch.tensor(0.3)
218
+ out = vel(t, x)
219
+ assert out.shape == x.shape
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_mlp.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from ef_vfm.modules.main_modules import MLP, PositionalEmbedding
4
+
5
+
6
+ # ---- PositionalEmbedding tests ----
7
+
8
+ def test_positional_embedding_shape():
9
+ pe = PositionalEmbedding(num_channels=64)
10
+ x = torch.rand(8)
11
+ out = pe(x)
12
+ assert out.shape == (8, 64)
13
+
14
+
15
+ def test_positional_embedding_bounded():
16
+ pe = PositionalEmbedding(num_channels=64)
17
+ x = torch.rand(8)
18
+ out = pe(x)
19
+ assert out.min() >= -1.0
20
+ assert out.max() <= 1.0
21
+
22
+
23
+ def test_positional_embedding_deterministic():
24
+ pe = PositionalEmbedding(num_channels=64)
25
+ x = torch.tensor([0.1, 0.5, 0.9])
26
+ out1 = pe(x)
27
+ out2 = pe(x)
28
+ assert torch.equal(out1, out2)
29
+
30
+
31
+ def test_positional_embedding_different_timesteps():
32
+ pe = PositionalEmbedding(num_channels=64)
33
+ t1 = torch.tensor([0.1])
34
+ t2 = torch.tensor([0.9])
35
+ assert not torch.allclose(pe(t1), pe(t2))
36
+
37
+
38
+ # ---- MLP tests ----
39
+
40
+ def test_mlp_output_shape(make_mlp):
41
+ mlp = make_mlp(d_in=32, dim_t=64)
42
+ x = torch.randn(8, 32)
43
+ t = torch.rand(8)
44
+ out = mlp(x, t)
45
+ assert out.shape == (8, 32)
46
+
47
+
48
+ def test_mlp_use_mlp_true(make_mlp):
49
+ mlp = make_mlp(d_in=32, dim_t=64, use_mlp=True)
50
+ assert isinstance(mlp.mlp, nn.Sequential)
51
+
52
+
53
+ def test_mlp_use_mlp_false(make_mlp):
54
+ mlp = make_mlp(d_in=32, dim_t=64, use_mlp=False)
55
+ assert isinstance(mlp.mlp, nn.Linear)
56
+
57
+
58
+ def test_mlp_time_conditioning(make_mlp):
59
+ mlp = make_mlp(d_in=32, dim_t=64)
60
+ mlp.eval()
61
+ x = torch.randn(4, 32)
62
+ t1 = torch.zeros(4)
63
+ t2 = torch.ones(4)
64
+ out1 = mlp(x, t1)
65
+ out2 = mlp(x, t2)
66
+ assert not torch.allclose(out1, out2)
67
+
68
+
69
+ def test_mlp_gradient_flows(make_mlp):
70
+ mlp = make_mlp(d_in=32, dim_t=64)
71
+ x = torch.randn(4, 32)
72
+ t = torch.rand(4)
73
+ out = mlp(x, t)
74
+ out.sum().backward()
75
+ assert mlp.proj.weight.grad is not None and mlp.proj.weight.grad.abs().sum() > 0
76
+ assert mlp.map_noise.num_channels == 64 # sanity check on PE config
77
+
78
+
79
+ def test_mlp_different_dim_t(make_mlp):
80
+ for dim_t in [32, 128, 256]:
81
+ mlp = make_mlp(d_in=16, dim_t=dim_t)
82
+ x = torch.randn(4, 16)
83
+ t = torch.rand(4)
84
+ out = mlp(x, t)
85
+ assert out.shape == (4, 16)
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_reconstructor.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ from ef_vfm.modules.transformer import Reconstructor
4
+
5
+
6
+ def test_output_shapes_mixed(make_reconstructor, dims):
7
+ d = dims
8
+ r = make_reconstructor(d["d_numerical"], d["categories"], d["d_token"])
9
+ seq_len = d["d_numerical"] + len(d["categories"])
10
+ h = torch.randn(d["batch_size"], seq_len, d["d_token"])
11
+ x_num, x_cat = r(h)
12
+ assert x_num.shape == (d["batch_size"], d["d_numerical"])
13
+ assert len(x_cat) == len(d["categories"])
14
+ for i, k in enumerate(d["categories"]):
15
+ assert x_cat[i].shape == (d["batch_size"], k)
16
+
17
+
18
+ def test_categorical_count(make_reconstructor, dims):
19
+ d = dims
20
+ r = make_reconstructor(d["d_numerical"], d["categories"], d["d_token"])
21
+ seq_len = d["d_numerical"] + len(d["categories"])
22
+ h = torch.randn(d["batch_size"], seq_len, d["d_token"])
23
+ _, x_cat = r(h)
24
+ assert len(x_cat) == len(d["categories"])
25
+
26
+
27
+ def test_empty_categories(make_reconstructor):
28
+ r = make_reconstructor(4, np.array([]), 16)
29
+ h = torch.randn(8, 4, 16)
30
+ x_num, x_cat = r(h)
31
+ assert x_num.shape == (8, 4)
32
+ assert len(x_cat) == 0
33
+
34
+
35
+ def test_weight_shape(make_reconstructor, dims):
36
+ d = dims
37
+ r = make_reconstructor(d["d_numerical"], d["categories"], d["d_token"])
38
+ assert r.weight.shape == (d["d_numerical"], d["d_token"])
39
+
40
+
41
+ def test_gradient_flows(make_reconstructor, dims):
42
+ d = dims
43
+ r = make_reconstructor(d["d_numerical"], d["categories"], d["d_token"])
44
+ seq_len = d["d_numerical"] + len(d["categories"])
45
+ h = torch.randn(d["batch_size"], seq_len, d["d_token"])
46
+ x_num, x_cat = r(h)
47
+ loss = x_num.sum() + sum(c.sum() for c in x_cat)
48
+ loss.backward()
49
+ assert r.weight.grad is not None and r.weight.grad.abs().sum() > 0
50
+ for recon in r.cat_recons:
51
+ assert recon.weight.grad is not None
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_tokenizer.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+
4
+
5
+ def test_forward_shape_mixed(make_tokenizer, make_dummy_inputs, dims):
6
+ tok = make_tokenizer(dims["d_numerical"], dims["categories"], dims["d_token"])
7
+ x_num, x_cat_oh, _, _ = make_dummy_inputs(dims["d_numerical"], dims["categories"], dims["batch_size"])
8
+ out = tok(x_num, x_cat_oh)
9
+ expected_seq = 1 + dims["d_numerical"] + len(dims["categories"])
10
+ assert out.shape == (dims["batch_size"], expected_seq, dims["d_token"])
11
+
12
+
13
+ def test_forward_shape_numerical_only(make_tokenizer, make_dummy_inputs, dims_numerical_only):
14
+ d = dims_numerical_only
15
+ tok = make_tokenizer(d["d_numerical"], d["categories"], d["d_token"])
16
+ x_num, _, _, _ = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"])
17
+ out = tok(x_num, None)
18
+ expected_seq = 1 + d["d_numerical"]
19
+ assert out.shape == (d["batch_size"], expected_seq, d["d_token"])
20
+
21
+
22
+ def test_forward_shape_single_feature(make_tokenizer, make_dummy_inputs, dims_single):
23
+ d = dims_single
24
+ tok = make_tokenizer(d["d_numerical"], d["categories"], d["d_token"])
25
+ x_num, x_cat_oh, _, _ = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"])
26
+ out = tok(x_num, x_cat_oh)
27
+ expected_seq = 1 + d["d_numerical"] + len(d["categories"])
28
+ assert out.shape == (d["batch_size"], expected_seq, d["d_token"])
29
+
30
+
31
+ def test_n_tokens_property(make_tokenizer, dims):
32
+ tok = make_tokenizer(dims["d_numerical"], dims["categories"], dims["d_token"])
33
+ expected = dims["d_numerical"] + 1 + len(dims["categories"])
34
+ assert tok.n_tokens == expected
35
+
36
+
37
+ def test_n_tokens_numerical_only(make_tokenizer, dims_numerical_only):
38
+ d = dims_numerical_only
39
+ tok = make_tokenizer(d["d_numerical"], d["categories"], d["d_token"])
40
+ assert tok.n_tokens == d["d_numerical"] + 1
41
+
42
+
43
+ def test_cls_token_position(make_tokenizer, make_dummy_inputs, dims):
44
+ tok = make_tokenizer(dims["d_numerical"], dims["categories"], dims["d_token"], bias=False)
45
+ x_num, x_cat_oh, _, _ = make_dummy_inputs(dims["d_numerical"], dims["categories"], dims["batch_size"])
46
+ out = tok(x_num, x_cat_oh)
47
+ # CLS token: ones * weight[0], so all batch rows should have the same CLS token
48
+ cls_tokens = out[:, 0, :]
49
+ assert torch.allclose(cls_tokens[0], cls_tokens[1])
50
+ assert torch.allclose(cls_tokens[0], tok.weight[0])
51
+
52
+
53
+ def test_bias_vs_no_bias(make_tokenizer, make_dummy_inputs, dims):
54
+ d = dims
55
+ tok_bias = make_tokenizer(d["d_numerical"], d["categories"], d["d_token"], bias=True)
56
+ tok_no_bias = make_tokenizer(d["d_numerical"], d["categories"], d["d_token"], bias=False)
57
+ assert tok_bias.bias is not None
58
+ assert tok_no_bias.bias is None
59
+
60
+
61
+ def test_category_offsets_values(make_tokenizer):
62
+ cats = np.array([3, 5, 2])
63
+ tok = make_tokenizer(4, cats, 16)
64
+ assert torch.equal(tok.category_offsets, torch.tensor([0, 3, 8]))
65
+ assert torch.equal(tok.category_ends, torch.tensor([3, 8, 10]))
66
+
67
+
68
+ def test_cat_weight_shape(make_tokenizer, dims):
69
+ tok = make_tokenizer(dims["d_numerical"], dims["categories"], dims["d_token"])
70
+ assert tok.cat_weight.shape == (sum(dims["categories"]), dims["d_token"])
71
+
72
+
73
+ def test_weight_shape(make_tokenizer, dims):
74
+ tok = make_tokenizer(dims["d_numerical"], dims["categories"], dims["d_token"])
75
+ assert tok.weight.shape == (dims["d_numerical"] + 1, dims["d_token"])
76
+
77
+
78
+ def test_gradient_flows(make_tokenizer, make_dummy_inputs, dims):
79
+ tok = make_tokenizer(dims["d_numerical"], dims["categories"], dims["d_token"])
80
+ x_num, x_cat_oh, _, _ = make_dummy_inputs(dims["d_numerical"], dims["categories"], dims["batch_size"])
81
+ out = tok(x_num, x_cat_oh)
82
+ out.sum().backward()
83
+ assert tok.weight.grad is not None and tok.weight.grad.abs().sum() > 0
84
+ assert tok.cat_weight.grad is not None and tok.cat_weight.grad.abs().sum() > 0
85
+ assert tok.bias.grad is not None and tok.bias.grad.abs().sum() > 0
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_trainer.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+
4
+
5
+ # ---- Gradient clipping tests ----
6
+
7
+ def test_grad_clipping_applied(make_trainer, tmp_path):
8
+ trainer = make_trainer(max_grad_norm=0.5, tmp_path=tmp_path)
9
+ batch = next(iter(trainer.train_iter))
10
+ trainer._run_step(batch, closs_weight=1.0, dloss_weight=1.0)
11
+ # After clipping, total gradient norm should be <= max_grad_norm (with tolerance)
12
+ total_norm = torch.nn.utils.clip_grad_norm_(trainer.flow.parameters(), float('inf'))
13
+ # Gradients were already clipped in _run_step, then optimizer.step() zeroed them.
14
+ # So we re-run to check: do a fresh forward-backward without step
15
+ trainer.optimizer.zero_grad()
16
+ dloss, closs = trainer.flow.mixed_loss(batch.to(trainer.device))
17
+ (dloss + closs).backward()
18
+ torch.nn.utils.clip_grad_norm_(trainer.flow.parameters(), 0.5)
19
+ total_norm = 0.0
20
+ for p in trainer.flow.parameters():
21
+ if p.grad is not None:
22
+ total_norm += p.grad.data.norm(2).item() ** 2
23
+ total_norm = total_norm ** 0.5
24
+ assert total_norm <= 0.5 + 1e-6
25
+
26
+
27
+ def test_grad_clipping_disabled(make_trainer, tmp_path):
28
+ trainer = make_trainer(max_grad_norm=0, tmp_path=tmp_path)
29
+ assert trainer.max_grad_norm == 0
30
+
31
+
32
+ def test_run_step_returns_losses(make_trainer, tmp_path):
33
+ trainer = make_trainer(tmp_path=tmp_path)
34
+ batch = next(iter(trainer.train_iter))
35
+ dloss, closs = trainer._run_step(batch, closs_weight=1.0, dloss_weight=1.0)
36
+ assert isinstance(dloss, torch.Tensor)
37
+ assert isinstance(closs, torch.Tensor)
38
+ assert torch.isfinite(dloss)
39
+ assert torch.isfinite(closs)
40
+
41
+
42
+ # ---- LR warmup tests ----
43
+
44
+ def test_warmup_lr_linear_ramp(make_trainer, tmp_path):
45
+ init_lr = 0.01
46
+ warmup = 5
47
+ trainer = make_trainer(lr=init_lr, warmup_epochs=warmup, tmp_path=tmp_path)
48
+ # Simulate warmup epochs
49
+ for epoch in range(warmup):
50
+ expected_lr = init_lr * (epoch + 1) / warmup
51
+ if trainer.warmup_epochs > 0 and (epoch + 1) <= trainer.warmup_epochs:
52
+ warmup_lr = trainer.init_lr * (epoch + 1) / trainer.warmup_epochs
53
+ for pg in trainer.optimizer.param_groups:
54
+ pg["lr"] = warmup_lr
55
+ actual_lr = trainer.optimizer.param_groups[0]["lr"]
56
+ assert abs(actual_lr - expected_lr) < 1e-8, f"Epoch {epoch}: expected {expected_lr}, got {actual_lr}"
57
+
58
+
59
+ def test_warmup_overrides_scheduler(make_trainer, tmp_path):
60
+ trainer = make_trainer(warmup_epochs=10, lr_scheduler='reduce_lr_on_plateau', tmp_path=tmp_path)
61
+ initial_lr = trainer.optimizer.param_groups[0]["lr"]
62
+ # During warmup, scheduler.step should NOT be called (we just set LR directly)
63
+ # Simulate epoch 1 warmup
64
+ warmup_lr = trainer.init_lr * 1 / trainer.warmup_epochs
65
+ for pg in trainer.optimizer.param_groups:
66
+ pg["lr"] = warmup_lr
67
+ assert trainer.optimizer.param_groups[0]["lr"] == warmup_lr
68
+ assert warmup_lr < initial_lr # warmup starts lower
69
+
70
+
71
+ def test_no_warmup_when_zero(make_trainer, tmp_path):
72
+ trainer = make_trainer(warmup_epochs=0, tmp_path=tmp_path)
73
+ assert trainer.warmup_epochs == 0
74
+ # LR should be the init_lr from the start
75
+ assert trainer.optimizer.param_groups[0]["lr"] == trainer.init_lr
76
+
77
+
78
+ # ---- LR scheduler tests ----
79
+
80
+ def test_anneal_lr(make_trainer, tmp_path):
81
+ trainer = make_trainer(lr=0.01, steps=100, lr_scheduler='anneal', tmp_path=tmp_path)
82
+ trainer._anneal_lr(50)
83
+ expected = 0.01 * (1 - 50 / 100)
84
+ assert abs(trainer.optimizer.param_groups[0]["lr"] - expected) < 1e-8
85
+
86
+
87
+ # ---- EMA tests ----
88
+
89
+ def test_ema_model_created(make_trainer, tmp_path):
90
+ trainer = make_trainer(tmp_path=tmp_path)
91
+ # EMA model should exist and have same structure as flow._vf_fn
92
+ assert trainer.ema_model is not None
93
+ ema_params = list(trainer.ema_model.parameters())
94
+ model_params = list(trainer.flow._vf_fn.parameters())
95
+ assert len(ema_params) == len(model_params)
96
+ # EMA params should be detached (requires_grad=False)
97
+ for p in ema_params:
98
+ assert not p.requires_grad
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_transformer.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import torch
3
+ from ef_vfm.modules.transformer import Transformer
4
+
5
+
6
+ def test_output_shape_preserved(make_transformer):
7
+ t = make_transformer(d_token=16, n_layers=2)
8
+ x = torch.randn(4, 5, 16)
9
+ out = t(x)
10
+ assert out.shape == x.shape
11
+
12
+
13
+ def test_activation_gelu(make_transformer):
14
+ t = make_transformer(d_token=16, activation='gelu')
15
+ x = torch.randn(4, 5, 16)
16
+ out = t(x)
17
+ assert out.shape == x.shape
18
+
19
+
20
+ def test_activation_silu(make_transformer):
21
+ t = make_transformer(d_token=16, activation='silu')
22
+ x = torch.randn(4, 5, 16)
23
+ out = t(x)
24
+ assert out.shape == x.shape
25
+
26
+
27
+ def test_activation_relu(make_transformer):
28
+ t = make_transformer(d_token=16, activation='relu')
29
+ x = torch.randn(4, 5, 16)
30
+ out = t(x)
31
+ assert out.shape == x.shape
32
+
33
+
34
+ def test_invalid_activation_raises():
35
+ with pytest.raises(ValueError, match="Unknown activation"):
36
+ Transformer(2, 16, 1, 16, 4, activation='bad')
37
+
38
+
39
+ def test_prenorm_first_layer_no_norm0():
40
+ t = Transformer(2, 16, 1, 16, 4, prenormalization=True)
41
+ assert 'norm0' not in t.layers[0]
42
+ # Second layer should have norm0
43
+ assert 'norm0' in t.layers[1]
44
+
45
+
46
+ def test_no_prenorm_all_layers_have_norm0():
47
+ t = Transformer(2, 16, 1, 16, 4, prenormalization=False)
48
+ for layer in t.layers:
49
+ assert 'norm0' in layer
50
+
51
+
52
+ def test_single_layer():
53
+ t = Transformer(1, 16, 1, 16, 4)
54
+ x = torch.randn(4, 5, 16)
55
+ out = t(x)
56
+ assert out.shape == x.shape
57
+
58
+
59
+ def test_multi_layer():
60
+ t = Transformer(4, 16, 1, 16, 4)
61
+ x = torch.randn(4, 5, 16)
62
+ out = t(x)
63
+ assert out.shape == x.shape
64
+
65
+
66
+ def test_gradient_flows(make_transformer):
67
+ t = make_transformer(d_token=16, n_layers=2)
68
+ x = torch.randn(4, 5, 16, requires_grad=True)
69
+ out = t(x)
70
+ out.sum().backward()
71
+ assert x.grad is not None and x.grad.abs().sum() > 0
72
+ # Check gradients through at least the first layer's linear0
73
+ assert t.layers[0]['linear0'].weight.grad is not None
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_unimodmlp.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+
4
+
5
+ def test_forward_shapes_mixed(make_unimodmlp, make_dummy_inputs, dims):
6
+ d = dims
7
+ model = make_unimodmlp(d["d_numerical"], d["categories"], d_token=d["d_token"])
8
+ x_num, x_cat_oh, _, t = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"])
9
+ x_num_pred, x_cat_pred = model(x_num, x_cat_oh, t)
10
+ assert x_num_pred.shape == (d["batch_size"], d["d_numerical"])
11
+ assert x_cat_pred.shape == (d["batch_size"], sum(d["categories"]))
12
+
13
+
14
+ def test_forward_shapes_numerical_only(make_unimodmlp, make_dummy_inputs, dims_numerical_only):
15
+ d = dims_numerical_only
16
+ model = make_unimodmlp(d["d_numerical"], d["categories"], d_token=d["d_token"])
17
+ x_num, _, _, t = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"])
18
+ x_cat = torch.zeros(d["batch_size"], 0)
19
+ x_num_pred, x_cat_pred = model(x_num, x_cat, t)
20
+ assert x_num_pred.shape == (d["batch_size"], d["d_numerical"])
21
+ # When no categories, cat_pred should be zeros with shape matching x_cat
22
+ assert x_cat_pred.shape[0] == d["batch_size"]
23
+ assert torch.all(x_cat_pred == 0)
24
+
25
+
26
+ def test_forward_shapes_single_feature(make_unimodmlp, make_dummy_inputs, dims_single):
27
+ d = dims_single
28
+ model = make_unimodmlp(d["d_numerical"], d["categories"], d_token=d["d_token"])
29
+ x_num, x_cat_oh, _, t = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"])
30
+ x_num_pred, x_cat_pred = model(x_num, x_cat_oh, t)
31
+ assert x_num_pred.shape == (d["batch_size"], d["d_numerical"])
32
+ assert x_cat_pred.shape == (d["batch_size"], sum(d["categories"]))
33
+
34
+
35
+ def test_d_in_computation(make_unimodmlp, dims):
36
+ d = dims
37
+ model = make_unimodmlp(d["d_numerical"], d["categories"], d_token=d["d_token"])
38
+ expected = d["d_token"] * (d["d_numerical"] + len(d["categories"]))
39
+ assert model.mlp.proj.in_features == expected
40
+
41
+
42
+ def test_output_dtypes(make_unimodmlp, make_dummy_inputs, dims):
43
+ d = dims
44
+ model = make_unimodmlp(d["d_numerical"], d["categories"], d_token=d["d_token"])
45
+ x_num, x_cat_oh, _, t = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"])
46
+ x_num_pred, x_cat_pred = model(x_num, x_cat_oh, t)
47
+ assert x_num_pred.dtype == torch.float32
48
+ assert x_cat_pred.dtype == torch.float32
49
+
50
+
51
+ def test_gradient_flows_end_to_end(make_unimodmlp, make_dummy_inputs, dims):
52
+ d = dims
53
+ model = make_unimodmlp(d["d_numerical"], d["categories"], d_token=d["d_token"])
54
+ x_num, x_cat_oh, _, t = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"])
55
+ x_num_pred, x_cat_pred = model(x_num, x_cat_oh, t)
56
+ loss = x_num_pred.sum() + x_cat_pred.sum()
57
+ loss.backward()
58
+ params_with_grad = sum(1 for p in model.parameters() if p.grad is not None and p.grad.abs().sum() > 0)
59
+ total_params = sum(1 for _ in model.parameters())
60
+ # Transformer.head is defined but unused in forward(), so not all params get gradients
61
+ assert params_with_grad > total_params * 0.8, f"Only {params_with_grad}/{total_params} params got gradients"
62
+
63
+
64
+ def test_different_activations(make_unimodmlp, make_dummy_inputs, dims):
65
+ d = dims
66
+ x_num, x_cat_oh, _, t = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"])
67
+ for act in ['relu', 'gelu', 'silu']:
68
+ model = make_unimodmlp(d["d_numerical"], d["categories"], d_token=d["d_token"], activation=act)
69
+ x_num_pred, x_cat_pred = model(x_num, x_cat_oh, t)
70
+ assert x_num_pred.shape == (d["batch_size"], d["d_numerical"])
71
+ assert torch.isfinite(x_num_pred).all()
72
+ assert torch.isfinite(x_cat_pred).all()
syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_utils.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+
4
+ from utils_train import update_ema, concat_y_to_X
5
+
6
+
7
+ # ---- update_ema tests ----
8
+
9
+ def test_update_ema_basic():
10
+ target = [torch.tensor([1.0, 2.0])]
11
+ source = [torch.tensor([3.0, 4.0])]
12
+ target[0].requires_grad_(False)
13
+ rate = 0.9
14
+ update_ema(target, source, rate=rate)
15
+ expected = 0.9 * torch.tensor([1.0, 2.0]) + 0.1 * torch.tensor([3.0, 4.0])
16
+ assert torch.allclose(target[0], expected)
17
+
18
+
19
+ def test_update_ema_rate_zero():
20
+ target = [torch.tensor([1.0, 2.0])]
21
+ source = [torch.tensor([3.0, 4.0])]
22
+ target[0].requires_grad_(False)
23
+ update_ema(target, source, rate=0.0)
24
+ assert torch.allclose(target[0], torch.tensor([3.0, 4.0]))
25
+
26
+
27
+ def test_update_ema_rate_one():
28
+ target = [torch.tensor([1.0, 2.0])]
29
+ source = [torch.tensor([3.0, 4.0])]
30
+ target[0].requires_grad_(False)
31
+ update_ema(target, source, rate=1.0)
32
+ assert torch.allclose(target[0], torch.tensor([1.0, 2.0]))
33
+
34
+
35
+ # ---- concat_y_to_X tests ----
36
+
37
+ def test_concat_y_to_X_with_X():
38
+ X = np.array([[1, 2], [3, 4]])
39
+ y = np.array([10, 20])
40
+ result = concat_y_to_X(X, y)
41
+ expected = np.array([[10, 1, 2], [20, 3, 4]])
42
+ np.testing.assert_array_equal(result, expected)
43
+
44
+
45
+ def test_concat_y_to_X_without_X():
46
+ y = np.array([10, 20, 30])
47
+ result = concat_y_to_X(None, y)
48
+ expected = np.array([[10], [20], [30]])
49
+ np.testing.assert_array_equal(result, expected)