jialinzhang commited on
Commit ·
e2bf942
1
Parent(s): f1d7e19
Add syntheticFail n12
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/_tabbyflow_train.pyAdded+24
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/input_snapshot.jsonAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/public_gate/normalized_schema_snapshot.jsonAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/public_gate/public_gate_report.jsonAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/public_gate/staged_input_manifest.jsonAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/run_config.jsonAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/runtime_result.jsonAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/staged/public/staged_features.jsonAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/staged/public/test.csvAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/staged/public/train.csvAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/staged/public/val.csvAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/staged/tabbyflow/adapter_report.jsonAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/staged/tabbyflow/adapter_transforms_applied.jsonAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/staged/tabbyflow/model_input_manifest.jsonAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/X_num_test.npyAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/X_num_train.npyAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/X_num_val.npyAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/info.jsonAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/real.csvAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/staged_features.jsonAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/test.csvAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/train.csvAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/val.csvAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/y_test.npyAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/y_train.npyAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/y_val.npyAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/train_20260510_202730.logAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/.gitignoreAdded+174
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/LICENCEAdded+7
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/README.mdAdded+128
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/X_num_test.npyAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/X_num_train.npyAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/X_num_val.npyAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/info.jsonAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/real.csvAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/staged_features.jsonAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/test.csvAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/train.csvAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/val.csvAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/y_test.npyAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/y_train.npyAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/y_val.npyAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/download_dataset.pyAdded+49
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/ef_vfm/configs/ef_vfm_configs.tomlAdded+3
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/ef_vfm/main.pyAdded+246
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/ef_vfm/metrics.pyAdded+306
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/ef_vfm/models/flow_model.pyAdded+195
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/ef_vfm/modules/main_modules.pyAdded+102
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/ef_vfm/modules/transformer.pyAdded+269
- syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/ef_vfm/trainer.pyAdded+557
123456789101112131415161718192021222324
import os, shutil, subprocess, sysroot = r"/workspace/ef-vfm"name = r"pipeline_n12"src = r"/work/output-Benchmark-trainonly-v1/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12"os.makedirs(os.path.join(root, "data", name), exist_ok=True)dst_data = os.path.join(root, "data", name)dst_syn = os.path.join(root, "synthetic", name)shutil.rmtree(dst_data, ignore_errors=True)shutil.copytree(src, dst_data)os.makedirs(dst_syn, exist_ok=True)for fn in ("real.csv", "test.csv", "val.csv"): shutil.copy(os.path.join(src, fn), os.path.join(dst_syn, fn))os.chdir(root)os.environ["PYTHONPATH"] = root + os.pathsep + os.environ.get("PYTHONPATH", "")os.environ["EFVFM_SMOKE_STEPS"] = "100"os.environ["EFVFM_ADAPTER_TRAIN"] = "1"os.environ.setdefault("EFVFM_SAMPLE_BATCH_SIZE", "128")os.environ.setdefault("EFVFM_EVAL_NUM_SAMPLES", "512")subprocess.check_call([ sys.executable, "main.py", "--dataname", name, "--mode", "train", "--gpu", "0", "--no_wandb", "--exp_name", r"adapter_efvfm",])123version https://git-lfs.github.com/spec/v1oid sha256:a8d27ecb4984ffedf45030368b1733997f42cc4ed7064c057d4dc9c0058ac1bcsize 1362123version https://git-lfs.github.com/spec/v1oid sha256:f557e091384db0c72c9acb9ef1549554fc2a2d69f9990d9697104a90556b8a68size 1878123version https://git-lfs.github.com/spec/v1oid sha256:2669f797a1e70611d433ac20e4b082cf45938adaeb6f5fdc85dda5e18bcfaf48size 920123version https://git-lfs.github.com/spec/v1oid sha256:56d12b969fce443335acf214998f68507c8b6b57541505ff101cce5a924b00a5size 2714123version https://git-lfs.github.com/spec/v1oid sha256:8190b035cfbd91cd81fa24bff02704dd07deb16f8989992aa3664d024be9db92size 1828123version https://git-lfs.github.com/spec/v1oid sha256:5ea6e9d4204b05490b5d889c2429053bb0d99829dc9e13824673a19b0fbc59dasize 1108123version https://git-lfs.github.com/spec/v1oid sha256:148b95cbf4c3da3ebc38686f20ef1e724b56b701abfa24065d77f9b417e8671esize 382123version https://git-lfs.github.com/spec/v1oid sha256:4972eb2812d325c143ec99492afa470fe047141a9bdf34893ec0133a12b8dc26size 315789123version https://git-lfs.github.com/spec/v1oid sha256:728fec9c0ec06ca4b292989614be4374c308d9a15b1e0002c3daeb3a68d5d350size 2524420123version https://git-lfs.github.com/spec/v1oid sha256:8931c0b2402466ccca41868fc484ab4bc6f627d68422570b20d47d1104922959size 315663123version https://git-lfs.github.com/spec/v1oid sha256:6e069bbc16920549cfabcca64aed58d99bda2e2b66e754a3ca8df6f86192188dsize 329123version https://git-lfs.github.com/spec/v1oid sha256:4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945size 2123version https://git-lfs.github.com/spec/v1oid sha256:f7db846e94452ae99b58db74ee416e8c6de8fe7ae2d7e722ffbb96f651c322d1size 2919123version https://git-lfs.github.com/spec/v1oid sha256:c61438cf93c656fb5cb15eaf2307b9a6762caaac9767fc58fe2952aac45fc3f5size 294200123version https://git-lfs.github.com/spec/v1oid sha256:81c9f92b945e7c858dd597c0ca1c4214488b28e0235e7540729aaa6ac355e3d9size 2352668123version https://git-lfs.github.com/spec/v1oid sha256:54b84a34c98bec5e63d00e8383bffc55618cc35ca19227edb8002567851a456esize 294200123version https://git-lfs.github.com/spec/v1oid sha256:02559b8584b55130a4e5ba46c593a0ed67e2f2dc812b3591721763c9b1ad4d19size 1118123version https://git-lfs.github.com/spec/v1oid sha256:728fec9c0ec06ca4b292989614be4374c308d9a15b1e0002c3daeb3a68d5d350size 2524420123version https://git-lfs.github.com/spec/v1oid sha256:148b95cbf4c3da3ebc38686f20ef1e724b56b701abfa24065d77f9b417e8671esize 382123version https://git-lfs.github.com/spec/v1oid sha256:4972eb2812d325c143ec99492afa470fe047141a9bdf34893ec0133a12b8dc26size 315789123version https://git-lfs.github.com/spec/v1oid sha256:728fec9c0ec06ca4b292989614be4374c308d9a15b1e0002c3daeb3a68d5d350size 2524420123version https://git-lfs.github.com/spec/v1oid sha256:8931c0b2402466ccca41868fc484ab4bc6f627d68422570b20d47d1104922959size 315663123version https://git-lfs.github.com/spec/v1oid sha256:bf9f1e26e93a4ce529e1b2b19584b310c3dbfeb4710430cddd3ba8801a505a56size 98152123version https://git-lfs.github.com/spec/v1oid sha256:b3364a73bf996bb34a52618df06197d3b8d019bfa3f75ab7e43ed9e93ffb56efsize 784308123version https://git-lfs.github.com/spec/v1oid sha256:7871f5214b6bae4b8a0bfaf8c930995b30f34bca844dfd13c079556269d6f22dsize 98152123version https://git-lfs.github.com/spec/v1oid sha256:b420e7a0cff64b0aff02d3e4cb15755e3693c5ba390afb24bf2a680c104ca234size 1176123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174# Byte-compiled / optimized / DLL files__pycache__/*.py[cod]*$py.class
# C extensions*.so
# Distribution / packaging.Pythonbuild/develop-eggs/dist/downloads/eggs/.eggs/lib/lib64/parts/sdist/var/wheels/share/python-wheels/*.egg-info/.installed.cfg*.eggMANIFEST
# PyInstaller# Usually these files are written by a python script from a template# before PyInstaller builds the exe, so as to inject date/other infos into it.*.manifest*.spec
# Installer logspip-log.txtpip-delete-this-directory.txt
# Unit test / coverage reportshtmlcov/.tox/.nox/.coverage.coverage.*.cachenosetests.xmlcoverage.xml*.cover*.py,cover.hypothesis/.pytest_cache/cover/
# Translations*.mo*.pot
# Django stuff:*.loglocal_settings.pydb.sqlite3db.sqlite3-journal
# Flask stuff:instance/.webassets-cache
# Scrapy stuff:.scrapy
# Sphinx documentationdocs/_build/
# PyBuilder.pybuilder/target/
# Jupyter Notebook.ipynb_checkpoints
# IPythonprofile_default/ipython_config.py
# pyenv# For a library or package, you might want to ignore these files since the code is# intended to run in multiple environments; otherwise, check them in:# .python-version
# pipenv# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.# However, in case of collaboration, if having platform-specific dependencies or dependencies# having no cross-platform support, pipenv may install dependencies that don't work, or not# install all needed dependencies.#Pipfile.lock
# poetry# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.# This is especially recommended for binary packages to ensure reproducibility, and is more# commonly ignored for libraries.# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control#poetry.lock
# pdm# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.#pdm.lock# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it# in version control.# https://pdm.fming.dev/latest/usage/project/#working-with-version-control.pdm.toml.pdm-python.pdm-build/
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm__pypackages__/
# Celery stuffcelerybeat-schedulecelerybeat.pid
# SageMath parsed files*.sage.py
# Environments.env.venvenv/venv/ENV/env.bak/venv.bak/
# Spyder project settings.spyderproject.spyproject
# Rope project settings.ropeproject
# mkdocs documentation/site
# mypy.mypy_cache/.dmypy.jsondmypy.json
# Pyre type checker.pyre/
# pytype static type analyzer.pytype/
# Cython debug symbolscython_debug/
# PyCharm# JetBrains specific template is maintained in a separate JetBrains.gitignore that can# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore# and can be added to the global gitignore or merged into this file. For a more nuclear# option (not recommended) you can uncomment the following to ignore the entire idea folder.#.idea/
.DS_Store# data/adultdata/beijingdata/defaultdata/magicdata/newsdata/shoppers
wandb/
*.DS_Store1234567Copyright 2024 Andrés Guzmán-Cordero
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:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
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.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128# Exponential Family Variational Flow Matching for Tabular Data Generation
<p align="center"> <a href="https://github.com/andresguzco/ef-vfm/blob/main/LICENSE.txt"> <img alt="MIT License" src="https://img.shields.io/badge/License-MIT-yellow.svg"> </a> <a href="https://openreview.net/pdf?id=kjtvCSkSsy"> <img alt="Openreview" src="https://img.shields.io/badge/review-OpenReview-blue"> </a> <a href="https://arxiv.org/pdf/2506.05940"> <img alt="Paper URL" src="https://img.shields.io/badge/cs.LG-2506.05940-B31B1B.svg"> </a></p>
<div align="center"> <img src="images/demo.jpg" alt="Model Logo" width="800" style="margin-left:'auto' margin-right:'auto' display:'block'"/> <p><em> Figure 1: Exponential Family Variational Flow Matching (EF-VFM) is a generative modeling framework designed for mixed continuousand discrete variables. By leveraging the exponential family and a mean-field assumption, EF-VFM efficiently matches the sufficientstatistics of the distributions via learned probability paths, ensuring state-of-the-art fidelity and diversity in synthetic data.</a></em></p></div>
This repository provides the prototypical implementation of EF-VFM: TabbyFlow (ICML, 2025).
## Latest Update
- [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!
## Introduction
EF-VFM uses the exponential family to jointly model different distributions with a single variational flow matching framework. Its key contributions are:
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.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.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.
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).
## Environment Setup
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)
```conda env create -f ef_vfm.yaml```
Create another environment with [synthcity.yaml](synthcity.yaml) to evaluate additional data fidelity metrics
```conda env create -f synthcity.yaml```
## Datasets Preparation
### Using the datasets experimented in the paper
Download raw datasets:
```python download_dataset.py```
Process datasets:
```python process_dataset.py```
## Training TabbyFlow
To train an unconditional EF-VFM model across the entire table, run
```python main.py --dataname <NAME_OF_DATASET> --mode train --exp_name <EXP_NAME>```
where ```<NAME_OF_DATASET>``` is the name of the dataset you want to train on, and ```<EXP_NAME>``` is the name of your experiment.
Current Options of ```<NAME_OF_DATASET>``` are: adult, default, shoppers, magic, beijing, news
Wanb logging is enabled by default. To disable it and log locally, add the ```--no_wandb``` flag.
You must specify the experiment name, which will be used for logging and saving files, add ```--exp_name <your experiment name>```.
## Sampling and Evaluating TabbyFlow (Density, MLE, C2ST)
To sample synthetic tables from trained EF-VFM models and evaluate them, run
```python main.py --dataname <NAME_OF_DATASET> --mode test --report --no_wandb --exp_name <EXP_NAME>```
where ```<NAME_OF_DATASET>``` and ```<EXP_NAME>``` should be the same as those used in training.
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>/.
## Evaluating on Additional Fidelity Metrics ($\alpha$-precision and $\beta$-recall scores)
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
```conda activate synthcity```
Then, evaluate the metrics by running
```python eval/eval_quality.py --dataname <NAME_OF_DATASET>```
Similarly, the results will be printed out in the terminal and added to ./eval/report_runs/<EXP_NAME>/<NAME_OF_DATASET>/
## Evaluating Data Privacy (DCR score)
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>```
```python main.py --dataname <NAME_OF_DATASET>_dcr --mode train```
Then, test the models on DCR with the same `_dcr` suffix
```python main.py --dataname <NAME_OF_DATASET>_dcr --mode test --report --no_wandb```
## License
This work is licensed under the MIT License.
## Acknowledgement
This repo is built upon the previous work TabDiff's [[codebase]](https://github.com/MinkaiXu/TabDiff). Many thanks to Juntong, Minkai, Harper and Hengrui!
## Citation
```@inproceedings{guzmancordero2025exponentialfamily,title={Exponential Family Variational Flow Matching for Tabular Data Generation},author={Andr\'es Guzm\'an-Cordero and Floor Eijkelboom and Jan-Willem van de Meent},booktitle={The Forty-Second International Conference on Machine Learning},year={2025},url={https://openreview.net/forum?id=kjtvCSkSsy}}```
## Contact
If you encounter any problem or you have any question regarding the paper, please contact [Andrés](andresguzco@gmail.com).123version https://git-lfs.github.com/spec/v1oid sha256:c61438cf93c656fb5cb15eaf2307b9a6762caaac9767fc58fe2952aac45fc3f5size 294200123version https://git-lfs.github.com/spec/v1oid sha256:81c9f92b945e7c858dd597c0ca1c4214488b28e0235e7540729aaa6ac355e3d9size 2352668123version https://git-lfs.github.com/spec/v1oid sha256:54b84a34c98bec5e63d00e8383bffc55618cc35ca19227edb8002567851a456esize 294200123version https://git-lfs.github.com/spec/v1oid sha256:5b8d53efcd8f5ad02da9415b33fbe1ab53bfed7a191ed60ddec769dbedd1b12dsize 1092123version https://git-lfs.github.com/spec/v1oid sha256:728fec9c0ec06ca4b292989614be4374c308d9a15b1e0002c3daeb3a68d5d350size 2524420123version https://git-lfs.github.com/spec/v1oid sha256:148b95cbf4c3da3ebc38686f20ef1e724b56b701abfa24065d77f9b417e8671esize 382123version https://git-lfs.github.com/spec/v1oid sha256:4972eb2812d325c143ec99492afa470fe047141a9bdf34893ec0133a12b8dc26size 315789123version https://git-lfs.github.com/spec/v1oid sha256:728fec9c0ec06ca4b292989614be4374c308d9a15b1e0002c3daeb3a68d5d350size 2524420123version https://git-lfs.github.com/spec/v1oid sha256:8931c0b2402466ccca41868fc484ab4bc6f627d68422570b20d47d1104922959size 315663123version https://git-lfs.github.com/spec/v1oid sha256:587fd6fe2d75caab988288d939395769ac7ea8c41a0938041ae5250bcf5e7351size 196176123version https://git-lfs.github.com/spec/v1oid sha256:287f6835c6d89c1245143b25166673da2a55377c2ca2ead7f5bbc0e34cc03c1bsize 1568488123version https://git-lfs.github.com/spec/v1oid sha256:693dcf53a187d58d619d0193dd178f117a2f1e98296ea30d8cb5bc8dd9d48647size 19617612345678910111213141516171819202122232425262728293031323334353637383940414243444546474849import osfrom urllib import requestimport zipfile
DATA_DIR = 'data'
NAME_URL_DICT_UCI = { 'adult': 'https://archive.ics.uci.edu/static/public/2/adult.zip', 'default': 'https://archive.ics.uci.edu/static/public/350/default+of+credit+card+clients.zip', 'magic': 'https://archive.ics.uci.edu/static/public/159/magic+gamma+telescope.zip', 'shoppers': 'https://archive.ics.uci.edu/static/public/468/online+shoppers+purchasing+intention+dataset.zip', 'beijing': 'https://archive.ics.uci.edu/static/public/381/beijing+pm2+5+data.zip', 'news': 'https://archive.ics.uci.edu/static/public/332/online+news+popularity.zip', 'news_nocat': 'https://archive.ics.uci.edu/static/public/332/online+news+popularity.zip', 'adult_dcr': 'https://archive.ics.uci.edu/static/public/2/adult.zip', 'default_dcr': 'https://archive.ics.uci.edu/static/public/350/default+of+credit+card+clients.zip', 'magic_dcr': 'https://archive.ics.uci.edu/static/public/159/magic+gamma+telescope.zip', 'shoppers_dcr': 'https://archive.ics.uci.edu/static/public/468/online+shoppers+purchasing+intention+dataset.zip', 'beijing_dcr': 'https://archive.ics.uci.edu/static/public/381/beijing+pm2+5+data.zip', 'news_dcr': 'https://archive.ics.uci.edu/static/public/332/online+news+popularity.zip',}
def unzip_file(zip_filepath, dest_path): with zipfile.ZipFile(zip_filepath, 'r') as zip_ref: zip_ref.extractall(dest_path)
def download_from_uci(name):
print(f'Start processing dataset {name} from UCI.') save_dir = f'{DATA_DIR}/{name}' if not os.path.exists(save_dir): os.makedirs(save_dir)
url = NAME_URL_DICT_UCI[name] request.urlretrieve(url, f'{save_dir}/{name}.zip') print(f'Finish downloading dataset from {url}, data has been saved to {save_dir}.') unzip_file(f'{save_dir}/{name}.zip', save_dir) print(f'Finish unzipping {name}.') else: print('Aready downloaded.')
if __name__ == '__main__': for name in NAME_URL_DICT_UCI.keys(): download_from_uci(name) 123version https://git-lfs.github.com/spec/v1oid sha256:677698232b3ea325b54527cccdc11c49fadb971129a77065e71d64aa7567ddb6size 674123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246import globimport jsonimport osimport pickleimport random
import numpy as npfrom ef_vfm.metrics import TabMetricsfrom ef_vfm.modules.main_modules import UniModMLPfrom ef_vfm.models.flow_model import ExpVFMfrom ef_vfm.trainer import Trainerimport srcimport torch
from torch.utils.data import DataLoaderimport argparseimport warnings
import wandb
from utils_train import EFVFMDataset
warnings.filterwarnings('ignore')
def main(args): device = args.device
## Disable scientific numerical format np.set_printoptions(suppress=True) torch.set_printoptions(sci_mode=False)
## Get data info dataname = args.dataname data_dir = f'data/{dataname}' info_path = f'data/{dataname}/info.json' with open(info_path, 'r') as f: info = json.load(f) ## Set up flags is_dcr = 'dcr' in dataname
## Set experiment name exp_name = args.exp_name assert args.exp_name is not None, "Experiment name must be provided" ## Load configs curr_dir = os.path.dirname(os.path.abspath(__file__)) config_path = f'{curr_dir}/configs/ef_vfm_configs.toml' raw_config = src.load_config(config_path) print(f"{args.mode.capitalize()} Mode is Enabled") num_samples_to_generate = None ckpt_path = None if args.mode == 'train': print("NEW training is started") elif args.mode == 'test': num_samples_to_generate = args.num_samples_to_generate ckpt_path = args.ckpt_path if ckpt_path is None: ckpt_parent_path = f"{curr_dir}/ckpt/{dataname}/{exp_name}" ckpt_path_arr = glob.glob(f"{ckpt_parent_path}/best_ema_model*") 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!" ckpt_path = ckpt_path_arr[0] config_path = os.path.join(os.path.dirname(ckpt_path), 'config.pkl') if os.path.exists(config_path): with open(config_path, 'rb') as f: cached_raw_config = pickle.load(f) print(f"Found cached config at {config_path}") raw_config = cached_raw_config ## Creat model_save and result paths model_save_path, result_save_path = None, None if args.mode == 'train': model_save_path = 'debug/ckpt' if args.debug else f'{curr_dir}/ckpt/{dataname}/{exp_name}' result_save_path = model_save_path.replace('ckpt', 'result') #i.e., f'{curr_dir}/results/{dataname}/{exp_name}' elif args.mode == 'test': if args.report: result_save_path = f"eval/report_runs/{exp_name}/{dataname}" else: result_save_path = os.path.dirname(ckpt_path).replace('ckpt', 'result') # infer the exp_name from the ckpt_name raw_config['model_save_path'] = model_save_path raw_config['result_save_path'] = result_save_path if model_save_path is not None: if not os.path.exists(model_save_path): os.makedirs(model_save_path) if result_save_path is not None: if not os.path.exists(result_save_path): os.makedirs(result_save_path) ## Make everything determinstic if needed raw_config['deterministic'] = args.deterministic if args.deterministic: print("DETERMINISTIC MODE is enabled!!!") ## Set global random seeds torch.manual_seed(0) random.seed(0) np.random.seed(0)
## Ensure deterministic CUDA operations os.environ['PYTHONHASHSEED'] = '0' os.environ['CUBLAS_WORKSPACE_CONFIG'] = ':4096:8' # or ':16:8' torch.use_deterministic_algorithms(True) if torch.cuda.is_available(): torch.cuda.manual_seed(0) torch.cuda.manual_seed_all(0) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False ## Set debug mode parameters if args.debug: # fast eval for DEBUG mode raw_config['train']['main']['check_val_every'] = 2 raw_config['train']['main']['batch_size'] = 4096 raw_config['sample']['batch_size'] = 10000
_smoke = os.environ.get("EFVFM_SMOKE_STEPS", "").strip() if _smoke and args.mode == "train": n = max(1, int(_smoke)) raw_config["train"]["main"]["steps"] = n raw_config["train"]["main"]["check_val_every"] = max( 1, min(n, raw_config["train"]["main"]["check_val_every"]) ) if os.environ.get("EFVFM_ADAPTER_TRAIN", "").strip() and args.mode == "train": raw_config["train"]["main"]["check_val_every"] = int(raw_config["train"]["main"]["steps"])
_sample_batch = os.environ.get("EFVFM_SAMPLE_BATCH_SIZE", "").strip() if _sample_batch: raw_config["sample"]["batch_size"] = max(1, int(_sample_batch)) _train_workers = os.environ.get("EFVFM_TRAIN_NUM_WORKERS", "").strip() train_num_workers = max(0, int(_train_workers)) if _train_workers else 4
## Load training data batch_size = raw_config['train']['main']['batch_size']
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']) train_loader = DataLoader( train_data, batch_size = batch_size, shuffle = True, num_workers = train_num_workers, ) d_numerical, categories = train_data.d_numerical, train_data.categories 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'])
## Load Metrics real_data_path = f'synthetic/{dataname}/real.csv' test_data_path = f'synthetic/{dataname}/test.csv' val_data_path = f'synthetic/{dataname}/val.csv' if not os.path.exists(val_data_path): print(f"{args.dataname} does not have its validation set. During MLE evaluation, a validation set will be splitted from the training set!") val_data_path = None if args.mode == 'train': metric_list = ["density"] else: if is_dcr: metric_list = ["dcr"] else: metric_list = [ "density", "mle", "c2st", ] metrics = TabMetrics(real_data_path, test_data_path, val_data_path, info, device, metric_list=metric_list) ## Load the module and models raw_config['unimodmlp_params']['d_numerical'] = d_numerical raw_config['unimodmlp_params']['categories'] = (categories).tolist() model = UniModMLP(**raw_config['unimodmlp_params']) model.to(device) flow_model = ExpVFM( num_classes=categories, num_numerical_features=d_numerical, vf_fn=model, device=device, ) num_params = sum(p.numel() for p in flow_model.parameters()) print("The number of parameters = ", num_params) flow_model.to(device) flow_model.train()
## Print the configs printed_configs = json.dumps(raw_config, default=lambda x: int(x) if isinstance(x, np.int64) else x, indent=4) print(f"The config of the current run is : \n {printed_configs}") ## Enable Wandb project_name = f"XVFM_{dataname}" raw_config['project_name'] = project_name logger = wandb.init( project=raw_config['project_name'], name=exp_name, config=raw_config, mode='disabled' if args.debug or args.no_wandb else 'online', )
## Load Trainer sample_batch_size = raw_config['sample']['batch_size'] trainer = Trainer( flow_model, train_loader, train_data, val_data, metrics, logger, **raw_config['train']['main'], sample_batch_size=sample_batch_size, num_samples_to_generate=num_samples_to_generate, model_save_path=raw_config['model_save_path'], result_save_path=raw_config['result_save_path'], device=device, ckpt_path=ckpt_path, ) if args.mode == 'test': if args.report: if is_dcr: trainer.report_test_dcr(args.num_runs) else: trainer.report_test(args.num_runs) else: trainer.test() else: ## Save config config_save_path = raw_config['model_save_path'] with open (os.path.join(config_save_path, 'config.pkl'), 'wb') as f: pickle.dump(raw_config, f) trainer.run_loop()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Training of TabbyFlow')
parser.add_argument('--dataname', type=str, default='adult', help='Name of dataset.') parser.add_argument('--gpu', type=int, default=0, help='GPU index.')
args = parser.parse_args()
# check cuda if args.gpu != -1 and torch.cuda.is_available(): args.device = f'cuda:{args.gpu}' else: args.device = 'cpu'123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306from copy import deepcopyimport numpy as npimport torchimport pandas as pd# Metricsfrom eval.mle.mle import get_evaluatorfrom eval.visualize_density import plot_densityfrom sdmetrics.reports.single_table import QualityReport, DiagnosticReportfrom sdmetrics.single_table import LogisticDetectionfrom sklearn.preprocessing import OneHotEncoder
from tqdm import tqdm
class TabMetrics(object): def __init__(self, real_data_path, test_data_path, val_data_path, info, device, metric_list) -> None: self.real_data_path = real_data_path self.test_data_path = test_data_path self.val_data_path = val_data_path self.info = info self.device = device self.real_data_size = len(pd.read_csv(real_data_path)) self.metric_list = metric_list
def evaluate(self, syn_data): metrics, extras = {}, {} syn_data_cp = deepcopy(syn_data) for metric in self.metric_list: func = eval(f"self.evaluate_{metric}") print(f"Evaluating {metric}") out_metrics, out_extras = func(syn_data_cp) metrics.update(out_metrics) extras.update(out_extras) return metrics, extras def evaluate_density(self, syn_data): real_data = pd.read_csv(self.real_data_path) real_data.columns = range(len(real_data.columns)) syn_data.columns = range(len(syn_data.columns))
info = deepcopy(self.info) y_only = len(syn_data.columns)==1 if y_only: target_col_idx = info['target_col_idx'][0] syn_data = self.complete_y_only_data(syn_data, real_data, target_col_idx)
metadata = info['metadata'] metadata['columns'] = {int(key): value for key, value in metadata['columns'].items()} # ensure that keys are all integers?
new_real_data, new_syn_data, metadata = reorder(real_data, syn_data, info)
qual_report = QualityReport() qual_report.generate(new_real_data, new_syn_data, metadata)
diag_report = DiagnosticReport() diag_report.generate(new_real_data, new_syn_data, metadata)
quality = qual_report.get_properties() diag = diag_report.get_properties()
Shape = quality['Score'][0] Trend = quality['Score'][1]
Overall = (Shape + Trend) / 2
shape_details = qual_report.get_details(property_name='Column Shapes') trend_details = qual_report.get_details(property_name='Column Pair Trends')
if y_only: Shape = shape_details['Score'].min() out_metrics = { "density/Shape": Shape, "density/Trend": Trend, "density/Overall": Overall, } out_extras = { "shapes": shape_details, "trends": trend_details } return out_metrics, out_extras def evaluate_mle(self, syn_data): train = syn_data.to_numpy() test = pd.read_csv(self.test_data_path).to_numpy() val = pd.read_csv(self.val_data_path).to_numpy() if self.val_data_path else None info = deepcopy(self.info)
task_type = info['task_type']
evaluator = get_evaluator(task_type)
if task_type == 'regression': best_r2_scores, best_rmse_scores = evaluator(train, test, info, val=val) overall_scores = {} for score_name in ['best_r2_scores', 'best_rmse_scores']: overall_scores[score_name] = {} scores = eval(score_name) for method in scores: name = method['name'] method.pop('name') overall_scores[score_name][name] = method
else: best_f1_scores, best_weighted_scores, best_auroc_scores, best_acc_scores, best_avg_scores = evaluator(train, test, info, val=val)
overall_scores = {} for score_name in ['best_f1_scores', 'best_weighted_scores', 'best_auroc_scores', 'best_acc_scores', 'best_avg_scores']: overall_scores[score_name] = {} scores = eval(score_name) for method in scores: name = method['name'] method.pop('name') overall_scores[score_name][name] = method mle_score = overall_scores['best_rmse_scores']['XGBRegressor']['RMSE'] if task_type == 'regression' else overall_scores['best_auroc_scores']['XGBClassifier']['roc_auc'] out_metrics = { "mle": mle_score, } out_extras = { "mle": overall_scores, } return out_metrics, out_extras def evaluate_c2st(self, syn_data): info = deepcopy(self.info) real_data = pd.read_csv(self.real_data_path)
real_data.columns = range(len(real_data.columns)) syn_data.columns = range(len(syn_data.columns))
metadata = info['metadata'] metadata['columns'] = {int(key): value for key, value in metadata['columns'].items()}
new_real_data, new_syn_data, metadata = reorder(real_data, syn_data, info)
score = LogisticDetection.compute( real_data=new_real_data, synthetic_data=new_syn_data, metadata=metadata ) out_metrics = { "c2st": score, } out_extras = {} return out_metrics, out_extras
def evaluate_dcr(self, syn_data): info = deepcopy(self.info) real_data = pd.read_csv(self.real_data_path) test_data = pd.read_csv(self.test_data_path) num_col_idx = info['num_col_idx'] cat_col_idx = info['cat_col_idx'] target_col_idx = info['target_col_idx']
task_type = info['task_type'] if task_type == 'regression': num_col_idx += target_col_idx else: cat_col_idx += target_col_idx
num_ranges = []
real_data.columns = list(np.arange(len(real_data.columns))) syn_data.columns = list(np.arange(len(real_data.columns))) test_data.columns = list(np.arange(len(real_data.columns))) for i in num_col_idx: num_ranges.append(real_data[i].max() - real_data[i].min()) num_ranges = np.array(num_ranges)
num_real_data = real_data[num_col_idx] cat_real_data = real_data[cat_col_idx] num_syn_data = syn_data[num_col_idx] cat_syn_data = syn_data[cat_col_idx] num_test_data = test_data[num_col_idx] cat_test_data = test_data[cat_col_idx]
num_real_data_np = num_real_data.to_numpy() cat_real_data_np = cat_real_data.to_numpy().astype('str') num_syn_data_np = num_syn_data.to_numpy() cat_syn_data_np = cat_syn_data.to_numpy().astype('str') num_test_data_np = num_test_data.to_numpy() cat_test_data_np = cat_test_data.to_numpy().astype('str')
encoder = OneHotEncoder() cat_complete_data_np = np.concatenate([cat_real_data_np, cat_test_data_np], axis=0) encoder.fit(cat_complete_data_np) # encoder.fit(cat_real_data_np)
cat_real_data_oh = encoder.transform(cat_real_data_np).toarray() cat_syn_data_oh = encoder.transform(cat_syn_data_np).toarray() cat_test_data_oh = encoder.transform(cat_test_data_np).toarray()
num_real_data_np = num_real_data_np / num_ranges num_syn_data_np = num_syn_data_np / num_ranges num_test_data_np = num_test_data_np / num_ranges
real_data_np = np.concatenate([num_real_data_np, cat_real_data_oh], axis=1) syn_data_np = np.concatenate([num_syn_data_np, cat_syn_data_oh], axis=1) test_data_np = np.concatenate([num_test_data_np, cat_test_data_oh], axis=1)
device = self.device
real_data_th = torch.tensor(real_data_np).to(device) syn_data_th = torch.tensor(syn_data_np).to(device) test_data_th = torch.tensor(test_data_np).to(device)
dcrs_real = [] dcrs_test = [] 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
for i in tqdm(range((syn_data_th.shape[0] // batch_size) + 1)): if i != (syn_data_th.shape[0] // batch_size): batch_syn_data_th = syn_data_th[i*batch_size: (i+1) * batch_size] else: batch_syn_data_th = syn_data_th[i*batch_size:] dcr_real = (batch_syn_data_th[:, None] - real_data_th).abs().sum(dim = 2).min(dim = 1).values dcr_test = (batch_syn_data_th[:, None] - test_data_th).abs().sum(dim = 2).min(dim = 1).values dcrs_real.append(dcr_real) dcrs_test.append(dcr_test) dcrs_real = torch.cat(dcrs_real) dcrs_test = torch.cat(dcrs_test) score = (dcrs_real < dcrs_test).nonzero().shape[0] / dcrs_real.shape[0] out_metrics = { "dcr": score, } out_extras = { "dcr_real": dcrs_real.cpu().numpy(), "dcr_test": dcrs_test.cpu().numpy(), } return out_metrics, out_extras def plot_density(self, syn_data): syn_data_cp = deepcopy(syn_data) real_data = pd.read_csv(self.real_data_path) info = deepcopy(self.info) y_only = len(syn_data_cp.columns)==1 if y_only: target_col_idx = info['target_col_idx'][0] target_col_name = info['column_names'][target_col_idx] syn_data_cp = self.complete_y_only_data(syn_data_cp, real_data, target_col_name) img = plot_density(syn_data_cp, real_data, info) return img def complete_y_only_data(self, syn_data, real_data, target_col_idx): syn_target_col = deepcopy(syn_data.iloc[:, 0]) syn_data = deepcopy(real_data) syn_data[target_col_idx] = syn_target_col return syn_data
def reorder(real_data, syn_data, info): num_col_idx = deepcopy(info['num_col_idx']) # BUG: info will be modified by += in the next few lines cat_col_idx = deepcopy(info['cat_col_idx']) target_col_idx = deepcopy(info['target_col_idx'])
task_type = info['task_type'] if task_type == 'regression': num_col_idx += target_col_idx else: cat_col_idx += target_col_idx
real_num_data = real_data[num_col_idx] real_cat_data = real_data[cat_col_idx]
new_real_data = pd.concat([real_num_data, real_cat_data], axis=1) new_real_data.columns = range(len(new_real_data.columns))
syn_num_data = syn_data[num_col_idx] syn_cat_data = syn_data[cat_col_idx] new_syn_data = pd.concat([syn_num_data, syn_cat_data], axis=1) new_syn_data.columns = range(len(new_syn_data.columns))
metadata = info['metadata']
columns = metadata['columns'] metadata['columns'] = {}
inverse_idx_mapping = info['inverse_idx_mapping']
for i in range(len(new_real_data.columns)): if i < len(num_col_idx): metadata['columns'][i] = columns[num_col_idx[i]] else: metadata['columns'][i] = columns[cat_col_idx[i-len(num_col_idx)]]
return new_real_data, new_syn_data, metadata123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195import torch.nn.functional as Fimport torchimport numpy as npfrom torchdiffeq import odeint_adjoint as odeint
class ExpVFM(torch.nn.Module): def __init__( self, num_classes: np.array, num_numerical_features: int, vf_fn, device=torch.device('cpu'), **kwargs ):
super(ExpVFM, self).__init__()
self.num_numerical_features = num_numerical_features self.num_classes = num_classes # it as a vector [K1, K2, ..., Km] self.num_classes_expanded = torch.from_numpy( np.concatenate([num_classes[i].repeat(num_classes[i]) for i in range(len(num_classes))]) ).to(device) if len(num_classes)>0 else torch.tensor([]).to(device).int() self.neg_infinity = -1000000.0
offsets = np.cumsum(self.num_classes) offsets = np.append([0], offsets) self.slices_for_classes = [] for i in range(1, len(offsets)): self.slices_for_classes.append(np.arange(offsets[i - 1], offsets[i])) self.offsets = torch.from_numpy(offsets).to(device) offsets = np.cumsum(self.num_classes) + np.arange(1, len(self.num_classes)+1) offsets = np.append([0], offsets)
self._vf_fn = vf_fn self.device = device
def mixed_loss(self, x): b = x.shape[0] dev = x.device
x_num = x[:, :self.num_numerical_features] x_cat = x[:, self.num_numerical_features:].long()
t = torch.rand(b, device=dev, dtype=x_num.dtype) t = t[:, None] # Continuous interpolation x_num_t = x_num if x_num.shape[1] > 0: noise = torch.randn_like(x_num) x_num_t = t * x_num + (1 - t) * noise # + noise * sigma_num # Discrete interpolation x_cat_oh = self.to_one_hot(x_cat).float() x_cat_t = x_cat_oh if x_cat.shape[1] > 0: x_cat_t = t * x_cat_oh + (1 - t) * torch.randn_like(x_cat_oh)
# Predict orignal data (distribution) model_out_num, model_out_cat = self._vf_fn(x_num_t, x_cat_t, t.squeeze())
d_loss = torch.zeros((1,)).float() c_loss = torch.zeros((1,)).float()
# Compute the loss if x_num.shape[1] > 0: c_loss = self._mvgloss(model_out_num, x_num, t)
if x_cat.shape[1] > 0: d_loss = self._absorbed_closs(model_out_cat, x_cat, self._vf_fn.categories) return d_loss.mean(), c_loss.mean() def _mvgloss(self, mu_t, x_num_t, t): n, k = mu_t.shape dev = mu_t.device dt = mu_t.dtype
identity = torch.eye(k, device=dev, dtype=dt).unsqueeze(0).expand(n, -1, -1) scale = 1 - (1 - 0.01) * t.unsqueeze(1) ** 2 sigma = scale * identity dist = torch.distributions.MultivariateNormal(mu_t, sigma) return -dist.log_prob(x_num_t).mean()
@torch.no_grad() def sample(self, num_samples): dev = self.device dt = torch.float32 d_in = self.num_numerical_features + sum(self.num_classes) d_out = self.num_numerical_features + len(self.num_classes)
x0 = torch.randn(num_samples, d_in, device=dev) t = torch.tensor([0.0, 0.999]).to(dev) vf = Velocity(self._vf_fn) trajectory = odeint(vf, x0, t, method="dopri5", rtol=1e-5, atol=1e-5) out = trajectory[1]
sample = torch.zeros(num_samples, d_out, device=dev, dtype=dt) sample[:, :self.num_numerical_features] = out[:, :self.num_numerical_features].to(torch.float32) if sum(self.num_classes) != 0: idx = self.num_numerical_features for i, val in enumerate(self.num_classes): col = self.num_numerical_features + i sample[:, col] = torch.argmax(out[:, idx:idx + val], dim=1) idx += val assert val >= sample[:, col].max() >= 0, f"Sampled value {sample[:, col].max()} is out of range for categorical feature {i} with {val} classes."
return sample.cpu() def sample_all(self, num_samples, batch_size, keep_nan_samples=False): b = batch_size
all_samples = [] num_generated = 0 while num_generated < num_samples: print(f"Samples left to generate: {num_samples-num_generated}") sample = self.sample(b) mask_nan = torch.any(sample.isnan(), dim=1) if keep_nan_samples: # If the sample instances that contains Nan are decided to be kept, the row with Nan will be foreced to all zeros sample = sample * (~mask_nan)[:, None] else: # Otherwise the instances with Nan will be eliminated sample = sample[~mask_nan]
all_samples.append(sample) num_generated += sample.shape[0]
x_gen = torch.cat(all_samples, dim=0)[:num_samples]
return x_gen
def to_one_hot(self, x_cat): if len(self.num_classes) == 0: return torch.zeros(x_cat.shape[0], 0, device=x_cat.device, dtype=torch.long) x_cat_oh = torch.cat( [F.one_hot(x_cat[:, i], num_classes=self.num_classes[i]) for i in range(len(self.num_classes))], dim=-1 ) return x_cat_oh def _absorbed_closs(self, model_output, x0, cats): #, sigma, dsigma): """ alpha: (bs,) """ cum_sum =0 losses = torch.zeros(len(cats), device=model_output.device) for i, val in enumerate(cats): dist = torch.distributions.Categorical(logits=model_output[:, cum_sum:cum_sum+val]) losses[i] = -dist.log_prob(x0[:, i]).mean() cum_sum += val
loss = losses.sum() return loss
class Velocity(torch.nn.Module): def __init__(self, model): super(Velocity, self).__init__() self.model = model
def forward(self, t, x): t = t * torch.ones(x.shape[0]).to(x.device)
x_num = x[:, :self.model.d_numerical] x_cat = x[:, self.model.d_numerical:] mu, logits = self.model(x_num, x_cat, t)
# Numerical velocity if self.model.d_numerical > 0: v_num = (mu - (1 - 0.01) * x_num) / (1 - (1 - 0.01) * t.unsqueeze(1)) else: v_num = torch.zeros_like(x_num)
# Categorical velocity: normalize logits into probability space before computing velocity if len(self.model.categories) > 0: v_cat_parts = [] logit_idx = 0 oh_idx = 0 for k in self.model.categories: probs_k = F.softmax(logits[:, logit_idx:logit_idx + k], dim=-1) x_k = x_cat[:, oh_idx:oh_idx + k] v_k = (probs_k - (1 - 0.01) * x_k) / (1 - (1 - 0.01) * t.unsqueeze(1)) v_cat_parts.append(v_k) logit_idx += k oh_idx += k v_cat = torch.cat(v_cat_parts, dim=1) else: v_cat = torch.zeros_like(x_cat)
v_t = torch.cat([v_num, v_cat], dim=1) return v_t123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102from typing import Callable, Union
from ef_vfm.modules.transformer import Reconstructor, Tokenizer, Transformerimport torchimport torch.nn as nnimport torch.optim
ModuleType = Union[str, Callable[..., nn.Module]]
class SiLU(nn.Module): def forward(self, x): return x * torch.sigmoid(x)
class PositionalEmbedding(torch.nn.Module): def __init__(self, num_channels, max_positions=10000, endpoint=False): super().__init__() self.num_channels = num_channels self.max_positions = max_positions self.endpoint = endpoint
def forward(self, x): freqs = torch.arange(start=0, end=self.num_channels//2, dtype=torch.float32, device=x.device) freqs = freqs / (self.num_channels // 2 - (1 if self.endpoint else 0)) freqs = (1 / self.max_positions) ** freqs x = x.ger(freqs.to(x.dtype)) x = torch.cat([x.cos(), x.sin()], dim=1) return x
class MLP(nn.Module): def __init__(self, d_in, dim_t = 512, use_mlp=True): super().__init__() self.dim_t = dim_t
self.proj = nn.Linear(d_in, dim_t)
self.mlp = nn.Sequential( nn.Linear(dim_t, dim_t * 2), nn.SiLU(), nn.Linear(dim_t * 2, dim_t * 2), nn.SiLU(), nn.Linear(dim_t * 2, dim_t), nn.SiLU(), nn.Linear(dim_t, d_in), ) if use_mlp else nn.Linear(dim_t, d_in)
self.map_noise = PositionalEmbedding(num_channels=dim_t) self.time_embed = nn.Sequential( nn.Linear(dim_t, dim_t), nn.SiLU(), nn.Linear(dim_t, dim_t) ) self.use_mlp = use_mlp def forward(self, x, timesteps): emb = self.map_noise(timesteps) emb = emb.reshape(emb.shape[0], 2, -1).flip(1).reshape(*emb.shape) # swap sin/cos emb = self.time_embed(emb) x = self.proj(x) + emb return self.mlp(x)
class UniModMLP(nn.Module): """ Input: x_num: [bs, d_numerical] x_cat: [bs, len(categories)] Output: x_num_pred: [bs, d_numerical], the predicted mean for numerical data x_cat_pred: [bs, sum(categories)], the predicted UNORMALIZED logits for categorical data """ def __init__( self, d_numerical, categories, num_layers, d_token, n_head = 1, factor = 4, bias = True, dim_t=512, use_mlp=True, activation='gelu', **kwargs ): super().__init__() self.d_numerical = d_numerical self.categories = categories
self.tokenizer = Tokenizer(d_numerical, categories, d_token, bias = bias) self.encoder = Transformer(num_layers, d_token, n_head, d_token, factor, activation=activation) d_in = d_token * (d_numerical + len(categories)) self.mlp = MLP(d_in, dim_t=dim_t, use_mlp=use_mlp) self.decoder = Transformer(num_layers, d_token, n_head, d_token, factor, activation=activation) self.detokenizer = Reconstructor(d_numerical, categories, d_token) self.model = nn.ModuleList([self.tokenizer, self.encoder, self.mlp, self.decoder, self.detokenizer])
def forward(self, x_num, x_cat, timesteps): e = self.tokenizer(x_num, x_cat) decoder_input = e[:, 1:, :] # ignore the first CLS token. y = self.encoder(decoder_input) pred_y = self.mlp(y.reshape(y.shape[0], -1), timesteps) pred_e = self.decoder(pred_y.reshape(*y.shape)) x_num_pred, x_cat_pred = self.detokenizer(pred_e) 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)
return x_num_pred, x_cat_pred123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269import torchimport torch.nn as nnimport torch.nn.init as nn_initimport torch.nn.functional as Ffrom torch import Tensor
import math
class Tokenizer(nn.Module):
def __init__(self, d_numerical, categories, d_token, bias): super().__init__() if categories is None: d_bias = d_numerical self.category_offsets = None self.category_embeddings = None self.n_categories = 0 else: d_bias = d_numerical + len(categories) category_offsets = torch.tensor([0] + list(categories[:-1])).cumsum(0) category_ends = torch.tensor(list(categories)).cumsum(0) self.register_buffer('category_offsets', category_offsets) self.register_buffer('category_ends', category_ends) self.cat_weight = nn.Parameter(Tensor(sum(categories), d_token)) nn.init.kaiming_uniform_(self.cat_weight, a=math.sqrt(5)) self.n_categories = len(categories)
# take [CLS] token into account self.weight = nn.Parameter(Tensor(d_numerical + 1, d_token)) self.bias = nn.Parameter(Tensor(d_bias, d_token)) if bias else None # The initialization is inspired by nn.Linear nn_init.kaiming_uniform_(self.weight, a=math.sqrt(5)) if self.bias is not None: nn_init.kaiming_uniform_(self.bias, a=math.sqrt(5))
@property def n_tokens(self): return len(self.weight) + ( 0 if self.category_offsets is None else len(self.category_offsets) )
def forward(self, x_num, x_cat): x_some = x_num if x_cat is None else x_cat assert x_some is not None x_num = torch.cat( [torch.ones(len(x_some), 1, device=x_some.device)] # [CLS] + ([] if x_num is None else [x_num]), dim=1, )
x = self.weight[None] * x_num[:, :, None]
if x_cat is not None and self.n_categories > 0: # Vectorized categorical token computation: one matmul per category cat_tokens = [] for start, end in zip(self.category_offsets, self.category_ends): # x_cat[:, start:end] @ cat_weight[start:end] -> [batch, d_token] cat_tokens.append( (x_cat[:, start:end] @ self.cat_weight[start:end]).unsqueeze(1) ) x = torch.cat([x] + cat_tokens, dim=1)
if self.bias is not None: bias = torch.cat( [ torch.zeros(1, self.bias.shape[1], device=x.device), self.bias, ] ) x = x + bias[None]
return x
class MultiheadAttention(nn.Module): def __init__(self, d, n_heads, dropout, initialization = 'kaiming'):
if n_heads > 1: assert d % n_heads == 0 assert initialization in ['xavier', 'kaiming']
super().__init__() self.W_q = nn.Linear(d, d) self.W_k = nn.Linear(d, d) self.W_v = nn.Linear(d, d) self.W_out = nn.Linear(d, d) if n_heads > 1 else None self.n_heads = n_heads self.dropout = nn.Dropout(dropout) if dropout else None
for m in [self.W_q, self.W_k, self.W_v]: if initialization == 'xavier' and (n_heads > 1 or m is not self.W_v): # gain is needed since W_qkv is represented with 3 separate layers nn_init.xavier_uniform_(m.weight, gain=1 / math.sqrt(2)) nn_init.zeros_(m.bias) if self.W_out is not None: nn_init.zeros_(self.W_out.bias)
def _reshape(self, x): batch_size, n_tokens, d = x.shape d_head = d // self.n_heads return ( x.reshape(batch_size, n_tokens, self.n_heads, d_head) .transpose(1, 2) .reshape(batch_size * self.n_heads, n_tokens, d_head) )
def forward(self, x_q, x_kv, key_compression = None, value_compression = None): q, k, v = self.W_q(x_q), self.W_k(x_kv), self.W_v(x_kv) for tensor in [q, k, v]: assert tensor.shape[-1] % self.n_heads == 0 if key_compression is not None: assert value_compression is not None k = key_compression(k.transpose(1, 2)).transpose(1, 2) v = value_compression(v.transpose(1, 2)).transpose(1, 2) else: assert value_compression is None
batch_size = len(q) d_head_key = k.shape[-1] // self.n_heads d_head_value = v.shape[-1] // self.n_heads n_q_tokens = q.shape[1]
q = self._reshape(q) k = self._reshape(k)
a = q @ k.transpose(1, 2) b = math.sqrt(d_head_key) attention = F.softmax(a/b , dim=-1)
if self.dropout is not None: attention = self.dropout(attention) x = attention @ self._reshape(v) x = ( x.reshape(batch_size, self.n_heads, n_q_tokens, d_head_value) .transpose(1, 2) .reshape(batch_size, n_q_tokens, self.n_heads * d_head_value) ) if self.W_out is not None: x = self.W_out(x)
return x class Transformer(nn.Module):
def __init__( self, n_layers: int, d_token: int, n_heads: int, d_out: int, d_ffn_factor: int, attention_dropout = 0.0, ffn_dropout = 0.0, residual_dropout = 0.0, activation = 'relu', prenormalization = True, initialization = 'kaiming', ): super().__init__()
def make_normalization(): return nn.LayerNorm(d_token)
d_hidden = int(d_token * d_ffn_factor) self.layers = nn.ModuleList([]) for layer_idx in range(n_layers): layer = nn.ModuleDict( { 'attention': MultiheadAttention( d_token, n_heads, attention_dropout, initialization ), 'linear0': nn.Linear( d_token, d_hidden ), 'linear1': nn.Linear(d_hidden, d_token), 'norm1': make_normalization(), } ) if not prenormalization or layer_idx: layer['norm0'] = make_normalization() self.layers.append(layer)
_activations = { 'relu': nn.ReLU, 'gelu': nn.GELU, 'silu': nn.SiLU, } if activation not in _activations: raise ValueError(f"Unknown activation '{activation}'. Choose from: {list(_activations)}") self.activation = _activations[activation]() self.last_activation = _activations[activation]() self.prenormalization = prenormalization self.last_normalization = make_normalization() if prenormalization else None self.ffn_dropout = ffn_dropout self.residual_dropout = residual_dropout self.head = nn.Linear(d_token, d_out)
def _start_residual(self, x, layer, norm_idx): x_residual = x if self.prenormalization: norm_key = f'norm{norm_idx}' if norm_key in layer: x_residual = layer[norm_key](x_residual) return x_residual
def _end_residual(self, x, x_residual, layer, norm_idx): if self.residual_dropout: x_residual = F.dropout(x_residual, self.residual_dropout, self.training) x = x + x_residual if not self.prenormalization: x = layer[f'norm{norm_idx}'](x) return x
def forward(self, x): for layer_idx, layer in enumerate(self.layers): is_last_layer = layer_idx + 1 == len(self.layers)
x_residual = self._start_residual(x, layer, 0) x_residual = layer['attention']( # for the last attention, it is enough to process only [CLS] x_residual, x_residual, )
x = self._end_residual(x, x_residual, layer, 0)
x_residual = self._start_residual(x, layer, 1) x_residual = layer['linear0'](x_residual) x_residual = self.activation(x_residual) if self.ffn_dropout: x_residual = F.dropout(x_residual, self.ffn_dropout, self.training) x_residual = layer['linear1'](x_residual) x = self._end_residual(x, x_residual, layer, 1) return x
class Reconstructor(nn.Module): def __init__(self, d_numerical, categories, d_token): super(Reconstructor, self).__init__()
self.d_numerical = d_numerical self.categories = categories self.d_token = d_token self.weight = nn.Parameter(Tensor(d_numerical, d_token)) nn.init.xavier_uniform_(self.weight, gain=1 / math.sqrt(2)) self.cat_recons = nn.ModuleList()
for d in categories: recon = nn.Linear(d_token, d) nn.init.xavier_uniform_(recon.weight, gain=1 / math.sqrt(2)) self.cat_recons.append(recon)
def forward(self, h): h_num = h[:, :self.d_numerical] h_cat = h[:, self.d_numerical:]
recon_x_num = torch.mul(h_num, self.weight.unsqueeze(0)).sum(-1) recon_x_cat = []
for i, recon in enumerate(self.cat_recons): recon_x_cat.append(recon(h_cat[:, i]))
return recon_x_num, recon_x_cat123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557import osimport globimport timeimport torchfrom torch.optim.lr_scheduler import ReduceLROnPlateauimport numpy as npimport pandas as pdimport json
from copy import deepcopy
from utils_train import update_ema
from tqdm import tqdm
BAR = "=============="def print_with_bar(log_msg): log_msg = BAR + log_msg + BAR if "End" in log_msg: log_msg += "\n" print(log_msg)
class Trainer: def __init__( self, flow, train_iter, dataset, test_dataset, metrics, logger, lr, weight_decay, steps, batch_size, check_val_every, sample_batch_size, model_save_path, result_save_path, num_samples_to_generate=None, lr_scheduler='reduce_lr_on_plateau', reduce_lr_patience=100, factor=0.9, ema_decay=0.997, closs_weight_schedule = "fixed", c_lambda = 1.0, d_lambda = 1.0, max_grad_norm = 1.0, warmup_epochs = 0, device=torch.device('cuda:1'), ckpt_path = None, **kwargs ): self.flow = flow self.ema_model = deepcopy(self.flow._vf_fn) for param in self.ema_model.parameters(): param.detach_()
self.train_iter = train_iter self.dataset = dataset self.test_dataset = test_dataset self.steps = steps self.init_lr = lr self.optimizer = torch.optim.AdamW(self.flow.parameters(), lr=lr, weight_decay=weight_decay) self.ema_decay = ema_decay self.lr_scheduler = lr_scheduler self.scheduler = ReduceLROnPlateau(self.optimizer, mode='min', factor=factor, patience=reduce_lr_patience) self.closs_weight_schedule = closs_weight_schedule self.c_lambda = c_lambda self.d_lambda = d_lambda self.max_grad_norm = max_grad_norm self.warmup_epochs = warmup_epochs
self.batch_size = batch_size self.sample_batch_size = sample_batch_size self.num_samples_to_generate = num_samples_to_generate self.metrics = metrics self.logger = logger self.check_val_every = check_val_every
self.device = device self.model_save_path = model_save_path self.result_save_path = result_save_path self.ckpt_path = ckpt_path if self.ckpt_path is not None: state_dicts = torch.load(self.ckpt_path, map_location=self.device) self.flow._vf_fn.load_state_dict(state_dicts['vf_fn']) print(f"Weights are loaded from {self.ckpt_path}")
self.curr_epoch = int(os.path.basename(self.ckpt_path).split('_')[-1].split('.')[0]) if self.ckpt_path is not None else 0
def _anneal_lr(self, step): frac_done = step / self.steps lr = self.init_lr * (1 - frac_done) for param_group in self.optimizer.param_groups: param_group["lr"] = lr
def _run_step(self, x, closs_weight, dloss_weight): x = x.to(self.device) self.flow.train()
self.optimizer.zero_grad()
dloss, closs = self.flow.mixed_loss(x)
loss = dloss_weight * dloss + closs_weight * closs loss.backward() if self.max_grad_norm > 0: torch.nn.utils.clip_grad_norm_(self.flow.parameters(), self.max_grad_norm) self.optimizer.step()
return dloss, closs def compute_loss(self): # eval loss is not weighted curr_dloss = 0.0 curr_closs = 0.0 curr_count = 0 data_iter = self.train_iter for batch in data_iter: x = batch.float().to(self.device) self.flow.eval() with torch.no_grad(): batch_dloss, batch_closs = self.flow.mixed_loss(x) curr_dloss += batch_dloss.item() * len(x) curr_closs += batch_closs.item() * len(x) curr_count += len(x) mloss = np.around(curr_dloss / curr_count, 4) gloss = np.around(curr_closs / curr_count, 4) return mloss, gloss def run_loop(self): patience = 0 closs_weight, dloss_weight = self.c_lambda, self.d_lambda best_loss = np.inf best_ema_loss = np.inf best_val_loss = np.inf start_time = time.time() print_with_bar(f"Starting Trainin Loop, total number of epoch = {self.steps}") # Set up wandb's step metric self.logger.define_metric("epoch") self.logger.define_metric("*", step_metric="epoch") start_epoch = self.curr_epoch if start_epoch > 0: print_with_bar(f"Resuming training from epoch {start_epoch}, with validation check every {self.check_val_every} epoches") for epoch in range (start_epoch, self.steps): self.curr_epoch = epoch+1 # Set up pbar pbar = tqdm(self.train_iter, total=len(self.train_iter)) pbar.set_description(f"Epoch {epoch+1}/{self.steps}") # Compute the loss weights if self.closs_weight_schedule == "fixed": pass elif self.closs_weight_schedule == "anneal": frac_done = epoch / self.steps closs_weight = self.c_lambda * (1 - frac_done) else: raise NotImplementedError(f"The continuous loss weight schedule {self.closs_weight_schedule} is not implemneted")
# Training Step curr_dloss = 0.0 curr_closs = 0.0 curr_count = 0 curr_lr = self.optimizer.param_groups[0]['lr'] for batch in pbar: x = batch.float().to(self.device) batch_dloss, batch_closs = self._run_step(x, closs_weight, dloss_weight) curr_dloss += batch_dloss.item() * len(x) curr_closs += batch_closs.item() * len(x) curr_count += len(x) pbar.set_postfix({ "lr": curr_lr, "DLoss": np.around(curr_dloss/curr_count, 4), "CLoss": np.around(curr_closs/curr_count, 4), "TotalLoss": np.around((curr_dloss + curr_closs)/curr_count, 4), "closs_weight": closs_weight, "dloss_weight": dloss_weight, }) # Log training Loss log_dict = {} mloss = np.around(curr_dloss / curr_count, 4) gloss = np.around(curr_closs / curr_count, 4) total_loss = mloss + gloss if np.isnan(gloss): print('Finding Nan in gaussian loss') break loss_dict = { "epoch": epoch + 1, "lr": curr_lr, "closs_weight": closs_weight, "dloss_weight": dloss_weight, "loss/c_loss": gloss, "loss/d_loss": mloss, "loss/total_loss": total_loss } log_dict.update(loss_dict) # Adjust learning rate (warmup overrides during early epochs) if self.warmup_epochs > 0 and (epoch + 1) <= self.warmup_epochs: warmup_lr = self.init_lr * (epoch + 1) / self.warmup_epochs for param_group in self.optimizer.param_groups: param_group["lr"] = warmup_lr elif self.lr_scheduler == 'reduce_lr_on_plateau': self.scheduler.step(total_loss) elif self.lr_scheduler == 'anneal': self._anneal_lr(epoch) elif self.lr_scheduler == 'fixed': pass else: raise NotImplementedError(f"LR scheduler with name '{self.lr_scheduler}' is not implemented") # Update EMA models update_ema(self.ema_model.parameters(), self.flow._vf_fn.parameters(), rate=self.ema_decay)
# Save ckpt base on the best training loss if total_loss < best_loss and self.curr_epoch > 4000: best_loss = total_loss to_remove = glob.glob(os.path.join(self.model_save_path, f"best_model_*")) if to_remove: os.remove(to_remove[0]) state_dicts = { 'vf_fn': self.flow._vf_fn.state_dict(), } torch.save(state_dicts, os.path.join(self.model_save_path, f'best_model_{np.round(total_loss,4)}_{epoch+1}.pt')) patience = 0 else: patience += 1 # increment patience if best loss is not surpassed # Compute and log EMA model loss curr_model = self.to_ema_model() ema_mloss, ema_gloss = self.compute_loss() self.to_model(curr_model) ema_total_loss = ema_mloss + ema_gloss ema_loss_dict = { "ema_loss/c_loss": ema_gloss, "ema_loss/d_loss": ema_mloss, "ema_loss/total_loss": ema_total_loss } # Save the best ema ckpt if ema_total_loss < best_ema_loss and self.curr_epoch > 4000: best_ema_loss = ema_total_loss to_remove = glob.glob(os.path.join(self.model_save_path, f"best_ema_model_*")) if to_remove: os.remove(to_remove[0]) state_dicts = { 'vf_fn': self.ema_model.state_dict(), } torch.save(state_dicts, os.path.join(self.model_save_path, f'best_ema_model_{np.round(ema_total_loss,4)}_{epoch+1}.pt')) # Evaluate Sample Quality if (epoch+1) % self.check_val_every == 0: state_dicts = { 'vf_fn': self.flow._vf_fn.state_dict(), } torch.save(state_dicts, os.path.join(self.model_save_path, f'model_{epoch+1}.pt')) print_with_bar(f"Routine Generation Evaluation every {self.check_val_every}, currently at epoch #{epoch+1}, wiht total_loss={total_loss}.") _plot_density = os.environ.get("EFVFM_ADAPTER_TRAIN", "").strip().lower() not in ("1", "true", "yes") out_metrics, _, _ = self.evaluate_generation(save_metric_details=True, plot_density=_plot_density) log_dict.update(out_metrics) print(f"Eval Resutls of the Non-EMA model:\n {out_metrics}")
# Evaluate the EMA model torch.save(self.ema_model.state_dict(), os.path.join(self.model_save_path, f'ema_model_{epoch+1}.pt')) ema_out_metrics, _, _ = self.evaluate_generation(ema=True, save_metric_details=True, plot_density=_plot_density) log_dict.update({ "ema": ema_out_metrics, }) print(f"Eval Resutls of the EMA model:\n {ema_out_metrics}") # Submit logs self.logger.log(log_dict)
end_time = time.time() print_with_bar(f"Ending Trainnig Loop, totoal training time = {end_time - start_time}") self.logger.log({ 'training_time': end_time - start_time }) def report_test(self, num_runs): save_dir = self.result_save_path shape_ = [] trend_ = [] mle_ = [] c2st_ = [] for i in range(num_runs): print_with_bar(f"GENERAL Evaluation Run {i}") out_metrics, extras, syn_df = self.evaluate_generation() print(f"Results of Run {i} are: \n{out_metrics}") shape_.append(out_metrics["density/Shape"]) trend_.append(out_metrics["density/Trend"]) mle_.append(out_metrics["mle"]) c2st_.append(out_metrics["c2st"]) # Save samples for quality evaluation save_path = os.path.join(save_dir, "all_samples") if not os.path.exists(save_path): os.makedirs(save_path) syn_df.to_csv(os.path.join(save_path, f"samples_{i}.csv"), index=False)
shape_ = np.array(shape_) trend_ = np.array(trend_) mle_ = np.array(mle_) c2st_ = np.array(c2st_) shape_error = (1 - shape_)*100 trend_error = (1 - trend_)*100 c2st_percent = c2st_ * 100 all_results = pd.DataFrame({ "shape": shape_error, "trend": trend_error, "mle": mle_, "c2st": c2st_percent, }) avg = all_results.mean(axis=0).round(3) std = all_results.std(axis=0).round(3) avg_std = pd.concat([avg, std], axis=1, ignore_index=True) avg_std.columns = ["avg", "std"] avg_std.index = [ "shape", "trend", "mle", "c2st", ] # Savings all_results.to_csv(f"{save_dir}/all_results.csv", index=True) avg_std.to_csv(f"{save_dir}/avg_std.csv", index=True) print_with_bar(f"The AVG over {num_runs} runs are: \n{avg_std}") def report_test_dcr(self, num_runs): save_dir = self.result_save_path dcr_ = [] dcr_real_ = [] dcr_test_ = [] for i in range(num_runs): print_with_bar(f"DCR Evaluation Run {i}") out_metrics, extras, syn_df = self.evaluate_generation() print(f"Results of Run {i} are: \n{out_metrics}") dcr_.append(out_metrics["dcr"]) dcr_real_.append(extras["dcr_real"]) dcr_test_.append(extras["dcr_test"]) save_path = os.path.join(save_dir, "all_samples") if not os.path.exists(save_path): os.makedirs(save_path) syn_df.to_csv(os.path.join(save_path, f"samples_{i}.csv"), index=False)
dcr_ = np.array(dcr_) dcr_percent = dcr_ * 100 all_results = pd.DataFrame({ "dcr": dcr_percent, }) avg = all_results.mean(axis=0).round(3) std = all_results.std(axis=0).round(3) avg_std = pd.concat([avg, std], axis=1, ignore_index=True) avg_std.columns = ["avg", "std"] avg_std.index = [ "dcr", ] # Savings all_results.to_csv(f"{save_dir}/all_results.csv", index=True) avg_std.to_csv(f"{save_dir}/avg_std.csv", index=True) dcr_real = np.concatenate(dcr_real_, axis=0) dcr_test = np.concatenate(dcr_test_, axis=0) dcr_df = pd.DataFrame({ "dcr_real": dcr_real, "dcr_test": dcr_test }) dcr_df.to_csv(f"{save_dir}/dcr.csv", index=False) print_with_bar(f"The AVG over {num_runs} runs are: \n{avg_std}") def test(self): _plot_density = os.environ.get("EFVFM_ADAPTER_TRAIN", "").strip().lower() not in ("1", "true", "yes") out_metrics, _, _ = self.evaluate_generation(save_metric_details=True, plot_density=_plot_density) print_with_bar(f"Results of the test are: \n{out_metrics}") self.logger.log(out_metrics) print(out_metrics)
def evaluate_generation(self, save_metric_details=False, plot_density=False, ema=False): self.flow.eval() # Sample a synthetic table env_num_samples = os.environ.get("EFVFM_EVAL_NUM_SAMPLES", "").strip() if self.num_samples_to_generate: num_samples = self.num_samples_to_generate elif env_num_samples: num_samples = max(1, int(env_num_samples)) else: 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. syn_df = self.sample_synthetic(num_samples, ema=ema) # Save the sample save_path = os.path.join(self.result_save_path, str(self.curr_epoch), "ema" if ema else "") if not os.path.exists(save_path): os.makedirs(save_path) path = os.path.join(save_path, "samples.csv") syn_df.to_csv(path, index=False) print( f"Samples are saved at {path}" )
if os.environ.get("EFVFM_ADAPTER_SAMPLE_ONLY", "").strip().lower() in ("1", "true", "yes"): return {}, {}, syn_df # Compute evaluation metrics on the sample 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. out_metrics, extras = self.metrics.evaluate(syn_df_loaded) # Save metrics and metric details path = os.path.join(save_path, "all_results.json") with open(path, "w") as json_file: json.dump(out_metrics, json_file, indent=4, separators=(", ", ": ")) # always locally save the output metrics if save_metric_details: for name, extra in extras.items(): if isinstance(extra, pd.DataFrame): extra.to_csv(os.path.join(save_path, f"{name}.csv")) elif isinstance(extra, dict): with open(os.path.join(save_path, f"{name}.json"), "w") as json_file: json.dump(extra, json_file, indent=4, separators=(", ", ": ")) else: raise NotImplementedError(f"Extra file generated during evaluations has type {type(extra)}, and code to save this type of file is not implemented") # Plot density figures if plot_density: img = self.metrics.plot_density(syn_df_loaded) path = os.path.join(save_path, "density_plots.png") img.save(path) print( f"The density plots are saved at {path}" ) return out_metrics, extras, syn_df
def sample_synthetic(self, num_samples, keep_nan_samples=True, ema=False): if ema: curr_model = self.to_ema_model()
info = self.metrics.info print_with_bar(f"Starting Sampling, total samples to generate = {num_samples}") start_time = time.time() syn_data = self.flow.sample_all(num_samples, self.sample_batch_size, keep_nan_samples=keep_nan_samples) print(f"Shape of the generated sample = {syn_data.shape}") if keep_nan_samples: num_all_zero_row = (syn_data.sum(dim=1) == 0).sum() if num_all_zero_row: print(f"The generated samples contain {num_all_zero_row} Nan instances!!!") self.logger.log({ 'num_Nan_sample': num_all_zero_row })
# Recover tables num_inverse = self.dataset.num_inverse int_inverse = self.dataset.int_inverse cat_inverse = self.dataset.cat_inverse syn_num, syn_cat, syn_target = split_num_cat_target(syn_data, info, num_inverse, int_inverse, cat_inverse) syn_df = recover_data(syn_num, syn_cat, syn_target, info)
idx_name_mapping = info['idx_name_mapping'] idx_name_mapping = {int(key): value for key, value in idx_name_mapping.items()}
syn_df.rename(columns = idx_name_mapping, inplace=True) end_time = time.time() print_with_bar(f"Ending Sampling, totoal sampling time = {end_time - start_time}") if ema: self.to_model(curr_model)
return syn_df def to_ema_model(self): curr_model = self.flow._vf_fn self.flow._vf_fn = self.ema_model # temporarily install the ema parameters into the model return curr_model
def to_model(self, curr_model): self.flow._vf_fn = curr_model # give back the parameters
def _as_numpy_float32(x): if x is None: return np.array([], dtype=np.float32) if isinstance(x, torch.Tensor): x = x.detach().cpu().numpy() return np.asarray(x, dtype=np.float32)
@torch.no_grad()def split_num_cat_target(syn_data, info, num_inverse, int_inverse, cat_inverse): task_type = info['task_type']
num_col_idx = info['num_col_idx'] cat_col_idx = info['cat_col_idx'] target_col_idx = info['target_col_idx']
n_num_feat = len(num_col_idx) n_cat_feat = len(cat_col_idx)
if task_type == 'regression': n_num_feat += len(target_col_idx) else: n_cat_feat += len(target_col_idx)
syn_num = syn_data[:, :n_num_feat] syn_cat = syn_data[:, n_num_feat:]
if n_num_feat > 0: syn_num = _as_numpy_float32(num_inverse(syn_num)) syn_num = _as_numpy_float32(int_inverse(syn_num)) else: syn_num = np.zeros((syn_data.shape[0], 0), dtype=np.float32) syn_cat = cat_inverse(syn_cat)
if info['task_type'] == 'regression': syn_target = syn_num[:, :len(target_col_idx)] syn_num = syn_num[:, len(target_col_idx):] else: syn_target = syn_cat[:, :len(target_col_idx)] syn_cat = syn_cat[:, len(target_col_idx):]
return syn_num, syn_cat, syn_target
def recover_data(syn_num, syn_cat, syn_target, info):
num_col_idx = info['num_col_idx'] cat_col_idx = info['cat_col_idx'] target_col_idx = info['target_col_idx']
idx_mapping = info['idx_mapping'] idx_mapping = {int(key): value for key, value in idx_mapping.items()}
syn_df = pd.DataFrame()
if info['task_type'] == 'regression': for i in range(len(num_col_idx) + len(cat_col_idx) + len(target_col_idx)): if i in set(num_col_idx): syn_df[i] = syn_num[:, idx_mapping[i]] elif i in set(cat_col_idx): syn_df[i] = syn_cat[:, idx_mapping[i] - len(num_col_idx)] else: syn_df[i] = syn_target[:, idx_mapping[i] - len(num_col_idx) - len(cat_col_idx)]
else: for i in range(len(num_col_idx) + len(cat_col_idx) + len(target_col_idx)): if i in set(num_col_idx): syn_df[i] = syn_num[:, idx_mapping[i]] elif i in set(cat_col_idx): syn_df[i] = syn_cat[:, idx_mapping[i] - len(num_col_idx)] else: syn_df[i] = syn_target[:, idx_mapping[i] - len(num_col_idx) - len(cat_col_idx)]
return syn_dfsyntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/_tabbyflow_train.pyAdded+24
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/input_snapshot.jsonAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/public_gate/normalized_schema_snapshot.jsonAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/public_gate/public_gate_report.jsonAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/public_gate/staged_input_manifest.jsonAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/run_config.jsonAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/runtime_result.jsonAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/staged/public/staged_features.jsonAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/staged/public/test.csvAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/staged/public/train.csvAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/staged/public/val.csvAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/staged/tabbyflow/adapter_report.jsonAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/staged/tabbyflow/adapter_transforms_applied.jsonAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/staged/tabbyflow/model_input_manifest.jsonAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/X_num_test.npyAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/X_num_train.npyAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/X_num_val.npyAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/info.jsonAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/real.csvAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/staged_features.jsonAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/test.csvAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/train.csvAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/val.csvAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/y_test.npyAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/y_train.npyAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/tabular_bundle/pipeline_n12/y_val.npyAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_202729/train_20260510_202730.logAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/.gitignoreAdded+174
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/LICENCEAdded+7
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/README.mdAdded+128
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/X_num_test.npyAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/X_num_train.npyAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/X_num_val.npyAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/info.jsonAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/real.csvAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/staged_features.jsonAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/test.csvAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/train.csvAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/val.csvAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/y_test.npyAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/y_train.npyAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/data/pipeline_n12/y_val.npyAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/download_dataset.pyAdded+49
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/ef_vfm/configs/ef_vfm_configs.tomlAdded+3
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/ef_vfm/main.pyAdded+246
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/ef_vfm/metrics.pyAdded+306
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/ef_vfm/models/flow_model.pyAdded+195
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/ef_vfm/modules/main_modules.pyAdded+102
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/ef_vfm/modules/transformer.pyAdded+269
syntheticFail/n12/tabbyflow/tabbyflow-n12-20260510_213421/_efvfm_runtime/ef_vfm/trainer.pyAdded+557