diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/.gitignore b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..5fe5c08858a9f78b16a14e3d3757641d03307c72 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/.gitignore @@ -0,0 +1,174 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# 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 logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_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 stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_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/adult +data/beijing +data/default +data/magic +data/news +data/shoppers + +wandb/ + +*.DS_Store diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/LICENCE b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/LICENCE new file mode 100644 index 0000000000000000000000000000000000000000..421b2ef006d92669068729de1866b3dde6b3fd45 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/LICENCE @@ -0,0 +1,7 @@ +Copyright 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. diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/README.md b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ffe4e59cce3dd04f5d51853fb14ac71daa561843 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/README.md @@ -0,0 +1,128 @@ +# Exponential Family Variational Flow Matching for Tabular Data Generation + +

+ + MIT License + + + Openreview + + + Paper URL + +

+ +
+ Model Logo +

Figure 1: Exponential Family Variational Flow Matching (EF-VFM) is a generative modeling framework designed for mixed continuous +and discrete variables. By leveraging the exponential family and a mean-field assumption, EF-VFM efficiently matches the sufficient +statistics of the distributions via learned probability paths, ensuring state-of-the-art fidelity and diversity in synthetic data.

+
+ +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 --mode train --exp_name ``` + +where `````` is the name of the dataset you want to train on, and `````` is the name of your experiment. + +Current Options of `````` 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 ```. + +## Sampling and Evaluating TabbyFlow (Density, MLE, C2ST) + +To sample synthetic tables from trained EF-VFM models and evaluate them, run + +```python main.py --dataname --mode test --report --no_wandb --exp_name ``` + +where `````` and `````` 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///. + +## 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 ``` + +Similarly, the results will be printed out in the terminal and added to ./eval/report_runs/// + +## 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 `````` + +```python main.py --dataname _dcr --mode train``` + +Then, test the models on DCR with the same `_dcr` suffix + +```python main.py --dataname _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). diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/X_num_test.npy b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/X_num_test.npy new file mode 100644 index 0000000000000000000000000000000000000000..58dcffe35f9c3d2be06bfacd6463afc29f469621 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/X_num_test.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e252b63332f6d0348986fa99b50bd0f50a4842a6535d987c77e35ec94dca2304 +size 41132 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/X_num_train.npy b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/X_num_train.npy new file mode 100644 index 0000000000000000000000000000000000000000..829ebc8714db6fb18f342ce0609de9b685c8a4c8 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/X_num_train.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b976aada0f39493df222408da25c8093fae5ed29c88a963352f6c5924720bfcb +size 326528 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/X_num_val.npy b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/X_num_val.npy new file mode 100644 index 0000000000000000000000000000000000000000..f9b501abfa8648ee74efcaddf531803aee3c5f5c --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/X_num_val.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:43682ea64d3dccdcaf67f0c922556fe78e3cd216b7456a914a5e169e2b52f5a8 +size 40724 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/info.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/info.json new file mode 100644 index 0000000000000000000000000000000000000000..349bd7f0dfb9558da57b1bb6f8027d081b2f8ffe --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/info.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:575631118d21657a7a362ba5a330d6fff150a3d78c4ba038ffb878dd37c75cd5 +size 9435 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/real.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/real.csv new file mode 100644 index 0000000000000000000000000000000000000000..3eb127a41257f73db9bdc048d746e032df1602e7 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/real.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c185607e5260848288c1fe3ee266131707a54e9f5e053f1234c019f315783fac +size 700663 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/staged_features.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/staged_features.json new file mode 100644 index 0000000000000000000000000000000000000000..764ec9270aa6a452ad32f774e4eb007bf24ca4ec --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/staged_features.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2ceb242f15c8115703b617ca54db02ff27dff41d99dd4f9af89bb5fcb513e5bb +size 5032 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/test.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/test.csv new file mode 100644 index 0000000000000000000000000000000000000000..f0047af47ae70bd3483af5c9474d2baa67f629bb --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/test.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6c58f97d23ce9ec15dde2caf4ba02105c2839eb4b1e1bb7f5183e0661fec4ecd +size 88640 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/train.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/train.csv new file mode 100644 index 0000000000000000000000000000000000000000..3eb127a41257f73db9bdc048d746e032df1602e7 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/train.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c185607e5260848288c1fe3ee266131707a54e9f5e053f1234c019f315783fac +size 700663 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/val.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/val.csv new file mode 100644 index 0000000000000000000000000000000000000000..a5a6f693df47fd7a53d30e1da2c9caaa2edf2d23 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/val.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:efcb8ee58a24ce4397213b3c4df4826fbcc6662da77b0919ff4e1935d12e2e89 +size 87578 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/y_test.npy b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/y_test.npy new file mode 100644 index 0000000000000000000000000000000000000000..5651fa99fbfba7f7fa1d0ad15aebc466b7a7cc53 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/y_test.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2e6b805a842cf97508b8a3789499fc698c44e659e45b100fb80d666ad2f96a74 +size 1736 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/y_train.npy b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/y_train.npy new file mode 100644 index 0000000000000000000000000000000000000000..0849049b021bfe542c1221ec2b7369cecd5e2165 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/y_train.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ee738812eaaf4a819a6c9f861ee2e99873bd2842f80c68eb380cc38033938b74 +size 12928 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/y_val.npy b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/y_val.npy new file mode 100644 index 0000000000000000000000000000000000000000..87b51e4ebfe724b015106152ef10e69ffd69b53b --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/data/pipeline_n14/y_val.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0df86b75b6fc8fea3f161682beaa867a5bb7dbe36f9331e7d36176459da70720 +size 1720 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/download_dataset.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/download_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..427dbbdc686039d81b03aa05d721d06c5b0dcd47 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/download_dataset.py @@ -0,0 +1,49 @@ +import os +from urllib import request +import 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) + \ No newline at end of file diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/ef_vfm/configs/ef_vfm_configs.toml b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/ef_vfm/configs/ef_vfm_configs.toml new file mode 100644 index 0000000000000000000000000000000000000000..da1df42825e99fb19a331757d981a43fd5c25472 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/ef_vfm/configs/ef_vfm_configs.toml @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:677698232b3ea325b54527cccdc11c49fadb971129a77065e71d64aa7567ddb6 +size 674 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/ef_vfm/main.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/ef_vfm/main.py new file mode 100644 index 0000000000000000000000000000000000000000..d3e0966c01ffb317e0d8cb94b6f293992dbfbdc1 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/ef_vfm/main.py @@ -0,0 +1,246 @@ +import glob +import json +import os +import pickle +import random + +import numpy as np +from ef_vfm.metrics import TabMetrics +from ef_vfm.modules.main_modules import UniModMLP +from ef_vfm.models.flow_model import ExpVFM +from ef_vfm.trainer import Trainer +import src +import torch + +from torch.utils.data import DataLoader +import argparse +import 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' diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/ef_vfm/metrics.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/ef_vfm/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..4f104427533ac37610c92216b135fdeba3d181be --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/ef_vfm/metrics.py @@ -0,0 +1,306 @@ +from copy import deepcopy +import numpy as np +import torch +import pandas as pd +# Metrics +from eval.mle.mle import get_evaluator +from eval.visualize_density import plot_density +from sdmetrics.reports.single_table import QualityReport, DiagnosticReport +from sdmetrics.single_table import LogisticDetection +from 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, metadata \ No newline at end of file diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/ef_vfm/models/flow_model.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/ef_vfm/models/flow_model.py new file mode 100644 index 0000000000000000000000000000000000000000..536d0cd1311210bac6bbc91dcc31d0612ca053b6 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/ef_vfm/models/flow_model.py @@ -0,0 +1,195 @@ +import torch.nn.functional as F +import torch +import numpy as np +from 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_t \ No newline at end of file diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/ef_vfm/modules/main_modules.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/ef_vfm/modules/main_modules.py new file mode 100644 index 0000000000000000000000000000000000000000..46dceb368af3302e55d5e448a2ffede4db122977 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/ef_vfm/modules/main_modules.py @@ -0,0 +1,102 @@ +from typing import Callable, Union + +from ef_vfm.modules.transformer import Reconstructor, Tokenizer, Transformer +import torch +import torch.nn as nn +import 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_pred diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/ef_vfm/modules/transformer.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/ef_vfm/modules/transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..98334864ad8befdc6e23fe5f64d5e50bf5907cee --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/ef_vfm/modules/transformer.py @@ -0,0 +1,269 @@ +import torch +import torch.nn as nn +import torch.nn.init as nn_init +import torch.nn.functional as F +from 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_cat diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/ef_vfm/trainer.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/ef_vfm/trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..eef113e930d00d7b80310b03b072384548fd31b0 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/ef_vfm/trainer.py @@ -0,0 +1,557 @@ +import os +import glob +import time +import torch +from torch.optim.lr_scheduler import ReduceLROnPlateau +import numpy as np +import pandas as pd +import 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_df \ No newline at end of file diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/eval/eval_quality.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/eval/eval_quality.py new file mode 100644 index 0000000000000000000000000000000000000000..c7f4f9409e5a207087ab59104d2f970a17341ba5 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/eval/eval_quality.py @@ -0,0 +1,149 @@ +import glob +import numpy as np +import pandas as pd +import os +import sys +import json + +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +from sklearn.preprocessing import OneHotEncoder +from synthcity.metrics import eval_statistical +from synthcity.plugins.core.dataloader import GenericDataLoader + +pd.options.mode.chained_assignment = None + +import argparse + +parser = argparse.ArgumentParser() +parser.add_argument('--dataname', type=str) +parser.add_argument('--exp_name', type=str, default=None) + + +args = parser.parse_args() + +def evaluate_quality(real_path, syn_path, info_path): + with open(info_path, 'r') as f: + info = json.load(f) + + syn_data = pd.read_csv(syn_path) + real_data = pd.read_csv(real_path) + + + ''' Special treatment for default dataset and CoDi model ''' + + real_data.columns = range(len(real_data.columns)) + syn_data.columns = range(len(syn_data.columns)) + + num_col_idx = info['num_col_idx'] + cat_col_idx = info['cat_col_idx'] + target_col_idx = info['target_col_idx'] + if info['task_type'] == 'regression': + num_col_idx += target_col_idx + else: + cat_col_idx += target_col_idx + + num_real_data = real_data[num_col_idx] + cat_real_data = real_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 = syn_data[num_col_idx] + cat_syn_data = syn_data[cat_col_idx] + + num_syn_data_np = num_syn_data.to_numpy() + + # cat_syn_data_np = np.array + cat_syn_data_np = cat_syn_data.to_numpy().astype('str') + + encoder = OneHotEncoder() + 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() + + le_real_data = pd.DataFrame(np.concatenate((num_real_data_np, cat_real_data_oh), axis = 1)).astype(float) + le_real_num = pd.DataFrame(num_real_data_np).astype(float) + le_real_cat = pd.DataFrame(cat_real_data_oh).astype(float) + + + le_syn_data = pd.DataFrame(np.concatenate((num_syn_data_np, cat_syn_data_oh), axis = 1)).astype(float) + le_syn_num = pd.DataFrame(num_syn_data_np).astype(float) + le_syn_cat = pd.DataFrame(cat_syn_data_oh).astype(float) + + # Check for nan + if le_syn_data.isnull().values.any(): + nan_coordinate = np.isnan(le_syn_data.to_numpy()).nonzero() + nan_row = np.unique(nan_coordinate[0]) + print(f"Synthetic data contains NaN at row {nan_row}: ") + print(le_syn_data.iloc[nan_row]) + return None, None + + + np.set_printoptions(precision=4) + + result = [] + + print('=========== All Features ===========') + print('Data shape: ', le_syn_data.shape) + + X_syn_loader = GenericDataLoader(le_syn_data) + X_real_loader = GenericDataLoader(le_real_data) + + quality_evaluator = eval_statistical.AlphaPrecision() + qual_res = quality_evaluator.evaluate(X_real_loader, X_syn_loader) + qual_res = { + k: v for (k, v) in qual_res.items() if "naive" in k + } # use the naive implementation of AlphaPrecision + qual_score = np.mean(list(qual_res.values())) + + print('alpha precision: {:.6f}, beta recall: {:.6f}'.format(qual_res['delta_precision_alpha_naive'], qual_res['delta_coverage_beta_naive'] )) + + Alpha_Precision_all = qual_res['delta_precision_alpha_naive'] + Beta_Recall_all = qual_res['delta_coverage_beta_naive'] + + return Alpha_Precision_all, Beta_Recall_all + +if __name__ == '__main__': + exp_name = args.exp_name + assert exp_name is not None, "Experiment name must be provided" + dataname = args.dataname + data_dir = f'data/{dataname}' + info_path = f'{data_dir}/info.json' + real_path = f'synthetic/{dataname}/real.csv' + + sample_dir = f"eval/report_runs/{exp_name}/{dataname}/all_samples" + sample_paths = glob.glob(os.path.join(sample_dir, "*.csv")) + print(f"{len(sample_paths )} samples loaded from {sample_dir}") + + alphas, betas = [], [] + for syn_path in sample_paths: + alpha_precision, beta_recall = evaluate_quality(real_path, syn_path, info_path) + if (alpha_precision is None) or (beta_recall is None): + continue + alphas.append(alpha_precision) + betas.append(beta_recall) + + alphas = np.array(alphas) + betas = np.array(betas) + alpha_percent = alphas * 100 + beta_percent = betas * 100 + + quality = pd.DataFrame({ + 'alpha': alpha_percent, + 'beta': beta_percent + }) + avg = quality.mean(axis=0).round(2) + std = quality.std(axis=0).round(2) + quality_avg_std = pd.concat([avg, std], axis=1, ignore_index=True) + quality_avg_std.columns = ["avg", "std"] + quality_avg_std.index = ["alpha", "beta"] + + save_dir = os.path.dirname(sample_dir) + quality.to_csv(os.path.join(save_dir, "quality.csv"), index=True) + avg_std = pd.read_csv(os.path.join(save_dir, "avg_std.csv"), index_col=0) + avg_std = pd.concat([avg_std, quality_avg_std]) + print(avg_std) + avg_std.to_csv(os.path.join(save_dir, "avg_std.csv"), index=True) diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/eval/mle/mle.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/eval/mle/mle.py new file mode 100644 index 0000000000000000000000000000000000000000..0cfb8766d1bf207b3abe48a1142f7ef436a6eae8 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/eval/mle/mle.py @@ -0,0 +1,781 @@ +import numpy as np +import pandas as pd +from xgboost import XGBClassifier, XGBRegressor +from sklearn.ensemble import AdaBoostClassifier, RandomForestClassifier, RandomForestRegressor +from sklearn.linear_model import LogisticRegression, LinearRegression +from sklearn.neural_network import MLPClassifier, MLPRegressor +from sklearn.preprocessing import OneHotEncoder, LabelEncoder +from sklearn.tree import DecisionTreeClassifier +from sklearn.metrics import classification_report, accuracy_score, f1_score, precision_score, recall_score, roc_auc_score +from sklearn.metrics import explained_variance_score, mean_squared_error, mean_absolute_error, r2_score +from sklearn.model_selection import ParameterGrid +from sklearn.utils._testing import ignore_warnings +from sklearn.exceptions import ConvergenceWarning +import logging +from prdc import compute_prdc +from tqdm import tqdm + +CATEGORICAL = "categorical" +CONTINUOUS = "continuous" + +_MODELS = { + 'binclass': [ # 184 + # { + # 'class': DecisionTreeClassifier, # 48 + # 'kwargs': { + # 'max_depth': [4, 8, 16, 32], + # 'min_samples_split': [2, 4, 8], + # 'min_samples_leaf': [1, 2, 4, 8] + # } + # }, + # { + # 'class': AdaBoostClassifier, # 4 + # 'kwargs': { + # 'n_estimators': [10, 50, 100, 200] + # } + # }, + # { + # 'class': LogisticRegression, # 36 + # 'kwargs': { + # 'solver': ['lbfgs'], + # 'n_jobs': [-1], + # 'max_iter': [10, 50, 100, 200], + # 'C': [0.01, 0.1, 1.0], + # 'tol': [1e-01, 1e-02, 1e-04] + # } + # }, + # { + # 'class': MLPClassifier, # 12 + # 'kwargs': { + # 'hidden_layer_sizes': [(100, ), (200, ), (100, 100)], + # 'max_iter': [50, 100], + # 'alpha': [0.0001, 0.001] + # } + # }, + # { + # 'class': RandomForestClassifier, # 48 + # 'kwargs': { + # 'max_depth': [8, 16, None], + # 'min_samples_split': [2, 4, 8], + # 'min_samples_leaf': [1, 2, 4, 8], + # 'n_jobs': [-1] + + # } + # }, + { + 'class': XGBClassifier, # 36 + 'kwargs': { + 'n_estimators': [10, 50, 100], + 'min_child_weight': [1, 10], + 'max_depth': [5, 10, 20], + 'gamma': [0.0, 1.0], + 'objective': ['binary:logistic'], + 'nthread': [-1], + 'tree_method': ['gpu_hist'] + }, + } + + ], + 'multiclass': [ # 132 + + # { + # 'class': MLPClassifier, # 12 + # 'kwargs': { + # 'hidden_layer_sizes': [(100, ), (200, ), (100, 100)], + # 'max_iter': [50, 100], + # 'alpha': [0.0001, 0.001] + # } + # }, + # { + # 'class': DecisionTreeClassifier, # 48 + # 'kwargs': { + # 'max_depth': [4, 8, 16, 32], + # 'min_samples_split': [2, 4, 8], + # 'min_samples_leaf': [1, 2, 4, 8] + # } + # }, + # { + # 'class': RandomForestClassifier, # 36 + # 'kwargs': { + # 'max_depth': [8, 16, None], + # 'min_samples_split': [2, 4, 8], + # 'min_samples_leaf': [1, 2, 4, 8], + # 'n_jobs': [-1] + + # } + # }, + { + 'class': XGBClassifier, # 36 + 'kwargs': { + 'n_estimators': [10, 50, 100], + 'min_child_weight': [1, 10], + 'max_depth': [5, 10, 20], + 'gamma': [0.0, 1.0], + 'objective': ['binary:logistic'], + 'nthread': [-1], + 'tree_method': ['gpu_hist'] + } + } + + ], + 'regression': [ # 84 + # { + # 'class': LinearRegression, + # }, + # { + # 'class': MLPRegressor, # 12 + # 'kwargs': { + # 'hidden_layer_sizes': [(100, ), (200, ), (100, 100)], + # 'max_iter': [50, 100], + # 'alpha': [0.0001, 0.001] + # } + #}, + { + 'class': XGBRegressor, # 36 + 'kwargs': { + 'n_estimators': [10, 50, 100], + 'min_child_weight': [1, 10], + 'max_depth': [5, 10, 20], + 'gamma': [0.0, 1.0], + 'objective': ['reg:linear'], + 'nthread': [-1], + 'tree_method': ['gpu_hist'] + } + }, + # { + # 'class': RandomForestRegressor, # 36 + # 'kwargs': { + # 'max_depth': [8, 16, None], + # 'min_samples_split': [2, 4, 8], + # 'min_samples_leaf': [1, 2, 4, 8], + # 'n_jobs': [-1] + # } + # } + ] +} + +def feat_transform(data, info, label_encoder = None, encoders = None, cmax = None, cmin = None): + num_col_idx = info['num_col_idx'] + cat_col_idx = info['cat_col_idx'] + target_col_idx = info['target_col_idx'] + + num_cols = len(num_col_idx + cat_col_idx + target_col_idx) + features = [] + + if not encoders: + encoders = dict() + for idx in range(num_cols): + col = data[:, idx] + + if idx in target_col_idx: + + if info['task_type'] != 'regression': + + if not label_encoder: + label_encoder = LabelEncoder() + label_encoder.fit(col) + + encoded_labels = label_encoder.transform(col) + labels = encoded_labels + else: + col = col.astype(np.float32) + labels = col.astype(np.float32) + + continue + + if idx in num_col_idx: + col = col.astype(np.float32) + + if not cmin: + cmin = col.min() + + if not cmax: + cmax = col.max() + + if cmin >= 0 and cmax >= 1e3: + feature = np.log(np.maximum(col, 1e-2)) + + else: + feature = (col - cmin) / (cmax - cmin) * 5 + + elif idx in cat_col_idx: + encoder = encoders.get(idx) + col = col.reshape(-1, 1) + if encoder: + feature = encoder.transform(col) + else: + # encoder = OneHotEncoder(sparse=False, handle_unknown='ignore') + encoder = OneHotEncoder(sparse_output=False, handle_unknown='ignore') # New in version 1.2: sparse was renamed to sparse_output + encoders[idx] = encoder + feature = encoder.fit_transform(col) + + + features.append(feature) + features = np.column_stack(features) + return features, labels, label_encoder, encoders, cmax, cmin + + +def prepare_ml_problem(train, test, info, val=None): + # test_X, test_y, label_encoder, encoders = feat_transform(test, info) + # train_X, train_y, _, _ = feat_transform(train, info, label_encoder, encoders) + + train_X, train_y, label_encoder, encoders, cmax, cmin = feat_transform(train, info) + test_X, test_y, _, _ , _, _ = feat_transform(test, info, label_encoder, encoders, cmax, cmin) + + if val is not None: + val_X, val_y, _, _, _, _ = feat_transform(val, info, label_encoder, encoders, cmax, cmin) + else: + total_train_num = train_X.shape[0] + val_num = int(total_train_num / 9) + + total_train_idx = np.arange(total_train_num) + np.random.shuffle(total_train_idx) + train_idx = total_train_idx[val_num:] + val_idx = total_train_idx[:val_num] + + + + # val_X, val_y = train_X[val_idx], train_y[val_idx] + # train_X, train_y = train_X[train_idx], train_y[train_idx] + + # model = _MODELS[info['task_type']] + + # return train_X, train_y, train_X, train_y, test_X, test_y, model + + + + val_X, val_y = train_X[val_idx], train_y[val_idx] + train_X, train_y = train_X[train_idx], train_y[train_idx] + + model = _MODELS[info['task_type']] + + return train_X, train_y, val_X, val_y, test_X, test_y, model + +class FeatureMaker: + + def __init__(self, metadata, label_column='label', label_type='int', sample=50000): + self.columns = metadata['columns'] + self.label_column = label_column + self.label_type = label_type + self.sample = sample + self.encoders = dict() + + def make_features(self, data): + data = data.copy() + np.random.shuffle(data) + data = data[:self.sample] + + features = [] + labels = [] + + for index, cinfo in enumerate(self.columns): + col = data[:, index] + if cinfo['name'] == self.label_column: + if self.label_type == 'int': + labels = col.astype(int) + elif self.label_type == 'float': + labels = col.astype(float) + else: + assert 0, 'unkown label type' + continue + + if cinfo['type'] == CONTINUOUS: + cmin = cinfo['min'] + cmax = cinfo['max'] + if cmin >= 0 and cmax >= 1e3: + feature = np.log(np.maximum(col, 1e-2)) + + else: + feature = (col - cmin) / (cmax - cmin) * 5 + + else: + if cinfo['size'] <= 2: + feature = col + + else: + encoder = self.encoders.get(index) + col = col.reshape(-1, 1) + if encoder: + feature = encoder.transform(col) + else: + encoder = OneHotEncoder(sparse=False, handle_unknown='ignore') + self.encoders[index] = encoder + feature = encoder.fit_transform(col) + + features.append(feature) + + features = np.column_stack(features) + + return features, labels + + +def _prepare_ml_problem(train, val, test, metadata, eval): + fm = FeatureMaker(metadata) + x_trains, y_trains = [], [] + + for i in train: + x_train, y_train = fm.make_features(i) + x_trains.append(x_train) + y_trains.append(y_train) + + x_val, y_val = fm.make_features(val) + if eval is None: + x_test = None + y_test = None + else: + x_test, y_test = fm.make_features(test) + model = _MODELS[metadata['problem_type']] + + return x_trains, y_trains, x_val, y_val, x_test, y_test, model + + +def _weighted_f1(y_test, pred): + report = classification_report(y_test, pred, output_dict=True) + classes = list(report.keys())[:-3] + proportion = [ report[i]['support'] / len(y_test) for i in classes] + weighted_f1 = np.sum(list(map(lambda i, prop: report[i]['f1-score']* (1-prop)/(len(classes)-1), classes, proportion))) + return weighted_f1 + + +@ignore_warnings(category=ConvergenceWarning) +def _evaluate_multi_classification(train, test, info, val=None): + x_trains, y_trains, x_valid, y_valid, x_test, y_test, classifiers = prepare_ml_problem(train, test, info, val=val) + best_f1_scores = [] + unique_labels = np.unique(y_trains) + + + best_f1_scores = [] + best_weighted_scores = [] + best_auroc_scores = [] + best_acc_scores = [] + best_avg_scores = [] + + for model_spec in classifiers: + model_class = model_spec['class'] + model_kwargs = model_spec.get('kwargs', dict()) + model_repr = model_class.__name__ + + unique_labels = np.unique(y_trains) + + param_set = list(ParameterGrid(model_kwargs)) + + results = [] + for param in tqdm(param_set): + model = model_class(**param) + + try: + model.fit(x_trains, y_trains) + except: + pass + + if len(unique_labels) != len(np.unique(y_valid)): + pred = [unique_labels[0]] * len(x_valid) + pred_prob = np.array([1.] * len(x_valid)) + else: + pred = model.predict(x_valid) + pred_prob = model.predict_proba(x_valid) + + macro_f1 = f1_score(y_valid, pred, average='macro') + weighted_f1 = _weighted_f1(y_valid, pred) + acc = accuracy_score(y_valid, pred) + + # 3. auroc + # size = [a["size"] for a in metadata["columns"] if a["name"] == "label"][0] + size = len(set(unique_labels)) + rest_label = set(range(size)) - set(unique_labels) + tmp = [] + j = 0 + for i in range(size): + if i in rest_label: + tmp.append(np.array([0] * y_valid.shape[0])[:,np.newaxis]) + else: + try: + tmp.append(pred_prob[:,[j]]) + except: + tmp.append(pred_prob[:, np.newaxis]) + j += 1 + + roc_auc = roc_auc_score(np.eye(size)[y_valid], np.hstack(tmp), multi_class='ovr') + + results.append( + { + "name": model_repr, + "param": param, + "macro_f1": macro_f1, + "weighted_f1": weighted_f1, + "roc_auc": roc_auc, + "accuracy": acc + } + ) + + results = pd.DataFrame(results) + results['avg'] = results.loc[:, ['macro_f1', 'weighted_f1', 'roc_auc']].mean(axis=1) + best_f1_param = results.param[results.macro_f1.idxmax()] + best_weighted_param = results.param[results.weighted_f1.idxmax()] + best_auroc_param = results.param[results.roc_auc.idxmax()] + best_acc_param = results.param[results.accuracy.idxmax()] + best_avg_param = results.param[results.avg.idxmax()] + + + # test the best model + results = pd.DataFrame(results) + # best_param = results.param[results.macro_f1.idxmax()] + + def _calc(best_model): + best_scores = [] + + x_train = x_trains + y_train = y_trains + + try: + best_model.fit(x_train, y_train) + except: + pass + + if len(unique_labels) != len(np.unique(y_test)): + pred = [unique_labels[0]] * len(x_test) + pred_prob = np.array([1.] * len(x_test)) + else: + pred = best_model.predict(x_test) + pred_prob = best_model.predict_proba(x_test) + + macro_f1 = f1_score(y_test, pred, average='macro') + weighted_f1 = _weighted_f1(y_test, pred) + acc = accuracy_score(y_test, pred) + + # 3. auroc + size = len(set(unique_labels)) + rest_label = set(range(size)) - set(unique_labels) + tmp = [] + j = 0 + for i in range(size): + if i in rest_label: + tmp.append(np.array([0] * y_test.shape[0])[:,np.newaxis]) + else: + try: + tmp.append(pred_prob[:,[j]]) + except: + tmp.append(pred_prob[:, np.newaxis]) + j += 1 + roc_auc = roc_auc_score(np.eye(size)[y_test], np.hstack(tmp), multi_class='ovr') + + best_scores.append( + { + "name": model_repr, + "macro_f1": macro_f1, + "weighted_f1": weighted_f1, + "roc_auc": roc_auc, + "accuracy": acc + } + ) + return pd.DataFrame(best_scores) + + def _df(dataframe): + return { + "name": model_repr, + "macro_f1": dataframe.macro_f1.values[0], + "roc_auc": dataframe.roc_auc.values[0], + "weighted_f1": dataframe.weighted_f1.values[0], + "accuracy": dataframe.accuracy.values[0], + } + + best_f1_scores.append(_df(_calc(model_class(**best_f1_param)))) + best_weighted_scores.append(_df(_calc(model_class(**best_weighted_param)))) + best_auroc_scores.append(_df(_calc(model_class(**best_auroc_param)))) + best_acc_scores.append(_df(_calc(model_class(**best_acc_param)))) + best_avg_scores.append(_df(_calc(model_class(**best_avg_param)))) + + return best_f1_scores, best_weighted_scores, best_auroc_scores, best_acc_scores, best_avg_scores + +@ignore_warnings(category=ConvergenceWarning) +def _evaluate_binary_classification(train, test, info, val=None): + x_trains, y_trains, x_valid, y_valid, x_test, y_test, classifiers = prepare_ml_problem(train, test, info, val=val) + + unique_labels = np.unique(y_trains) + + best_f1_scores = [] + best_weighted_scores = [] + best_auroc_scores = [] + best_acc_scores = [] + best_avg_scores = [] + + for model_spec in classifiers: + + model_class = model_spec['class'] + model_kwargs = model_spec.get('kwargs', dict()) + model_repr = model_class.__name__ + + unique_labels = np.unique(y_trains) + + param_set = list(ParameterGrid(model_kwargs)) + + results = [] + for param in tqdm(param_set): + model = model_class(**param) + + try: + model.fit(x_trains, y_trains) + except ValueError: + pass + + if len(unique_labels) == 1: + pred = [unique_labels[0]] * len(x_valid) + pred_prob = np.array([1.] * len(x_valid)) + else: + pred = model.predict(x_valid) + pred_prob = model.predict_proba(x_valid) + + binary_f1 = f1_score(y_valid, pred, average='binary') + weighted_f1 = _weighted_f1(y_valid, pred) + acc = accuracy_score(y_valid, pred) + precision = precision_score(y_valid, pred, average='binary') + recall = recall_score(y_valid, pred, average='binary') + macro_f1 = f1_score(y_valid, pred, average='macro') + + # auroc + size = 2 + rest_label = set(range(size)) - set(unique_labels) + tmp = [] + j = 0 + for i in range(size): + if i in rest_label: + tmp.append(np.array([0] * y_valid.shape[0])[:,np.newaxis]) + else: + try: + tmp.append(pred_prob[:,[j]]) + except: + tmp.append(pred_prob[:, np.newaxis]) + j += 1 + roc_auc = roc_auc_score(np.eye(size)[y_valid], np.hstack(tmp)) + + results.append( + { + "name": model_repr, + "param": param, + "binary_f1": binary_f1, + "weighted_f1": weighted_f1, + "roc_auc": roc_auc, + "accuracy": acc, + "precision": precision, + "recall": recall, + "macro_f1": macro_f1 + } + ) + + + # test the best model + results = pd.DataFrame(results) + results['avg'] = results.loc[:, ['binary_f1', 'weighted_f1', 'roc_auc']].mean(axis=1) + best_f1_param = results.param[results.binary_f1.idxmax()] + best_weighted_param = results.param[results.weighted_f1.idxmax()] + best_auroc_param = results.param[results.roc_auc.idxmax()] + best_acc_param = results.param[results.accuracy.idxmax()] + best_avg_param = results.param[results.avg.idxmax()] + + + def _calc(best_model): + best_scores = [] + + best_model.fit(x_trains, y_trains) + + if len(unique_labels) == 1: + pred = [unique_labels[0]] * len(x_test) + pred_prob = np.array([1.] * len(x_test)) + else: + pred = best_model.predict(x_test) + pred_prob = best_model.predict_proba(x_test) + + binary_f1 = f1_score(y_test, pred, average='binary') + weighted_f1 = _weighted_f1(y_test, pred) + acc = accuracy_score(y_test, pred) + precision = precision_score(y_test, pred, average='binary') + recall = recall_score(y_test, pred, average='binary') + macro_f1 = f1_score(y_test, pred, average='macro') + + # auroc + size = 2 + rest_label = set(range(size)) - set(unique_labels) + tmp = [] + j = 0 + for i in range(size): + if i in rest_label: + tmp.append(np.array([0] * y_test.shape[0])[:,np.newaxis]) + else: + try: + tmp.append(pred_prob[:,[j]]) + except: + tmp.append(pred_prob[:, np.newaxis]) + j += 1 + try: + roc_auc = roc_auc_score(np.eye(size)[y_test], np.hstack(tmp)) + except ValueError: + tmp[1] = tmp[1].reshape(20000, 1) + roc_auc = roc_auc_score(np.eye(size)[y_test], np.hstack(tmp)) + + best_scores.append( + { + "name": model_repr, + # "param": param, + "binary_f1": binary_f1, + "weighted_f1": weighted_f1, + "roc_auc": roc_auc, + "accuracy": acc, + "precision": precision, + "recall": recall, + "macro_f1": macro_f1 + } + ) + + return pd.DataFrame(best_scores) + def _df(dataframe): + return { + "name": model_repr, + "binary_f1": dataframe.binary_f1.values[0], + "roc_auc": dataframe.roc_auc.values[0], + "weighted_f1": dataframe.weighted_f1.values[0], + "accuracy": dataframe.accuracy.values[0], + } + + best_f1_scores.append(_df(_calc(model_class(**best_f1_param)))) + best_weighted_scores.append(_df(_calc(model_class(**best_weighted_param)))) + best_auroc_scores.append(_df(_calc(model_class(**best_auroc_param)))) + best_acc_scores.append(_df(_calc(model_class(**best_acc_param)))) + best_avg_scores.append(_df(_calc(model_class(**best_avg_param)))) + + return best_f1_scores, best_weighted_scores, best_auroc_scores, best_acc_scores, best_avg_scores + +@ignore_warnings(category=ConvergenceWarning) +def _evaluate_regression(train, test, info, val=None): + + x_trains, y_trains, x_valid, y_valid, x_test, y_test, regressors = prepare_ml_problem(train, test, info, val=val) + + + best_r2_scores = [] + best_ev_scores = [] + best_mae_scores = [] + best_rmse_scores = [] + best_avg_scores = [] + + y_trains = np.log(np.clip(y_trains, 1, 20000)) + y_test = np.log(np.clip(y_test, 1, 20000)) + + for model_spec in regressors: + model_class = model_spec['class'] + model_kwargs = model_spec.get('kwargs', dict()) + model_repr = model_class.__name__ + + param_set = list(ParameterGrid(model_kwargs)) + + results = [] + for param in tqdm(param_set): + model = model_class(**param) + model.fit(x_trains, y_trains) + pred = model.predict(x_valid) + + r2 = r2_score(y_valid, pred) + explained_variance = explained_variance_score(y_valid, pred) + mean_squared = mean_squared_error(y_valid, pred) + root_mean_squared = np.sqrt(mean_squared) + mean_absolute = mean_absolute_error(y_valid, pred) + + results.append( + { + "name": model_repr, + "param": param, + "r2": r2, + "explained_variance": explained_variance, + "mean_squared": mean_squared, + "mean_absolute": mean_absolute, + "rmse": root_mean_squared + } + ) + + results = pd.DataFrame(results) + # results['avg'] = results.loc[:, ['r2', 'rmse']].mean(axis=1) + best_r2_param = results.param[results.r2.idxmax()] + best_ev_param = results.param[results.explained_variance.idxmax()] + best_mae_param = results.param[results.mean_absolute.idxmin()] + best_rmse_param = results.param[results.rmse.idxmin()] + # best_avg_param = results.param[results.avg.idxmax()] + + def _calc(best_model): + best_scores = [] + x_train, y_train = x_trains, y_trains + + best_model.fit(x_train, y_train) + pred = best_model.predict(x_test) + + r2 = r2_score(y_test, pred) + explained_variance = explained_variance_score(y_test, pred) + mean_squared = mean_squared_error(y_test, pred) + root_mean_squared = np.sqrt(mean_squared) + mean_absolute = mean_absolute_error(y_test, pred) + + best_scores.append( + { + "name": model_repr, + "param": param, + "r2": r2, + "explained_variance": explained_variance, + "mean_squared": mean_squared, + "mean_absolute": mean_absolute, + "rmse": root_mean_squared + } + ) + + return pd.DataFrame(best_scores) + + def _df(dataframe): + return { + "name": model_repr, + "r2": dataframe.r2.values[0].astype(float), + "explained_variance": dataframe.explained_variance.values[0].astype(float), + "MAE": dataframe.mean_absolute.values[0].astype(float), + "RMSE": dataframe.rmse.values[0].astype(float), + } + + best_r2_scores.append(_df(_calc(model_class(**best_r2_param)))) + best_ev_scores.append(_df(_calc(model_class(**best_ev_param)))) + best_mae_scores.append(_df(_calc(model_class(**best_mae_param)))) + best_rmse_scores.append(_df(_calc(model_class(**best_rmse_param)))) + + return best_r2_scores, best_rmse_scores + +@ignore_warnings(category=ConvergenceWarning) +def compute_diversity(train, fake): + nearest_k = 5 + if train.shape[0] >= 50000: + num = np.random.randint(0, train.shape[0], 50000) + real_features = train[num] + fake_features_lst = [i[num] for i in fake] + else: + num = train.shape[0] + real_features = train[:num] + fake_features_lst = [i[:num] for i in fake] + scores = [] + for i, data in enumerate(fake_features_lst): + fake_features = data + metrics = compute_prdc(real_features=real_features, + fake_features=fake_features, + nearest_k=nearest_k) + metrics['i'] = i + scores.append(metrics) + return pd.DataFrame(scores).mean(axis=0), pd.DataFrame(scores).std(axis=0) + +_EVALUATORS = { + 'binclass': _evaluate_binary_classification, + 'multiclass': _evaluate_multi_classification, + 'regression': _evaluate_regression +} + +def get_evaluator(problem_type): + return _EVALUATORS[problem_type] + + +def compute_scores(train, test, synthesized_data, metadata, eval): + a, b, c = _EVALUATORS[metadata['problem_type']](train=train, test=test, fake=synthesized_data, metadata=metadata, eval=eval) + if eval is None: + return a.mean(axis=0), a.std(axis=0), a[['name','param']] + else: + return a.mean(axis=0), a.std(axis=0) + diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/eval/mle/tabular_dataload.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/eval/mle/tabular_dataload.py new file mode 100644 index 0000000000000000000000000000000000000000..d5561f456cdc32ca553f00c01f1c4b868aef37cb --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/eval/mle/tabular_dataload.py @@ -0,0 +1,111 @@ +# coding=utf-8 +# Copyright 2020 The Google Research Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# pylint: skip-file +"""Return training and evaluation/test datasets from config files.""" +import torch +import numpy as np +import pandas as pd +from tabular_transformer import GeneralTransformer +import json +import logging +import os + +CATEGORICAL = "categorical" +CONTINUOUS = "continuous" + +LOGGER = logging.getLogger(__name__) + +DATA_PATH = os.path.join(os.path.dirname(__file__), 'tabular_datasets') + +def _load_json(path): + with open(path) as json_file: + return json.load(json_file) + + +def _load_file(filename, loader): + local_path = os.path.join(DATA_PATH, filename) + + if loader == np.load: + return loader(local_path, allow_pickle=True) + return loader(local_path) + + +def _get_columns(metadata): + categorical_columns = list() + + for column_idx, column in enumerate(metadata['columns']): + if column['type'] == CATEGORICAL: + categorical_columns.append(column_idx) + + return categorical_columns + + +def load_data(name): + data_dir = f'data/{name}' + info_path = f'{data_dir}/info.json' + + train = pd.read_csv(f'{data_dir}/train.csv').to_numpy() + test = pd.read_csv(f'{data_dir}/test.csv').to_numpy() + + with open(f'{data_dir}/info.json', 'r') as f: + info = json.load(f) + + task_type = info['task_type'] + + num_cols = info['num_col_idx'] + cat_cols = info['cat_col_idx'] + target_cols = info['target_col_idx'] + + if task_type != 'regression': + cat_cols = cat_cols + target_cols + + return train, test, (cat_cols, info) + + +def get_dataset(FLAGS, evaluation=False): + + batch_size = FLAGS.training_batch_size if not evaluation else FLAGS.eval_batch_size + + if batch_size % torch.cuda.device_count() != 0: + raise ValueError(f'Batch sizes ({batch_size} must be divided by' + f'the number of devices ({torch.cuda.device_count()})') + + + # Create dataset builders for tabular data. + train, test, cols = load_data(FLAGS.dataname) + cols_idx = list(np.arange(train.shape[1])) + dis_idx = cols[0] + con_idx = [x for x in cols_idx if x not in dis_idx] + + #split continuous and categorical + train_con = train[:,con_idx] + train_dis = train[:,dis_idx] + + #new index + cat_idx_ = list(np.arange(train_dis.shape[1]))[:len(cols[0])] + + transformer_con = GeneralTransformer() + transformer_dis = GeneralTransformer() + + transformer_con.fit(train_con, []) + transformer_dis.fit(train_dis, cat_idx_) + + train_con_data = transformer_con.transform(train_con) + train_dis_data = transformer_dis.transform(train_dis) + + + return train, train_con_data, train_dis_data, test, (transformer_con, transformer_dis, cols[1]), con_idx, dis_idx + \ No newline at end of file diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/eval/mle/tabular_transformer.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/eval/mle/tabular_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..571e86a298d4b973484c7fd488819e86b5f14d30 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/eval/mle/tabular_transformer.py @@ -0,0 +1,110 @@ +import numpy as np +import pandas as pd + +CATEGORICAL = "categorical" +CONTINUOUS = "continuous" + +class Transformer: + + @staticmethod + def get_metadata(data, categorical_columns=tuple()): + meta = [] + + df = pd.DataFrame(data) + for index in df: + column = df[index] + + if index in categorical_columns: + mapper = column.value_counts().index.tolist() + meta.append({ + "name": index, + "type": CATEGORICAL, + "size": len(mapper), + "i2s": mapper + }) + else: + meta.append({ + "name": index, + "type": CONTINUOUS, + "min": column.min(), + "max": column.max(), + }) + + return meta + + def fit(self, data, categorical_columns=tuple()): + raise NotImplementedError + + def transform(self, data): + raise NotImplementedError + + def inverse_transform(self, data): + raise NotImplementedError + + +class GeneralTransformer(Transformer): + + def __init__(self, act='tanh'): + self.act = act + self.meta = None + self.output_dim = None + + def fit(self, data, categorical_columns=tuple()): + self.meta = self.get_metadata(data, categorical_columns) + self.output_dim = 0 + for info in self.meta: + if info['type'] in [CONTINUOUS]: + self.output_dim += 1 + else: + self.output_dim += info['size'] + + def transform(self, data): + data_t = [] + self.output_info = [] + for id_, info in enumerate(self.meta): + col = data[:, id_] + if info['type'] == CONTINUOUS: + col = (col - (info['min'])) / (info['max'] - info['min']) + if self.act == 'tanh': + col = col * 2 - 1 + data_t.append(col.reshape([-1, 1])) + self.output_info.append((1, self.act)) + + else: + col_t = np.zeros([len(data), info['size']]) + idx = list(map(info['i2s'].index, col)) + col_t[np.arange(len(data)), idx] = 1 + data_t.append(col_t) + self.output_info.append((info['size'], 'softmax')) + + return np.concatenate(data_t, axis=1) + + def inverse_transform(self, data): + if self.meta[1]['type'] == CONTINUOUS: + data_t = np.zeros([len(data), len(self.meta)]) + else: + dtype = np.dtype('U50') + data_t = np.empty([len(data), len(self.meta)], dtype=dtype) + + + data = data.copy() + for id_, info in enumerate(self.meta): + + if info['type'] == CONTINUOUS: + current = data[:, 0] + data = data[:, 1:] + + if self.act == 'tanh': + current = (current + 1) / 2 + + current = np.clip(current, 0, 1) + data_t[:, id_] = current * (info['max'] - info['min']) + info['min'] + + else: + current = data[:, :info['size']] + data = data[:, info['size']:] + idx = np.argmax(current, axis=1) + recovered = list(map(info['i2s'].__getitem__, idx)) + + data_t[:, id_] = recovered + return data_t diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/eval/visualize_density.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/eval/visualize_density.py new file mode 100644 index 0000000000000000000000000000000000000000..d7ee36fac552e916bbb238796e2fb2af1ebe5d50 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/eval/visualize_density.py @@ -0,0 +1,85 @@ +# %% +import numpy as np +import pandas as pd +import torch +import os + +import json + +# Metrics +from sdmetrics.visualization import get_column_plot + +import plotly.io as pio +from PIL import Image +from io import BytesIO + +from tqdm import tqdm +import argparse + +def main(args): + dataname = args.dataname + sample_file_name = args.sample_file_name + + syn_path = f'synthetic/{dataname}/{sample_file_name}' + real_path = f'synthetic/{dataname}/real.csv' + + syn_data = pd.read_csv(syn_path) + real_data = pd.read_csv(real_path) + + print((real_data[:2])) + + data_dir = f'data/{dataname}' + with open(f'{data_dir}/info.json', 'r') as f: + info = json.load(f) + + big_img = plot_density(syn_data, real_data, info) + + save_dir = f"eval/density_graphs/{dataname}" + if not os.path.exists(save_dir): + os.makedirs(save_dir) + save_path = os.path.join(save_dir, sample_file_name.replace('.csv', '.png')) + big_img.save(save_path) + print(f"Saved density graph to {save_path}") + +def plot_density(syn_data, real_data, info, num_per_row=3): + column_names = info['column_names'] + num_cat = len(column_names) + num_col = num_per_row + num_row = (num_cat-1)//num_col+1 + + imgs = [] + for i, col in tqdm(enumerate(column_names), total = len(column_names)): + # plot_type = 'bar' if i in info['cat_col_idx'] else 'distplot' + plot_type = 'bar' if info['metadata']['columns'][str(i)]['sdtype'] == 'categorical' else 'distplot' + if plot_type == 'distplot' and (syn_data[col][0] == syn_data[col]).all(): # to tackle a very weird bug + # If the continuous data all aggregate at a single value, get_column_plot() cannot plot a density curve for it. + # So, we perturb one entry of the cont data by a small amount + print(f"\n ALERT: the generated samples column_{i} with name '{col}' all has the same value of {syn_data[col][0]} \n") + syn_data[col][0] += 1e-5 + fig = get_column_plot( + real_data=real_data, + synthetic_data=syn_data, + column_name=col, + plot_type=plot_type + ) + + img_bytes = pio.to_image(fig, format='png') + img = Image.open(BytesIO(img_bytes)) + imgs.append(img) + + width, height = imgs[0].size + big_img = Image.new('RGB', (width * num_col, height * num_row)) + for i, img in enumerate(imgs): + coordinate = (i%num_col * width, i//num_col * height) + big_img.paste(img, coordinate) + return big_img + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + + parser.add_argument('--dataname', type=str, default='adult') + parser.add_argument('--sample_file_name', type=str, default='tabsyn.csv') + + args = parser.parse_args() + + main(args) \ No newline at end of file diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/main.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/main.py new file mode 100644 index 0000000000000000000000000000000000000000..30864194b14d60566efcbb2c997e95bc3351f49b --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/main.py @@ -0,0 +1,32 @@ +import torch +from ef_vfm.main import main as ef_vfm_main +import argparse + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='Training of EF-VFM (TabbyFlow) for tabular data generation') + + # General configs + parser.add_argument('--dataname', type=str, default='adult', help='Name dataset, one of those in data/ dir') + parser.add_argument('--mode', type=str, default='train', help='train or test') + parser.add_argument('--method', type=str, default='ef_vfm', help='Currently we only release our model EF-VFM. Baselines will be released soon.') + parser.add_argument('--gpu', type=int, default=0, help='GPU index') + parser.add_argument('--debug', action='store_true', help='Enable debug mode') + parser.add_argument('--no_wandb', action='store_true', help='disable wandb') + parser.add_argument('--exp_name', type=str, default=None, help='Experiment name, used to name log directories and the wandb run name') + parser.add_argument('--deterministic', action='store_true', help='Whether to make the entire process deterministic, i.e., fix global random seeds') + + # Configs for testing ef_vfm + parser.add_argument('--num_samples_to_generate', type=int, default=None, help='Number of samples to be generated while testing') + parser.add_argument('--ckpt_path', type=str, default=None, help='Path to the model checkpoint to be tested') + parser.add_argument('--report', action='store_true', help="Report testing mode: this mode sequentially runs test runs and report the avg and std") + parser.add_argument('--num_runs', type=int, default=20, help="Number of runs to be averaged in the report testing mode") + + 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' + + ef_vfm_main(args) \ No newline at end of file diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/process_dataset.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/process_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..38004d944f5ebe15a1147df0bc9e0e1abdef3ed5 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/process_dataset.py @@ -0,0 +1,492 @@ +import numpy as np +import pandas as pd +import os +import sys +import json +import argparse + +from sklearn.preprocessing import OrdinalEncoder +from sklearn import model_selection + +TYPE_TRANSFORM ={ + 'float', np.float32, + 'str', str, + 'int', int +} + +INFO_PATH = 'data/Info' + +parser = argparse.ArgumentParser(description='process dataset') + +# General configs +parser.add_argument('--dataname', type=str, default=None, help='Name of dataset.') +args = parser.parse_args() + +def preprocess_beijing(): + with open(f'{INFO_PATH}/beijing.json', 'r') as f: + info = json.load(f) + + data_path = info['raw_data_path'] + + data_df = pd.read_csv(data_path) + columns = data_df.columns + + data_df = data_df[columns[1:]] + + + df_cleaned = data_df.dropna() + df_cleaned.to_csv(info['data_path'], index = False) + +def preprocess_beijing_dcr(): + with open(f'{INFO_PATH}/beijing_dcr.json', 'r') as f: + info = json.load(f) + + data_path = info['raw_data_path'] + + data_df = pd.read_csv(data_path) + columns = data_df.columns + + data_df = data_df[columns[1:]] + + df_cleaned = data_df.dropna() + df_cleaned.to_csv(info['data_path'], index = False) + +def preprocess_news(remove_cat=False): + name = 'news' if not remove_cat else 'news_nocat' + with open(f'{INFO_PATH}/{name}.json', 'r') as f: + info = json.load(f) + + data_path = info['raw_data_path'] + data_df = pd.read_csv(data_path) + data_df = data_df.drop('url', axis=1) + + columns = np.array(data_df.columns.tolist()) + + cat_columns1 = columns[list(range(12,18))] + cat_columns2 = columns[list(range(30,38))] + + if not remove_cat: + cat_col1 = data_df[cat_columns1].astype(int).to_numpy().argmax(axis = 1) + cat_col2 = data_df[cat_columns2].astype(int).to_numpy().argmax(axis = 1) + + data_df = data_df.drop(cat_columns2, axis=1) + data_df = data_df.drop(cat_columns1, axis=1) + + if not remove_cat: + data_df['data_channel'] = cat_col1 + data_df['weekday'] = cat_col2 + + data_save_path = f'data/{name}/{name}.csv' + data_df.to_csv(f'{data_save_path}', index = False) + + columns = np.array(data_df.columns.tolist()) + num_columns = columns[list(range(45))] + cat_columns = ['data_channel', 'weekday'] if not remove_cat else [] + target_columns = columns[[45]] + + info['num_col_idx'] = list(range(45)) + info['cat_col_idx'] = [46, 47] if not remove_cat else [] + info['target_col_idx'] = [45] + info['data_path'] = data_save_path + + with open(f'{INFO_PATH}/{name}.json', 'w') as file: + json.dump(info, file, indent=4) + +def preprocess_news_dcr(remove_cat=False): + name = 'news_dcr' if not remove_cat else 'news_nocat_dcr' + with open(f'{INFO_PATH}/{name}.json', 'r') as f: + info = json.load(f) + + data_path = info['raw_data_path'] + data_df = pd.read_csv(data_path) + data_df = data_df.drop('url', axis=1) + + columns = np.array(data_df.columns.tolist()) + + cat_columns1 = columns[list(range(12,18))] + cat_columns2 = columns[list(range(30,38))] + + if not remove_cat: + cat_col1 = data_df[cat_columns1].astype(int).to_numpy().argmax(axis = 1) + cat_col2 = data_df[cat_columns2].astype(int).to_numpy().argmax(axis = 1) + + data_df = data_df.drop(cat_columns2, axis=1) + data_df = data_df.drop(cat_columns1, axis=1) + + if not remove_cat: + data_df['data_channel'] = cat_col1 + data_df['weekday'] = cat_col2 + + data_save_path = f'data/{name}/{name}.csv' + data_df.to_csv(f'{data_save_path}', index = False) + + columns = np.array(data_df.columns.tolist()) + num_columns = columns[list(range(45))] + cat_columns = ['data_channel', 'weekday'] if not remove_cat else [] + target_columns = columns[[45]] + + info['num_col_idx'] = list(range(45)) + info['cat_col_idx'] = [46, 47] if not remove_cat else [] + info['target_col_idx'] = [45] + info['data_path'] = data_save_path + + with open(f'{INFO_PATH}/{name}.json', 'w') as file: + json.dump(info, file, indent=4) + + +def get_column_name_mapping(data_df, num_col_idx, cat_col_idx, target_col_idx, column_names = None): + + if not column_names: + column_names = np.array(data_df.columns.tolist()) + + idx_mapping = {} + + curr_num_idx = 0 + curr_cat_idx = len(num_col_idx) + curr_target_idx = curr_cat_idx + len(cat_col_idx) + + for idx in range(len(column_names)): + + if idx in num_col_idx: + idx_mapping[int(idx)] = curr_num_idx + curr_num_idx += 1 + elif idx in cat_col_idx: + idx_mapping[int(idx)] = curr_cat_idx + curr_cat_idx += 1 + else: + idx_mapping[int(idx)] = curr_target_idx + curr_target_idx += 1 + + inverse_idx_mapping = {} + for k, v in idx_mapping.items(): + inverse_idx_mapping[int(v)] = k + + idx_name_mapping = {} + + for i in range(len(column_names)): + idx_name_mapping[int(i)] = column_names[i] + + return idx_mapping, inverse_idx_mapping, idx_name_mapping + + +def train_val_test_split(data_df, cat_columns, num_train = 0, num_test = 0): + total_num = data_df.shape[0] + idx = np.arange(total_num) + + seed = 1234 + + while True: + np.random.seed(seed) + np.random.shuffle(idx) + + train_idx = idx[:num_train] + test_idx = idx[-num_test:] + + train_df = data_df.loc[train_idx] + test_df = data_df.loc[test_idx] + + flag = 0 + for i in cat_columns: + if len(set(train_df[i])) != len(set(data_df[i])): + flag = 1 + break + + if flag == 0: + break + else: + seed += 1 + + return train_df, test_df, seed + + +def process_data(name): + + if name == 'news': + preprocess_news() + elif name == 'news_nocat': + preprocess_news(remove_cat=True) + elif name == 'news_dcr': + preprocess_news_dcr() + elif name == 'beijing': + preprocess_beijing() + elif name == 'beijing_dcr': + preprocess_beijing_dcr() + + with open(f'{INFO_PATH}/{name}.json', 'r') as f: + info = json.load(f) + + data_path = info['data_path'] + if info['file_type'] == 'csv': + data_df = pd.read_csv(data_path, header = info['header']) + + elif info['file_type'] == 'xls': + data_df = pd.read_excel(data_path, sheet_name='Data', header=1) + data_df = data_df.drop('ID', axis=1) + + num_data = data_df.shape[0] + + column_names = info['column_names'] if info['column_names'] else data_df.columns.tolist() + + num_col_idx = info['num_col_idx'] + cat_col_idx = info['cat_col_idx'] + target_col_idx = info['target_col_idx'] + + num_columns = [column_names[i] for i in num_col_idx] + cat_columns = [column_names[i] for i in cat_col_idx] + target_columns = [column_names[i] for i in target_col_idx] + + 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) + + has_val = bool(info['val_path']) + 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 + if info['test_path']: + + # if testing data is given + test_path = info['test_path'] + + 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 + with open(test_path, 'r') as f: + lines = f.readlines()[1:] + test_save_path = f'data/{name}/test.data' + if not os.path.exists(test_save_path): + with open(test_save_path, 'a') as f1: + for line in lines: + save_line = line.strip('\n').strip('.') + f1.write(f'{save_line}\n') + + test_df = pd.read_csv(test_save_path, header = None) + else: + test_df = pd.read_csv(test_path, header = info['header']) + + if has_val: # currently you cannot have a val path without a test path + val_path = info['val_path'] + val_df = pd.read_csv(val_path, header = info['header']) + + train_df = data_df + + 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 + complete_df = pd.concat([train_df, test_df, val_df], axis = 0, ignore_index=True) + num_data = complete_df.shape[0] + num_train = int(num_data*0.5) + num_test = num_data - num_train + complete_df.rename(columns = idx_name_mapping, inplace=True) + train_df, test_df, seed = train_val_test_split(complete_df, cat_columns, num_train, num_test) + + else: + # Train/ Test Split, 90% Training (50% for dcr eval exclusively), 10% Testing (Validation set will be selected from Training set) + if "dcr" in name: + num_train = int(num_data*0.5) + else: + num_train = int(num_data*0.9) + num_test = num_data - num_train + + train_df, test_df, seed = train_val_test_split(data_df, cat_columns, num_train, num_test) + + complete_df = pd.concat([train_df, test_df, val_df], axis = 0) + name_idx_mapping = {val: key for key, val in idx_name_mapping.items()} + int_columns = [] + int_col_idx = [] + int_col_idx_wrt_num = [] + for i, col_idx in enumerate(num_col_idx): + col = column_names[col_idx] + col_data = complete_df.iloc[:,col_idx] + is_int = (col_data%1 == 0).all() + if is_int: + int_columns.append(col) + int_col_idx.append(name_idx_mapping[col]) + int_col_idx_wrt_num.append(i) + info['int_col_idx'] = int_col_idx + info['int_columns'] = int_columns + info['int_col_idx_wrt_num'] = int_col_idx_wrt_num + + train_df.columns = range(len(train_df.columns)) + test_df.columns = range(len(test_df.columns)) + val_df.columns = range(len(val_df.columns)) + + print(name, train_df.shape, val_df.shape, test_df.shape, data_df.shape) + + col_info = {} + + for col_idx in num_col_idx: + col_info[col_idx] = {} + col_info['type'] = 'numerical' + col_info['max'] = float(train_df[col_idx].max()) + col_info['min'] = float(train_df[col_idx].min()) + + for col_idx in cat_col_idx: + col_info[col_idx] = {} + col_info['type'] = 'categorical' + col_info['categorizes'] = list(set(train_df[col_idx])) + + for col_idx in target_col_idx: + if info['task_type'] == 'regression': + col_info[col_idx] = {} + col_info['type'] = 'numerical' + col_info['max'] = float(train_df[col_idx].max()) + col_info['min'] = float(train_df[col_idx].min()) + else: + col_info[col_idx] = {} + col_info['type'] = 'categorical' + col_info['categorizes'] = list(set(train_df[col_idx])) + + info['column_info'] = col_info + + train_df.rename(columns = idx_name_mapping, inplace=True) + test_df.rename(columns = idx_name_mapping, inplace=True) + val_df.rename(columns = idx_name_mapping, inplace=True) + + for col in num_columns: + if (train_df[col] == ' ?').sum() > 0: + print(col) + import pdb; pdb.set_trace() + if (train_df[col] == '?').sum() > 0: + print(col) + import pdb; pdb.set_trace() + train_df.loc[train_df[col] == '?', col] = np.nan + for col in cat_columns: + train_df.loc[train_df[col] == '?', col] = 'nan' + for col in num_columns: + if (test_df[col] == ' ?').sum() > 0: + print(col) + import pdb; pdb.set_trace() + if (test_df[col] == '?').sum() > 0: + print(col) + import pdb; pdb.set_trace() + test_df.loc[test_df[col] == '?', col] = np.nan + for col in cat_columns: + test_df.loc[test_df[col] == '?', col] = 'nan' + for col in num_columns: + val_df.loc[val_df[col] == '?', col] = np.nan + for col in cat_columns: + val_df.loc[val_df[col] == '?', col] = 'nan' + + if train_df.isna().any().any(): + print("Training data contains nan in the numerical cols") + import pdb; pdb.set_trace() + + X_num_train = train_df[num_columns].to_numpy().astype(np.float32) + X_cat_train = train_df[cat_columns].to_numpy() + y_train = train_df[target_columns].to_numpy() + + X_num_test = test_df[num_columns].to_numpy().astype(np.float32) + X_cat_test = test_df[cat_columns].to_numpy() + y_test = test_df[target_columns].to_numpy() + + X_num_val = val_df[num_columns].to_numpy().astype(np.float32) + X_cat_val = val_df[cat_columns].to_numpy() + y_val = val_df[target_columns].to_numpy() + + save_dir = f'data/{name}' + np.save(f'{save_dir}/X_num_train.npy', X_num_train) + np.save(f'{save_dir}/X_cat_train.npy', X_cat_train) + np.save(f'{save_dir}/y_train.npy', y_train) + + np.save(f'{save_dir}/X_num_test.npy', X_num_test) + np.save(f'{save_dir}/X_cat_test.npy', X_cat_test) + np.save(f'{save_dir}/y_test.npy', y_test) + + if has_val: + np.save(f'{save_dir}/X_num_val.npy', X_num_val) + np.save(f'{save_dir}/X_cat_val.npy', X_cat_val) + np.save(f'{save_dir}/y_val.npy', y_val) + + train_df[num_columns] = train_df[num_columns].astype(np.float32) + test_df[num_columns] = test_df[num_columns].astype(np.float32) + val_df[num_columns] = val_df[num_columns].astype(np.float32) + + train_df.to_csv(f'{save_dir}/train.csv', index = False) + test_df.to_csv(f'{save_dir}/test.csv', index = False) + if has_val: + val_df.to_csv(f'{save_dir}/val.csv', index = False) + + if not os.path.exists(f'synthetic/{name}'): + os.makedirs(f'synthetic/{name}') + + train_df.to_csv(f'synthetic/{name}/real.csv', index = False) + test_df.to_csv(f'synthetic/{name}/test.csv', index = False) + + if has_val: + val_df.to_csv(f'synthetic/{name}/val.csv', index = False) + + print('Numerical', X_num_train.shape) + print('Categorical', X_cat_train.shape) + + info['column_names'] = column_names + info['train_num'] = train_df.shape[0] + info['test_num'] = test_df.shape[0] + info['val_num'] = val_df.shape[0] + + info['idx_mapping'] = idx_mapping + info['inverse_idx_mapping'] = inverse_idx_mapping + info['idx_name_mapping'] = idx_name_mapping + + metadata = {'columns': {}} + 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'] + + for i in num_col_idx: + metadata['columns'][i] = {} + metadata['columns'][i]['sdtype'] = 'numerical' + metadata['columns'][i]['computer_representation'] = 'Float' + + for i in cat_col_idx: + metadata['columns'][i] = {} + metadata['columns'][i]['sdtype'] = 'categorical' + + if task_type == 'regression': + + for i in target_col_idx: + metadata['columns'][i] = {} + metadata['columns'][i]['sdtype'] = 'numerical' + metadata['columns'][i]['computer_representation'] = 'Float' + + else: + for i in target_col_idx: + metadata['columns'][i] = {} + metadata['columns'][i]['sdtype'] = 'categorical' + + info['metadata'] = metadata + + with open(f'{save_dir}/info.json', 'w') as file: + json.dump(info, file, indent=4) + + print(f'Processing and Saving {name} Successfully!') + + print(name) + print('Total', info['train_num'] + info['test_num']) + print('Train', info['train_num']) + print('Val', info['val_num']) + print('Test', info['test_num']) + if info['task_type'] == 'regression': + num = len(info['num_col_idx'] + info['target_col_idx']) + cat = len(info['cat_col_idx']) + else: + cat = len(info['cat_col_idx'] + info['target_col_idx']) + num = len(info['num_col_idx']) + print('Num', num) + print('Int', len(info['int_col_idx'])) + print('Cat', cat) + +if __name__ == "__main__": + + if args.dataname: + process_data(args.dataname) + else: + for name in [ + 'adult', + 'default', + 'shoppers', + 'magic', + 'beijing', + 'news', + 'news_nocat', + 'adult_dcr', + 'default_dcr', + 'shoppers_dcr', + 'beijing_dcr', + 'news_dcr', + ]: + process_data(name) + diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/pyproject.toml b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..57737114306b42c08aa9fb800a23b6f746693bab --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/pyproject.toml @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bc2d5c09fdbd3457c0f7cdd1a92c8e44ea3b2ff1316a2b718865fb7e8059da36 +size 1029 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/src/__init__.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/src/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..07d7a4057f36847f7accf4ca148d590d8b4fc80f --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/src/__init__.py @@ -0,0 +1,11 @@ +import torch +from icecream import install + +torch.set_num_threads(1) +install() + +from . import env # noqa +from .data import * # noqa +from .env import * # noqa +from .metrics import * # noqa +from .util import * # noqa \ No newline at end of file diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/src/data.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/src/data.py new file mode 100644 index 0000000000000000000000000000000000000000..c6906ba122d1ff276b7f475b7f6e7c3440580654 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/src/data.py @@ -0,0 +1,780 @@ +import hashlib +from collections import Counter +from copy import deepcopy +from dataclasses import astuple, dataclass, replace +from importlib.resources import path +from pathlib import Path +from typing import Any, Literal, Optional, Union, cast, Tuple, Dict, List + +import numpy as np +import pandas as pd +from sklearn.model_selection import train_test_split +from sklearn.pipeline import make_pipeline +import sklearn.preprocessing +import torch +import os +from category_encoders import LeaveOneOutEncoder +from sklearn.impute import SimpleImputer +from sklearn.preprocessing import StandardScaler +from scipy.spatial.distance import cdist + +from . import env, util +from .metrics import calculate_metrics as calculate_metrics_ +from .util import TaskType, load_json + +ArrayDict = Dict[str, np.ndarray] +TensorDict = Dict[str, torch.Tensor] + + +CAT_MISSING_VALUE = 'nan' +CAT_RARE_VALUE = '__rare__' +Normalization = Literal['standard', 'quantile', 'minmax'] +NumNanPolicy = Literal['drop-rows', 'mean'] +CatNanPolicy = Literal['most_frequent'] +CatEncoding = Literal['one-hot', 'counter'] +YPolicy = Literal['default'] +DEQUANT_DIST = Literal['uniform', 'beta', 'round', 'none'] + + +class StandardScaler1d(StandardScaler): + def partial_fit(self, X, *args, **kwargs): + assert X.ndim == 1 + return super().partial_fit(X[:, None], *args, **kwargs) + + def transform(self, X, *args, **kwargs): + assert X.ndim == 1 + return super().transform(X[:, None], *args, **kwargs).squeeze(1) + + def inverse_transform(self, X, *args, **kwargs): + assert X.ndim == 1 + return super().inverse_transform(X[:, None], *args, **kwargs).squeeze(1) + + +def get_category_sizes(X: Union[torch.Tensor, np.ndarray]) -> List[int]: + XT = X.T.cpu().tolist() if isinstance(X, torch.Tensor) else X.T.tolist() + return [len(set(x)) for x in XT] + + +@dataclass(frozen=False) +class Dataset: + X_num: Optional[ArrayDict] + X_cat: Optional[ArrayDict] + y: ArrayDict + int_col_idx_wrt_num: list + y_info: Dict[str, Any] + task_type: TaskType + n_classes: Optional[int] + + @classmethod + def from_dir(cls, dir_: Union[Path, str]) -> 'Dataset': + dir_ = Path(dir_) + splits = [k for k in ['train', 'test'] if dir_.joinpath(f'y_{k}.npy').exists()] + + def load(item) -> ArrayDict: + return { + x: cast(np.ndarray, np.load(dir_ / f'{item}_{x}.npy', allow_pickle=True)) # type: ignore[code] + for x in splits + } + + if Path(dir_ / 'info.json').exists(): + info = util.load_json(dir_ / 'info.json') + else: + info = None + return Dataset( + load('X_num') if dir_.joinpath('X_num_train.npy').exists() else None, + load('X_cat') if dir_.joinpath('X_cat_train.npy').exists() else None, + load('y'), + {}, + TaskType(info['task_type']), + info.get('n_classes'), + ) + + @property + def is_binclass(self) -> bool: + return self.task_type == TaskType.BINCLASS + + @property + def is_multiclass(self) -> bool: + return self.task_type == TaskType.MULTICLASS + + @property + def is_regression(self) -> bool: + return self.task_type == TaskType.REGRESSION + + @property + def n_num_features(self) -> int: + return 0 if self.X_num is None else self.X_num['train'].shape[1] + + @property + def n_cat_features(self) -> int: + return 0 if self.X_cat is None else self.X_cat['train'].shape[1] + + @property + def n_features(self) -> int: + return self.n_num_features + self.n_cat_features + + def size(self, part: Optional[str]) -> int: + return sum(map(len, self.y.values())) if part is None else len(self.y[part]) + + @property + def nn_output_dim(self) -> int: + if self.is_multiclass: + assert self.n_classes is not None + return self.n_classes + else: + return 1 + + def get_category_sizes(self, part: str) -> List[int]: + return [] if self.X_cat is None else get_category_sizes(self.X_cat[part]) + + def calculate_metrics( + self, + predictions: Dict[str, np.ndarray], + prediction_type: Optional[str], + ) -> Dict[str, Any]: + metrics = { + x: calculate_metrics_( + self.y[x], predictions[x], self.task_type, prediction_type, self.y_info + ) + for x in predictions + } + if self.task_type == TaskType.REGRESSION: + score_key = 'rmse' + score_sign = -1 + else: + score_key = 'accuracy' + score_sign = 1 + for part_metrics in metrics.values(): + part_metrics['score'] = score_sign * part_metrics[score_key] + return metrics + +def change_val(dataset: Dataset, val_size: float = 0.2): + # should be done before transformations + + y = np.concatenate([dataset.y['train'], dataset.y['val']], axis=0) + + ixs = np.arange(y.shape[0]) + if dataset.is_regression: + train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777) + else: + train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777, stratify=y) + + dataset.y['train'] = y[train_ixs] + dataset.y['val'] = y[val_ixs] + + if dataset.X_num is not None: + X_num = np.concatenate([dataset.X_num['train'], dataset.X_num['val']], axis=0) + dataset.X_num['train'] = X_num[train_ixs] + dataset.X_num['val'] = X_num[val_ixs] + + if dataset.X_cat is not None: + X_cat = np.concatenate([dataset.X_cat['train'], dataset.X_cat['val']], axis=0) + dataset.X_cat['train'] = X_cat[train_ixs] + dataset.X_cat['val'] = X_cat[val_ixs] + + return dataset + +def num_process_nans(dataset: Dataset, policy: Optional[NumNanPolicy]) -> Dataset: + + assert dataset.X_num is not None + nan_masks = {k: np.isnan(v) for k, v in dataset.X_num.items()} + if not any(x.any() for x in nan_masks.values()): # type: ignore[code] + # assert policy is None + print('No NaNs in numerical features, skipping') + return dataset + + assert policy is not None + if policy == 'drop-rows': + valid_masks = {k: ~v.any(1) for k, v in nan_masks.items()} + assert valid_masks[ + 'test' + ].all(), 'Cannot drop test rows, since this will affect the final metrics.' + new_data = {} + for data_name in ['X_num', 'X_cat', 'y']: + data_dict = getattr(dataset, data_name) + if data_dict is not None: + new_data[data_name] = { + k: v[valid_masks[k]] for k, v in data_dict.items() + } + dataset = replace(dataset, **new_data) + elif policy == 'mean': + new_values = np.nanmean(dataset.X_num['train'], axis=0) + X_num = deepcopy(dataset.X_num) + for k, v in X_num.items(): + num_nan_indices = np.where(nan_masks[k]) + v[num_nan_indices] = np.take(new_values, num_nan_indices[1]) + dataset = replace(dataset, X_num=X_num) + else: + assert util.raise_unknown('policy', policy) + return dataset + + +# Inspired by: https://github.com/yandex-research/rtdl/blob/a4c93a32b334ef55d2a0559a4407c8306ffeeaee/lib/data.py#L20 +def normalize( + X: ArrayDict, normalization: Normalization, seed: Optional[int], return_normalizer : bool = False +) -> ArrayDict: + X_train = X['train'] + if normalization == 'standard': + normalizer = sklearn.preprocessing.StandardScaler() + elif normalization == 'minmax': + normalizer = sklearn.preprocessing.MinMaxScaler() + elif normalization == 'quantile': + normalizer = sklearn.preprocessing.QuantileTransformer( + output_distribution='normal', + n_quantiles=max(min(X['train'].shape[0] // 30, 1000), 10), + subsample=int(1e9), + random_state=seed, + ) + # noise = 1e-3 + # if noise > 0: + # assert seed is not None + # stds = np.std(X_train, axis=0, keepdims=True) + # noise_std = noise / np.maximum(stds, noise) # type: ignore[code] + # X_train = X_train + noise_std * np.random.default_rng(seed).standard_normal( + # X_train.shape + # ) + else: + util.raise_unknown('normalization', normalization) + + normalizer.fit(X_train) + if return_normalizer: + return {k: normalizer.transform(v) for k, v in X.items()}, normalizer + return {k: normalizer.transform(v) for k, v in X.items()} + +class dequantizer: + def __init__( + self, + dequant_dist: DEQUANT_DIST, + int_col_idx_wrt_num: list, + int_dequant_factor: float, + # return_dequantizer: bool = False + ): + self.dequant_dist = dequant_dist + self.int_col_idx_wrt_num = int_col_idx_wrt_num + self.int_dequant_factor = int_dequant_factor + def transform(self, X): + X_int = X[:, self.int_col_idx_wrt_num] + if self.dequant_dist == 'uniform': + X[:, self.int_col_idx_wrt_num] = X_int+ np.random.uniform(size=X_int.shape) * self.int_dequant_factor + elif self.dequant_dist == 'beta': + 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 + elif self.dequant_dist in ['round', 'none']: + pass + return X + def inverse_transform(self, X): + X_int = X[:, self.int_col_idx_wrt_num] + if self.dequant_dist == 'uniform': + X[:, self.int_col_idx_wrt_num] = np.floor(X_int) + elif self.dequant_dist == 'beta': + X[:, self.int_col_idx_wrt_num] = np.rint(X_int) + elif self.dequant_dist == 'round': + X[:, self.int_col_idx_wrt_num] = np.rint(X_int) + elif self.dequant_dist == 'none': + pass + return X + + + # if return_dequantizer: + # return {k: transform(v) for k, v in X.items()}, inverse_transform + # return {k: transform(v) for k, v in X.items()} + +def cat_process_nans(X: ArrayDict, policy: Optional[CatNanPolicy]) -> ArrayDict: + assert X is not None + nan_masks = {k: v == CAT_MISSING_VALUE for k, v in X.items()} + if any(x.any() for x in nan_masks.values()): # type: ignore[code] + if policy is None: + X_new = X + elif policy == 'most_frequent': + imputer = SimpleImputer(missing_values=CAT_MISSING_VALUE, strategy=policy) # type: ignore[code] + imputer.fit(X['train']) + X_new = {k: cast(np.ndarray, imputer.transform(v)) for k, v in X.items()} + else: + util.raise_unknown('categorical NaN policy', policy) + else: + assert policy is None + X_new = X + return X_new + + +def cat_drop_rare(X: ArrayDict, min_frequency: float) -> ArrayDict: + assert 0.0 < min_frequency < 1.0 + min_count = round(len(X['train']) * min_frequency) + X_new = {x: [] for x in X} + for column_idx in range(X['train'].shape[1]): + counter = Counter(X['train'][:, column_idx].tolist()) + popular_categories = {k for k, v in counter.items() if v >= min_count} + for part in X_new: + X_new[part].append( + [ + (x if x in popular_categories else CAT_RARE_VALUE) + for x in X[part][:, column_idx].tolist() + ] + ) + return {k: np.array(v).T for k, v in X_new.items()} + + +def cat_encode( + X: ArrayDict, + encoding: Optional[CatEncoding], + y_train: Optional[np.ndarray], + seed: Optional[int], + return_encoder : bool = False +) -> Tuple[ArrayDict, bool, Optional[Any]]: # (X, is_converted_to_numerical) + if encoding != 'counter': + y_train = None + + # Step 1. Map strings to 0-based ranges + + if encoding is None: + unknown_value = np.iinfo('int64').max - 3 + oe = sklearn.preprocessing.OrdinalEncoder( + handle_unknown='use_encoded_value', # type: ignore[code] + unknown_value=unknown_value, # type: ignore[code] + dtype='int64', # type: ignore[code] + ).fit(X['train']) + encoder = make_pipeline(oe) + encoder.fit(X['train']) + X = {k: encoder.transform(v) for k, v in X.items()} + max_values = X['train'].max(axis=0) + for part in X.keys(): + if part == 'train': continue + for column_idx in range(X[part].shape[1]): + X[part][X[part][:, column_idx] == unknown_value, column_idx] = ( + max_values[column_idx] + 1 + ) + if return_encoder: + return (X, False, encoder) + return (X, False) + + # Step 2. Encode. + + elif encoding == 'one-hot': + ohe = sklearn.preprocessing.OneHotEncoder( + handle_unknown='ignore', sparse_output=False, dtype=np.float32 # type: ignore[code] + ) + encoder = make_pipeline(ohe) + + # encoder.steps.append(('ohe', ohe)) + encoder.fit(X['train']) + X = {k: encoder.transform(v) for k, v in X.items()} + + elif encoding == 'counter': + assert y_train is not None + assert seed is not None + loe = LeaveOneOutEncoder(sigma=0.1, random_state=seed, return_df=False) + encoder.steps.append(('loe', loe)) + encoder.fit(X['train'], y_train) + X = {k: encoder.transform(v).astype('float32') for k, v in X.items()} # type: ignore[code] + if not isinstance(X['train'], pd.DataFrame): + X = {k: v.values for k, v in X.items()} # type: ignore[code] + else: + util.raise_unknown('encoding', encoding) + + if return_encoder: + return X, True, encoder # type: ignore[code] + return (X, True) + + +def build_target( + y: ArrayDict, policy: Optional[YPolicy], task_type: TaskType +) -> Tuple[ArrayDict, Dict[str, Any]]: + info: Dict[str, Any] = {'policy': policy} + if policy is None: + pass + elif policy == 'default': + if task_type == TaskType.REGRESSION: + mean, std = float(y['train'].mean()), float(y['train'].std()) + y = {k: (v - mean) / std for k, v in y.items()} + info['mean'] = mean + info['std'] = std + else: + util.raise_unknown('policy', policy) + return y, info + + +@dataclass(frozen=True) +class Transformations: + seed: int = 0 + normalization: Optional[Normalization] = None + num_nan_policy: Optional[NumNanPolicy] = None + cat_nan_policy: Optional[CatNanPolicy] = None + cat_min_frequency: Optional[float] = None + cat_encoding: Optional[CatEncoding] = None + y_policy: Optional[YPolicy] = 'default' + dequant_dist: Optional[DEQUANT_DIST] = None + int_dequant_factor: Optional[float] = 0.0 + + +def transform_dataset( + dataset: Dataset, + transformations: Transformations, + cache_dir: Optional[Path], + return_transforms: bool = False +) -> Dataset: + # WARNING: the order of transformations matters. Moreover, the current + # implementation is not ideal in that sense. + if cache_dir is not None: + transformations_md5 = hashlib.md5( + str(transformations).encode('utf-8') + ).hexdigest() + transformations_str = '__'.join(map(str, astuple(transformations))) + cache_path = ( + cache_dir / f'cache__{transformations_str}__{transformations_md5}.pickle' + ) + if cache_path.exists(): + cache_transformations, value = util.load_pickle(cache_path) + if transformations == cache_transformations: + print( + f"Using cached features: {cache_dir.name + '/' + cache_path.name}" + ) + return value + else: + raise RuntimeError(f'Hash collision for {cache_path}') + else: + cache_path = None + + if dataset.X_num is not None: + dataset = num_process_nans(dataset, transformations.num_nan_policy) + + num_transform = None + int_transform = None + cat_transform = None + X_num = dataset.X_num + + int_col_idx_wrt_num = dataset.int_col_idx_wrt_num + if X_num is not None and int_col_idx_wrt_num and transformations.dequant_dist is not None: + int_transform = dequantizer( + transformations.dequant_dist, + int_col_idx_wrt_num, + transformations.int_dequant_factor, + ) + X_num = {k: int_transform.transform(v) for k, v in X_num.items()} + + if X_num is not None and transformations.normalization is not None: + has_num = all([x.shape[1]>0 for x in dataset.X_num.values()]) + if has_num: + X_num, num_transform = normalize( + X_num, + transformations.normalization, + transformations.seed, + return_normalizer=True + ) + num_transform = num_transform + + if dataset.X_cat is None: + assert transformations.cat_nan_policy is None + assert transformations.cat_min_frequency is None + # assert transformations.cat_encoding is None + X_cat = None + else: + has_cat = all([x.shape[1]>0 for x in dataset.X_cat.values()]) + if not has_cat: + assert transformations.cat_nan_policy is None + assert transformations.cat_min_frequency is None + X_cat = dataset.X_cat + for split in X_cat.keys(): # a patch to make sure that the empty array is transformed into int dtype + X_cat[split] = X_cat[split].astype(np.int64) + else: + X_cat = cat_process_nans(dataset.X_cat, transformations.cat_nan_policy) + + if transformations.cat_min_frequency is not None: + X_cat = cat_drop_rare(X_cat, transformations.cat_min_frequency) + X_cat, is_num, cat_transform = cat_encode( + X_cat, + transformations.cat_encoding, + dataset.y['train'], + transformations.seed, + return_encoder=True + ) + + if is_num: + X_num = ( + X_cat + if X_num is None + else {x: np.hstack([X_num[x], X_cat[x]]) for x in X_num} + ) + X_cat = None + + + y, y_info = build_target(dataset.y, transformations.y_policy, dataset.task_type) + + dataset = replace(dataset, X_num=X_num, X_cat=X_cat, y=y, y_info=y_info) + dataset.num_transform = num_transform + dataset.int_transform = int_transform + dataset.cat_transform = cat_transform + + if cache_path is not None: + util.dump_pickle((transformations, dataset), cache_path) + # if return_transforms: + # return dataset, num_transform, cat_transform + return dataset + + +def build_dataset( + path: Union[str, Path], + transformations: Transformations, + cache: bool +) -> Dataset: + path = Path(path) + dataset = Dataset.from_dir(path) + return transform_dataset(dataset, transformations, path if cache else None) + + +def prepare_tensors( + dataset: Dataset, device: Union[str, torch.device] +) -> Tuple[Optional[TensorDict], Optional[TensorDict], TensorDict]: + X_num, X_cat, Y = ( + None if x is None else {k: torch.as_tensor(v) for k, v in x.items()} + for x in [dataset.X_num, dataset.X_cat, dataset.y] + ) + if device.type != 'cpu': + X_num, X_cat, Y = ( + None if x is None else {k: v.to(device) for k, v in x.items()} + for x in [X_num, X_cat, Y] + ) + assert X_num is not None + assert Y is not None + if not dataset.is_multiclass: + Y = {k: v.float() for k, v in Y.items()} + return X_num, X_cat, Y + +############### +## DataLoader## +############### + +class TabDataset(torch.utils.data.Dataset): + def __init__( + self, dataset : Dataset, split : Literal['train', 'val', 'test'] + ): + super().__init__() + + self.X_num = torch.from_numpy(dataset.X_num[split]) if dataset.X_num is not None else None + self.X_cat = torch.from_numpy(dataset.X_cat[split]) if dataset.X_cat is not None else None + self.y = torch.from_numpy(dataset.y[split]) + + assert self.y is not None + assert self.X_num is not None or self.X_cat is not None + + def __len__(self): + return len(self.y) + + def __getitem__(self, idx): + out_dict = { + 'y': self.y[idx].long() if self.y is not None else None, + } + + x = np.empty((0,)) + if self.X_num is not None: + x = self.X_num[idx] + if self.X_cat is not None: + x = torch.cat([x, self.X_cat[idx]], dim=0) + return x.float(), out_dict + +def prepare_dataloader( + dataset : Dataset, + split : str, + batch_size: int, +): + + torch_dataset = TabDataset(dataset, split) + loader = torch.utils.data.DataLoader( + torch_dataset, + batch_size=batch_size, + shuffle=(split == 'train'), + num_workers=1, + ) + while True: + yield from loader + +def prepare_torch_dataloader( + dataset : Dataset, + split : str, + shuffle : bool, + batch_size: int, +) -> torch.utils.data.DataLoader: + + torch_dataset = TabDataset(dataset, split) + loader = torch.utils.data.DataLoader(torch_dataset, batch_size=batch_size, shuffle=shuffle, num_workers=1) + + return loader + +def dataset_from_csv(paths : Dict[str, str], cat_features, target, T): + assert 'train' in paths + y = {} + X_num = {} + X_cat = {} if len(cat_features) else None + for split in paths.keys(): + df = pd.read_csv(paths[split]) + y[split] = df[target].to_numpy().astype(float) + if X_cat is not None: + X_cat[split] = df[cat_features].to_numpy().astype(str) + X_num[split] = df.drop(cat_features + [target], axis=1).to_numpy().astype(float) + + dataset = Dataset(X_num, X_cat, y, {}, None, len(np.unique(y['train']))) + return transform_dataset(dataset, T, None) + +class FastTensorDataLoader: + """ + A DataLoader-like object for a set of tensors that can be much faster than + TensorDataset + DataLoader because dataloader grabs individual indices of + the dataset and calls cat (slow). + Source: https://discuss.pytorch.org/t/dataloader-much-slower-than-manual-batching/27014/6 + """ + def __init__(self, *tensors, batch_size=32, shuffle=False): + """ + Initialize a FastTensorDataLoader. + :param *tensors: tensors to store. Must have the same length @ dim 0. + :param batch_size: batch size to load. + :param shuffle: if True, shuffle the data *in-place* whenever an + iterator is created out of this object. + :returns: A FastTensorDataLoader. + """ + assert all(t.shape[0] == tensors[0].shape[0] for t in tensors) + self.tensors = tensors + + self.dataset_len = self.tensors[0].shape[0] + self.batch_size = batch_size + self.shuffle = shuffle + + # Calculate # batches + n_batches, remainder = divmod(self.dataset_len, self.batch_size) + if remainder > 0: + n_batches += 1 + self.n_batches = n_batches + def __iter__(self): + if self.shuffle: + r = torch.randperm(self.dataset_len) + self.tensors = [t[r] for t in self.tensors] + self.i = 0 + return self + + def __next__(self): + if self.i >= self.dataset_len: + raise StopIteration + batch = tuple(t[self.i:self.i+self.batch_size] for t in self.tensors) + self.i += self.batch_size + return batch + + def __len__(self): + return self.n_batches + +def prepare_fast_dataloader( + D : Dataset, + split : str, + batch_size: int +): + + X = torch.from_numpy(np.concatenate([D.X_num[split], D.X_cat[split]], axis=1)).float() + dataloader = FastTensorDataLoader(X, batch_size=batch_size, shuffle=(split=='train')) + while True: + yield from dataloader + +def prepare_fast_torch_dataloader( + D : Dataset, + split : str, + batch_size: int +): + if D.X_cat is not None: + X = torch.from_numpy(np.concatenate([D.X_num[split], D.X_cat[split]], axis=1)).float() + else: + X = torch.from_numpy(D.X_num[split]).float() + y = torch.from_numpy(D.y[split]) + dataloader = FastTensorDataLoader(X, y, batch_size=batch_size, shuffle=(split=='train')) + return dataloader + +def round_columns(X_real, X_synth, columns): + for col in columns: + uniq = np.unique(X_real[:,col]) + dist = cdist(X_synth[:, col][:, np.newaxis].astype(float), uniq[:, np.newaxis].astype(float)) + X_synth[:, col] = uniq[dist.argmin(axis=1)] + return X_synth + +def concat_features(D : Dataset): + if D.X_num is None: + assert D.X_cat is not None + X = {k: pd.DataFrame(v, columns=range(D.n_features)) for k, v in D.X_cat.items()} + elif D.X_cat is None: + assert D.X_num is not None + X = {k: pd.DataFrame(v, columns=range(D.n_features)) for k, v in D.X_num.items()} + else: + X = { + part: pd.concat( + [ + pd.DataFrame(D.X_num[part], columns=range(D.n_num_features)), + pd.DataFrame( + D.X_cat[part], + columns=range(D.n_num_features, D.n_features), + ), + ], + axis=1, + ) + for part in D.y.keys() + } + + return X + +def concat_to_pd(X_num, X_cat, y): + if X_num is None: + return pd.concat([ + pd.DataFrame(X_cat, columns=list(range(X_cat.shape[1]))), + pd.DataFrame(y, columns=['y']) + ], axis=1) + if X_cat is not None: + return pd.concat([ + pd.DataFrame(X_num, columns=list(range(X_num.shape[1]))), + pd.DataFrame(X_cat, columns=list(range(X_num.shape[1], X_num.shape[1] + X_cat.shape[1]))), + pd.DataFrame(y, columns=['y']) + ], axis=1) + return pd.concat([ + pd.DataFrame(X_num, columns=list(range(X_num.shape[1]))), + pd.DataFrame(y, columns=['y']) + ], axis=1) + +def read_pure_data(path, split='train'): + y = np.load(os.path.join(path, f'y_{split}.npy'), allow_pickle=True) + X_num = None + X_cat = None + if os.path.exists(os.path.join(path, f'X_num_{split}.npy')): + X_num = np.load(os.path.join(path, f'X_num_{split}.npy'), allow_pickle=True) + if os.path.exists(os.path.join(path, f'X_cat_{split}.npy')): + X_cat = np.load(os.path.join(path, f'X_cat_{split}.npy'), allow_pickle=True) + + return X_num, X_cat, y + +def read_changed_val(path, val_size=0.2): + path = Path(path) + X_num_train, X_cat_train, y_train = read_pure_data(path, 'train') + X_num_val, X_cat_val, y_val = read_pure_data(path, 'val') + is_regression = load_json(path / 'info.json')['task_type'] == 'regression' + + y = np.concatenate([y_train, y_val], axis=0) + + ixs = np.arange(y.shape[0]) + if is_regression: + train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777) + else: + train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777, stratify=y) + y_train = y[train_ixs] + y_val = y[val_ixs] + + if X_num_train is not None: + X_num = np.concatenate([X_num_train, X_num_val], axis=0) + X_num_train = X_num[train_ixs] + X_num_val = X_num[val_ixs] + + if X_cat_train is not None: + X_cat = np.concatenate([X_cat_train, X_cat_val], axis=0) + X_cat_train = X_cat[train_ixs] + X_cat_val = X_cat[val_ixs] + + return X_num_train, X_cat_train, y_train, X_num_val, X_cat_val, y_val + +############# + +def load_dataset_info(dataset_dir_name: str) -> Dict[str, Any]: + path = Path("data/" + dataset_dir_name) + info = util.load_json(path / 'info.json') + info['size'] = info['train_size'] + info['val_size'] + info['test_size'] + info['n_features'] = info['n_num_features'] + info['n_cat_features'] + info['path'] = path + return info \ No newline at end of file diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/src/env.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/src/env.py new file mode 100644 index 0000000000000000000000000000000000000000..0b9dd619f31450414a9b31585aa58b9121834fbe --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/src/env.py @@ -0,0 +1,39 @@ +""" +Have not used in TabDDPM project. +""" + +import datetime +import os +import shutil +import typing as ty +from pathlib import Path + +PROJ = Path('tab-ddpm/').absolute().resolve() +EXP = PROJ / 'exp' +DATA = PROJ / 'data' + + +def get_path(path: ty.Union[str, Path]) -> Path: + if isinstance(path, str): + path = Path(path) + if not path.is_absolute(): + path = PROJ / path + return path.resolve() + + +def get_relative_path(path: ty.Union[str, Path]) -> Path: + return get_path(path).relative_to(PROJ) + + +def duplicate_path( + src: ty.Union[str, Path], alternative_project_dir: ty.Union[str, Path] +) -> None: + src = get_path(src) + alternative_project_dir = get_path(alternative_project_dir) + dst = alternative_project_dir / src.relative_to(PROJ) + dst.parent.mkdir(parents=True, exist_ok=True) + if dst.exists(): + dst = dst.with_name( + dst.name + '_' + datetime.datetime.now().strftime('%Y%m%dT%H%M%S') + ) + (shutil.copytree if src.is_dir() else shutil.copyfile)(src, dst) \ No newline at end of file diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/src/metrics.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/src/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..188a9be3f8e9d59b07688aa189a876660dbef7cd --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/src/metrics.py @@ -0,0 +1,157 @@ +import enum +from typing import Any, Optional, Tuple, Dict, Union, cast +from functools import partial + +import numpy as np +import scipy.special +import sklearn.metrics as skm + +from . import util +from .util import TaskType + + +class PredictionType(enum.Enum): + LOGITS = 'logits' + PROBS = 'probs' + +class MetricsReport: + def __init__(self, report: dict, task_type: TaskType): + self._res = {k: {} for k in report.keys()} + if task_type in (TaskType.BINCLASS, TaskType.MULTICLASS): + self._metrics_names = ["acc", "f1"] + for k in report.keys(): + self._res[k]["acc"] = report[k]["accuracy"] + self._res[k]["f1"] = report[k]["macro avg"]["f1-score"] + if task_type == TaskType.BINCLASS: + self._res[k]["roc_auc"] = report[k]["roc_auc"] + self._metrics_names.append("roc_auc") + + elif task_type == TaskType.REGRESSION: + self._metrics_names = ["r2", "rmse"] + for k in report.keys(): + self._res[k]["r2"] = report[k]["r2"] + self._res[k]["rmse"] = report[k]["rmse"] + else: + raise "Unknown TaskType!" + + def get_splits_names(self) -> list[str]: + return self._res.keys() + + def get_metrics_names(self) -> list[str]: + return self._metrics_names + + def get_metric(self, split: str, metric: str) -> float: + return self._res[split][metric] + + def get_val_score(self) -> float: + return self._res["val"]["r2"] if "r2" in self._res["val"] else self._res["val"]["f1"] + + def get_test_score(self) -> float: + return self._res["test"]["r2"] if "r2" in self._res["test"] else self._res["test"]["f1"] + + def print_metrics(self) -> None: + res = { + "val": {k: np.around(self._res["val"][k], 4) for k in self._res["val"]}, + "test": {k: np.around(self._res["test"][k], 4) for k in self._res["test"]} + } + + print("*"*100) + print("[val]") + print(res["val"]) + print("[test]") + print(res["test"]) + + return res + +class SeedsMetricsReport: + def __init__(self): + self._reports = [] + + def add_report(self, report: MetricsReport) -> None: + self._reports.append(report) + + def get_mean_std(self) -> dict: + res = {k: {} for k in ["train", "val", "test"]} + for split in self._reports[0].get_splits_names(): + for metric in self._reports[0].get_metrics_names(): + res[split][metric] = [x.get_metric(split, metric) for x in self._reports] + + agg_res = {k: {} for k in ["train", "val", "test"]} + for split in self._reports[0].get_splits_names(): + for metric in self._reports[0].get_metrics_names(): + for k, f in [("count", len), ("mean", np.mean), ("std", np.std)]: + agg_res[split][f"{metric}-{k}"] = f(res[split][metric]) + self._res = res + self._agg_res = agg_res + + return agg_res + + def print_result(self) -> dict: + res = {split: {k: float(np.around(self._agg_res[split][k], 4)) for k in self._agg_res[split]} for split in ["val", "test"]} + print("="*100) + print("EVAL RESULTS:") + print("[val]") + print(res["val"]) + print("[test]") + print(res["test"]) + print("="*100) + return res + +def calculate_rmse( + y_true: np.ndarray, y_pred: np.ndarray, std = None) -> float: + rmse = skm.mean_squared_error(y_true, y_pred) ** 0.5 + if std is not None: + rmse *= std + return rmse + + +def _get_labels_and_probs( + y_pred: np.ndarray, task_type: TaskType, prediction_type: Optional[PredictionType] +) -> Tuple[np.ndarray, Optional[np.ndarray]]: + assert task_type in (TaskType.BINCLASS, TaskType.MULTICLASS) + + if prediction_type is None: + return y_pred, None + + if prediction_type == PredictionType.LOGITS: + probs = ( + scipy.special.expit(y_pred) + if task_type == TaskType.BINCLASS + else scipy.special.softmax(y_pred, axis=1) + ) + elif prediction_type == PredictionType.PROBS: + probs = y_pred + else: + util.raise_unknown('prediction_type', prediction_type) + + assert probs is not None + labels = np.round(probs) if task_type == TaskType.BINCLASS else probs.argmax(axis=1) + return labels.astype('int64'), probs + + +def calculate_metrics( + y_true: np.ndarray, + y_pred: np.ndarray, + task_type: Union[str, TaskType], + prediction_type: Optional[Union[str, PredictionType]], + y_info: Dict[str, Any], +) -> Dict[str, Any]: + # Example: calculate_metrics(y_true, y_pred, 'binclass', 'logits', {}) + task_type = TaskType(task_type) + if prediction_type is not None: + prediction_type = PredictionType(prediction_type) + + if task_type == TaskType.REGRESSION: + assert prediction_type is None + assert 'std' in y_info + rmse = calculate_rmse(y_true, y_pred, y_info['std']) + r2 = skm.r2_score(y_true, y_pred) + result = {'rmse': rmse, 'r2': r2} + else: + labels, probs = _get_labels_and_probs(y_pred, task_type, prediction_type) + result = cast( + Dict[str, Any], skm.classification_report(y_true, labels, output_dict=True) + ) + if task_type == TaskType.BINCLASS: + result['roc_auc'] = skm.roc_auc_score(y_true, probs) + return result \ No newline at end of file diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/src/util.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/src/util.py new file mode 100644 index 0000000000000000000000000000000000000000..e105c961803b3bf0f8282e673eed8e84eaaa3891 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/src/util.py @@ -0,0 +1,347 @@ +import argparse +import atexit +import enum +import json +import os +import pickle +import shutil +import sys +import time +import uuid +from copy import deepcopy +from dataclasses import asdict, fields, is_dataclass +from pathlib import Path +from pprint import pprint +from typing import Any, Callable, List, Dict, Type, Optional, Tuple, TypeVar, Union, cast, get_args, get_origin + +import __main__ +import numpy as np +import tomli +import tomli_w +import torch +import typing as ty + +from . import env + +RawConfig = Dict[str, Any] +Report = Dict[str, Any] +T = TypeVar('T') + + +class Part(enum.Enum): + TRAIN = 'train' + VAL = 'val' + TEST = 'test' + + def __str__(self) -> str: + return self.value + + +class TaskType(enum.Enum): + BINCLASS = 'binclass' + MULTICLASS = 'multiclass' + REGRESSION = 'regression' + + def __str__(self) -> str: + return self.value + + + +def update_training_log(training_log, data, metrics): + def _update(log_part, data_part): + for k, v in data_part.items(): + if isinstance(v, dict): + _update(log_part.setdefault(k, {}), v) + elif isinstance(v, list): + log_part.setdefault(k, []).extend(v) + else: + log_part.setdefault(k, []).append(v) + + _update(training_log, data) + transposed_metrics = {} + for part, part_metrics in metrics.items(): + for metric_name, value in part_metrics.items(): + transposed_metrics.setdefault(metric_name, {})[part] = value + _update(training_log, transposed_metrics) + + +def raise_unknown(unknown_what: str, unknown_value: Any): + raise ValueError(f'Unknown {unknown_what}: {unknown_value}') + + +def _replace(data, condition, value): + def do(x): + if isinstance(x, dict): + return {k: do(v) for k, v in x.items()} + elif isinstance(x, list): + return [do(y) for y in x] + else: + return value if condition(x) else x + + return do(data) + + +_CONFIG_NONE = '__none__' + + +def unpack_config(config: RawConfig) -> RawConfig: + config = cast(RawConfig, _replace(config, lambda x: x == _CONFIG_NONE, None)) + return config + + +def pack_config(config: RawConfig) -> RawConfig: + config = cast(RawConfig, _replace(config, lambda x: x is None, _CONFIG_NONE)) + return config + + +def load_config(path: Union[Path, str]) -> Any: + with open(path, 'rb') as f: + return unpack_config(tomli.load(f)) + + +def dump_config(config: Any, path: Union[Path, str]) -> None: + with open(path, 'wb') as f: + tomli_w.dump(pack_config(config), f) + # check that there are no bugs in all these "pack/unpack" things + assert config == load_config(path) + + +def load_json(path: Union[Path, str], **kwargs) -> Any: + return json.loads(Path(path).read_text(), **kwargs) + + +def dump_json(x: Any, path: Union[Path, str], **kwargs) -> None: + kwargs.setdefault('indent', 4) + Path(path).write_text(json.dumps(x, **kwargs) + '\n') + + +def load_pickle(path: Union[Path, str], **kwargs) -> Any: + return pickle.loads(Path(path).read_bytes(), **kwargs) + + +def dump_pickle(x: Any, path: Union[Path, str], **kwargs) -> None: + Path(path).write_bytes(pickle.dumps(x, **kwargs)) + + +def load(path: Union[Path, str], **kwargs) -> Any: + return globals()[f'load_{Path(path).suffix[1:]}'](Path(path), **kwargs) + + +def dump(x: Any, path: Union[Path, str], **kwargs) -> Any: + return globals()[f'dump_{Path(path).suffix[1:]}'](x, Path(path), **kwargs) + + +def _get_output_item_path( + path: Union[str, Path], filename: str, must_exist: bool +) -> Path: + path = env.get_path(path) + if path.suffix == '.toml': + path = path.with_suffix('') + if path.is_dir(): + path = path / filename + else: + assert path.name == filename + assert path.parent.exists() + if must_exist: + assert path.exists() + return path + + +def load_report(path: Path) -> Report: + return load_json(_get_output_item_path(path, 'report.json', True)) + + +def dump_report(report: dict, path: Path) -> None: + dump_json(report, _get_output_item_path(path, 'report.json', False)) + + +def load_predictions(path: Path) -> Dict[str, np.ndarray]: + with np.load(_get_output_item_path(path, 'predictions.npz', True)) as predictions: + return {x: predictions[x] for x in predictions} + + +def dump_predictions(predictions: Dict[str, np.ndarray], path: Path) -> None: + np.savez(_get_output_item_path(path, 'predictions.npz', False), **predictions) + + +def dump_metrics(metrics: Dict[str, Any], path: Path) -> None: + dump_json(metrics, _get_output_item_path(path, 'metrics.json', False)) + + +def load_checkpoint(path: Path, *args, **kwargs) -> Dict[str, np.ndarray]: + return torch.load( + _get_output_item_path(path, 'checkpoint.pt', True), *args, **kwargs + ) + + +def get_device() -> torch.device: + if torch.cuda.is_available(): + assert os.environ.get('CUDA_VISIBLE_DEVICES') is not None + return torch.device('cuda:0') + else: + return torch.device('cpu') + + +def _print_sep(c, size=100): + print(c * size) + + +_LAST_SNAPSHOT_TIME = None + + +def backup_output(output_dir: Path) -> None: + backup_dir = os.environ.get('TMP_OUTPUT_PATH') + snapshot_dir = os.environ.get('SNAPSHOT_PATH') + if backup_dir is None: + assert snapshot_dir is None + return + assert snapshot_dir is not None + + try: + relative_output_dir = output_dir.relative_to(env.PROJ) + except ValueError: + return + + for dir_ in [backup_dir, snapshot_dir]: + new_output_dir = dir_ / relative_output_dir + prev_backup_output_dir = new_output_dir.with_name(new_output_dir.name + '_prev') + new_output_dir.parent.mkdir(exist_ok=True, parents=True) + if new_output_dir.exists(): + new_output_dir.rename(prev_backup_output_dir) + shutil.copytree(output_dir, new_output_dir) + # the case for evaluate.py which automatically creates configs + if output_dir.with_suffix('.toml').exists(): + shutil.copyfile( + output_dir.with_suffix('.toml'), new_output_dir.with_suffix('.toml') + ) + if prev_backup_output_dir.exists(): + shutil.rmtree(prev_backup_output_dir) + + global _LAST_SNAPSHOT_TIME + if _LAST_SNAPSHOT_TIME is None or time.time() - _LAST_SNAPSHOT_TIME > 10 * 60: + import nirvana_dl.snapshot # type: ignore[code] + + nirvana_dl.snapshot.dump_snapshot() + _LAST_SNAPSHOT_TIME = time.time() + print('The snapshot was saved!') + + +def _get_scores(metrics: Dict[str, Dict[str, Any]]) -> Optional[Dict[str, float]]: + return ( + {k: v['score'] for k, v in metrics.items()} + if 'score' in next(iter(metrics.values())) + else None + ) + + +def format_scores(metrics: Dict[str, Dict[str, Any]]) -> str: + return ' '.join( + f"[{x}] {metrics[x]['score']:.3f}" + for x in ['test', 'val', 'train'] + if x in metrics + ) + + +def finish(output_dir: Path, report: dict) -> None: + print() + _print_sep('=') + + metrics = report.get('metrics') + if metrics is not None: + scores = _get_scores(metrics) + if scores is not None: + dump_json(scores, output_dir / 'scores.json') + print(format_scores(metrics)) + _print_sep('-') + + dump_report(report, output_dir) + json_output_path = os.environ.get('JSON_OUTPUT_FILE') + if json_output_path: + try: + key = str(output_dir.relative_to(env.PROJ)) + except ValueError: + pass + else: + json_output_path = Path(json_output_path) + try: + json_data = json.loads(json_output_path.read_text()) + except (FileNotFoundError, json.decoder.JSONDecodeError): + json_data = {} + json_data[key] = load_json(output_dir / 'report.json') + json_output_path.write_text(json.dumps(json_data, indent=4)) + shutil.copyfile( + json_output_path, + os.path.join(os.environ['SNAPSHOT_PATH'], 'json_output.json'), + ) + + output_dir.joinpath('DONE').touch() + backup_output(output_dir) + print(f'Done! | {report.get("time")} | {output_dir}') + _print_sep('=') + print() + + +def from_dict(datacls: Type[T], data: dict) -> T: + assert is_dataclass(datacls) + data = deepcopy(data) + for field in fields(datacls): + if field.name not in data: + continue + if is_dataclass(field.type): + data[field.name] = from_dict(field.type, data[field.name]) + elif ( + get_origin(field.type) is Union + and len(get_args(field.type)) == 2 + and get_args(field.type)[1] is type(None) + and is_dataclass(get_args(field.type)[0]) + ): + if data[field.name] is not None: + data[field.name] = from_dict(get_args(field.type)[0], data[field.name]) + return datacls(**data) + + +def replace_factor_with_value( + config: RawConfig, + key: str, + reference_value: int, + bounds: Tuple[float, float], +) -> None: + factor_key = key + '_factor' + if factor_key not in config: + assert key in config + else: + assert key not in config + factor = config.pop(factor_key) + assert bounds[0] <= factor <= bounds[1] + config[key] = int(factor * reference_value) + + +def get_temporary_copy(path: Union[str, Path]) -> Path: + path = env.get_path(path) + assert not path.is_dir() and not path.is_symlink() + tmp_path = path.with_name( + path.stem + '___' + str(uuid.uuid4()).replace('-', '') + path.suffix + ) + shutil.copyfile(path, tmp_path) + atexit.register(lambda: tmp_path.unlink()) + return tmp_path + + +def get_python(): + python = Path('python3.9') + return str(python) if python.exists() else 'python' + +def get_catboost_config(real_data_path, is_cv=False): + ds_name = Path(real_data_path).name + C = load_json(f'tuned_models/catboost/{ds_name}_cv.json') + return C + +def get_categories(X_train_cat): + return ( + None + if X_train_cat is None + else [ + len(set(X_train_cat[:, i])) + for i in range(X_train_cat.shape[1]) + ] + ) \ No newline at end of file diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/synthetic/pipeline_n14/real.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/synthetic/pipeline_n14/real.csv new file mode 100644 index 0000000000000000000000000000000000000000..3eb127a41257f73db9bdc048d746e032df1602e7 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/synthetic/pipeline_n14/real.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c185607e5260848288c1fe3ee266131707a54e9f5e053f1234c019f315783fac +size 700663 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/synthetic/pipeline_n14/test.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/synthetic/pipeline_n14/test.csv new file mode 100644 index 0000000000000000000000000000000000000000..f0047af47ae70bd3483af5c9474d2baa67f629bb --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/synthetic/pipeline_n14/test.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6c58f97d23ce9ec15dde2caf4ba02105c2839eb4b1e1bb7f5183e0661fec4ecd +size 88640 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/synthetic/pipeline_n14/val.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/synthetic/pipeline_n14/val.csv new file mode 100644 index 0000000000000000000000000000000000000000..a5a6f693df47fd7a53d30e1da2c9caaa2edf2d23 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/synthetic/pipeline_n14/val.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:efcb8ee58a24ce4397213b3c4df4826fbcc6662da77b0919ff4e1935d12e2e89 +size 87578 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/conftest.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..f06feabdb2e28287232689c91868cc8e58730387 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/conftest.py @@ -0,0 +1,193 @@ +import pytest +import numpy as np +import torch +import torch.nn.functional as F +from unittest.mock import MagicMock + + +# --------------- dimension configs --------------- + +@pytest.fixture +def dims(): + """Standard mixed-data dimensions.""" + return {"d_numerical": 4, "categories": np.array([3, 5, 2]), "batch_size": 8, "d_token": 16} + + +@pytest.fixture +def dims_numerical_only(): + """Numerical-only scenario (no categorical features).""" + return {"d_numerical": 5, "categories": None, "batch_size": 8, "d_token": 16} + + +@pytest.fixture +def dims_single(): + """Minimal scenario: 1 numerical, 1 categorical with 2 classes.""" + return {"d_numerical": 1, "categories": np.array([2]), "batch_size": 4, "d_token": 8} + + +# --------------- dummy input factory --------------- + +@pytest.fixture +def make_dummy_inputs(): + """Factory: returns (x_num, x_cat_onehot, x_cat_int, timesteps) from any dims.""" + def _make(d_numerical, categories, batch_size): + torch.manual_seed(42) + x_num = torch.randn(batch_size, d_numerical) + if categories is not None and len(categories) > 0: + cat_parts = [] + for k in categories: + indices = torch.randint(0, k, (batch_size,)) + cat_parts.append(F.one_hot(indices, k).float()) + x_cat_onehot = torch.cat(cat_parts, dim=1) + x_cat_int = torch.stack( + [torch.randint(0, k, (batch_size,)) for k in categories], dim=1 + ) + else: + x_cat_onehot = None + x_cat_int = None + timesteps = torch.rand(batch_size) + return x_num, x_cat_onehot, x_cat_int, timesteps + return _make + + +# --------------- model factories --------------- + +@pytest.fixture +def make_tokenizer(): + from ef_vfm.modules.transformer import Tokenizer + def _make(d_numerical, categories, d_token, bias=True): + cats = list(categories) if categories is not None else None + return Tokenizer(d_numerical, cats, d_token, bias) + return _make + + +@pytest.fixture +def make_transformer(): + from ef_vfm.modules.transformer import Transformer + def _make(d_token, n_layers=2, n_heads=1, d_ffn_factor=4, activation='gelu'): + return Transformer(n_layers, d_token, n_heads, d_token, d_ffn_factor, activation=activation) + return _make + + +@pytest.fixture +def make_reconstructor(): + from ef_vfm.modules.transformer import Reconstructor + def _make(d_numerical, categories, d_token): + cats = list(categories) if categories is not None else [] + return Reconstructor(d_numerical, cats, d_token) + return _make + + +@pytest.fixture +def make_mlp(): + from ef_vfm.modules.main_modules import MLP + def _make(d_in, dim_t=128, use_mlp=True): + return MLP(d_in, dim_t=dim_t, use_mlp=use_mlp) + return _make + + +@pytest.fixture +def make_unimodmlp(): + from ef_vfm.modules.main_modules import UniModMLP + def _make(d_numerical, categories, d_token=16, n_layers=1, n_head=1, + factor=4, dim_t=64, activation='gelu'): + cats = list(categories) if categories is not None else [] + return UniModMLP( + d_numerical, cats, n_layers, d_token, + n_head=n_head, factor=factor, dim_t=dim_t, activation=activation, + ) + return _make + + +@pytest.fixture +def make_flow_model(): + from ef_vfm.modules.main_modules import UniModMLP + from ef_vfm.models.flow_model import ExpVFM + def _make(d_numerical, categories, d_token=16, n_layers=1, dim_t=64): + cats_list = list(categories) if categories is not None else [] + cats_np = np.array(cats_list) + model = UniModMLP( + d_numerical, cats_list, n_layers, d_token, + n_head=1, factor=4, dim_t=dim_t, activation='gelu', + ) + flow = ExpVFM( + num_classes=cats_np, + num_numerical_features=d_numerical, + vf_fn=model, + device=torch.device('cpu'), + ) + return flow + return _make + + +@pytest.fixture +def make_trainer(): + """Factory: creates a minimal Trainer with mocked external dependencies.""" + from ef_vfm.modules.main_modules import UniModMLP + from ef_vfm.models.flow_model import ExpVFM + from ef_vfm.trainer import Trainer + + def _make(d_numerical=4, categories=np.array([3, 5, 2]), + lr=0.001, max_grad_norm=1.0, warmup_epochs=0, + lr_scheduler='reduce_lr_on_plateau', steps=10, tmp_path=None): + + cats_list = list(categories) if categories is not None else [] + cats_np = np.array(cats_list) + + model = UniModMLP( + d_numerical, cats_list, 1, 16, + n_head=1, factor=4, dim_t=64, activation='gelu', + ) + flow = ExpVFM( + num_classes=cats_np, + num_numerical_features=d_numerical, + vf_fn=model, + device=torch.device('cpu'), + ) + + # Build a small synthetic dataset: [N, d_num + len(cats)] with int cat indices + n_samples = 32 + x_num = torch.randn(n_samples, d_numerical) + if len(cats_list) > 0: + x_cat = torch.stack( + [torch.randint(0, k, (n_samples,)) for k in cats_list], dim=1 + ).float() + data = torch.cat([x_num, x_cat], dim=1) + else: + data = x_num + + dataset = torch.utils.data.TensorDataset(data) + train_iter = torch.utils.data.DataLoader(dataset, batch_size=8, shuffle=False) + # DataLoader wraps in tuples; Trainer expects raw tensors, so use a wrapper + class _UnwrapLoader: + def __init__(self, loader): + self._loader = loader + def __iter__(self): + for (batch,) in self._loader: + yield batch + def __len__(self): + return len(self._loader) + + save_path = str(tmp_path) if tmp_path else "/tmp" + trainer = Trainer( + flow=flow, + train_iter=_UnwrapLoader(train_iter), + dataset=MagicMock(), + test_dataset=MagicMock(), + metrics=MagicMock(), + logger=MagicMock(), + lr=lr, + weight_decay=0, + steps=steps, + batch_size=8, + check_val_every=steps + 1, # never evaluate during test + sample_batch_size=8, + model_save_path=save_path, + result_save_path=save_path, + lr_scheduler=lr_scheduler, + max_grad_norm=max_grad_norm, + warmup_epochs=warmup_epochs, + device=torch.device('cpu'), + ) + return trainer + return _make diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_attention.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..6082db42ad2dff94440f4cc07659c57cf6326de4 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_attention.py @@ -0,0 +1,51 @@ +import pytest +import torch +from ef_vfm.modules.transformer import MultiheadAttention + + +def test_output_shape_single_head(): + attn = MultiheadAttention(d=16, n_heads=1, dropout=0.0) + x = torch.randn(4, 5, 16) + out = attn(x, x) + assert out.shape == (4, 5, 16) + + +def test_output_shape_multi_head(): + attn = MultiheadAttention(d=16, n_heads=4, dropout=0.0) + x = torch.randn(4, 5, 16) + out = attn(x, x) + assert out.shape == (4, 5, 16) + + +def test_no_W_out_single_head(): + attn = MultiheadAttention(d=16, n_heads=1, dropout=0.0) + assert attn.W_out is None + + +def test_W_out_exists_multi_head(): + attn = MultiheadAttention(d=16, n_heads=4, dropout=0.0) + assert attn.W_out is not None + + +def test_cross_attention_diff_seq_len(): + attn = MultiheadAttention(d=16, n_heads=1, dropout=0.0) + x_q = torch.randn(4, 3, 16) + x_kv = torch.randn(4, 7, 16) + out = attn(x_q, x_kv) + assert out.shape == (4, 3, 16) # output seq_len matches query + + +def test_invalid_d_nheads_raises(): + with pytest.raises(AssertionError): + MultiheadAttention(d=15, n_heads=4, dropout=0.0) + + +def test_gradient_flows(): + attn = MultiheadAttention(d=16, n_heads=2, dropout=0.0) + x = torch.randn(4, 5, 16, requires_grad=True) + out = attn(x, x) + out.sum().backward() + assert x.grad is not None and x.grad.abs().sum() > 0 + for name in ['W_q', 'W_k', 'W_v']: + param = getattr(attn, name) + assert param.weight.grad is not None and param.weight.grad.abs().sum() > 0 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_config.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_config.py new file mode 100644 index 0000000000000000000000000000000000000000..95c723f64388fe1259f0ba62f0ad8c6cf1051455 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_config.py @@ -0,0 +1,62 @@ +import os +from pathlib import Path + +from src.util import load_config +from ef_vfm.modules.main_modules import UniModMLP + + +CONFIG_PATH = Path(__file__).resolve().parent.parent / "ef_vfm" / "configs" / "ef_vfm_configs.toml" + + +def test_load_config_returns_dict(): + config = load_config(CONFIG_PATH) + assert isinstance(config, dict) + + +def test_config_has_expected_sections(): + config = load_config(CONFIG_PATH) + for key in ['data', 'unimodmlp_params', 'train', 'sample']: + assert key in config, f"Missing section '{key}'" + + +def test_unimodmlp_params_complete(): + config = load_config(CONFIG_PATH) + params = config['unimodmlp_params'] + required = ['num_layers', 'd_token', 'n_head', 'factor', 'bias', 'dim_t', 'use_mlp', 'activation'] + for key in required: + assert key in params, f"Missing param '{key}' in unimodmlp_params" + + +def test_activation_value_is_valid(): + config = load_config(CONFIG_PATH) + activation = config['unimodmlp_params']['activation'] + assert activation in ('relu', 'gelu', 'silu'), f"Invalid activation '{activation}'" + + +def test_train_main_has_new_params(): + """Verify the recently added config params are present.""" + config = load_config(CONFIG_PATH) + train = config['train']['main'] + assert 'max_grad_norm' in train + assert 'warmup_epochs' in train + assert isinstance(train['max_grad_norm'], (int, float)) + assert isinstance(train['warmup_epochs'], (int, float)) + + +def test_config_values_create_model(): + config = load_config(CONFIG_PATH) + params = config['unimodmlp_params'] + # Use dummy dimensions; the point is that config params are valid for the constructor + model = UniModMLP( + d_numerical=4, + categories=[3, 5, 2], + num_layers=params['num_layers'], + d_token=params['d_token'], + n_head=params['n_head'], + factor=params['factor'], + bias=params['bias'], + dim_t=params['dim_t'], + use_mlp=params['use_mlp'], + activation=params['activation'], + ) + assert model is not None diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_flow_model.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_flow_model.py new file mode 100644 index 0000000000000000000000000000000000000000..2bdc72bf2388cc70b56389463bdfd322b8badced --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_flow_model.py @@ -0,0 +1,219 @@ +import torch +import numpy as np +from unittest.mock import patch + +from ef_vfm.models.flow_model import ExpVFM, Velocity +from ef_vfm.modules.main_modules import UniModMLP + + +# ---- mixed_loss tests ---- + +def test_mixed_loss_returns_two_scalars(make_flow_model, make_dummy_inputs, dims): + d = dims + flow = make_flow_model(d["d_numerical"], d["categories"]) + _, _, x_cat_int, _ = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"]) + x_num = torch.randn(d["batch_size"], d["d_numerical"]) + x = torch.cat([x_num, x_cat_int.float()], dim=1) + d_loss, c_loss = flow.mixed_loss(x) + assert d_loss.dim() == 0 or d_loss.numel() == 1 + assert c_loss.dim() == 0 or c_loss.numel() == 1 + + +def test_mixed_loss_finite(make_flow_model, make_dummy_inputs, dims): + d = dims + flow = make_flow_model(d["d_numerical"], d["categories"]) + _, _, x_cat_int, _ = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"]) + x_num = torch.randn(d["batch_size"], d["d_numerical"]) + x = torch.cat([x_num, x_cat_int.float()], dim=1) + d_loss, c_loss = flow.mixed_loss(x) + assert torch.isfinite(d_loss).all() + assert torch.isfinite(c_loss).all() + + +def test_mixed_loss_gradients_flow(make_flow_model, make_dummy_inputs, dims): + d = dims + flow = make_flow_model(d["d_numerical"], d["categories"]) + _, _, x_cat_int, _ = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"]) + x_num = torch.randn(d["batch_size"], d["d_numerical"]) + x = torch.cat([x_num, x_cat_int.float()], dim=1) + d_loss, c_loss = flow.mixed_loss(x) + total = d_loss + c_loss + total.backward() + grads = [p.grad for p in flow.parameters() if p.grad is not None] + assert len(grads) > 0 + + +def test_mixed_loss_numerical_only(make_flow_model, make_dummy_inputs, dims_numerical_only): + d = dims_numerical_only + flow = make_flow_model(d["d_numerical"], d["categories"]) + x = torch.randn(d["batch_size"], d["d_numerical"]) + d_loss, c_loss = flow.mixed_loss(x) + assert d_loss.item() == 0.0 # no discrete features + assert c_loss.item() > 0.0 + + +# ---- sample tests (with mocked odeint) ---- + +def _make_flow(d_numerical, categories): + cats_list = list(categories) if categories is not None else [] + cats_np = np.array(cats_list) + model = UniModMLP(d_numerical, cats_list, 1, 16, n_head=1, factor=4, dim_t=64, activation='gelu') + return ExpVFM(cats_np, d_numerical, model, device=torch.device('cpu')) + + +def test_sample_output_shape(dims): + d = dims + flow = _make_flow(d["d_numerical"], d["categories"]) + d_in = d["d_numerical"] + sum(d["categories"]) + n = 5 + fake_trajectory = torch.randn(2, n, d_in) + with patch("ef_vfm.models.flow_model.odeint", return_value=fake_trajectory): + result = flow.sample(n) + d_out = d["d_numerical"] + len(d["categories"]) + assert result.shape == (n, d_out) + + +def test_sample_categorical_in_range(dims): + d = dims + flow = _make_flow(d["d_numerical"], d["categories"]) + d_in = d["d_numerical"] + sum(d["categories"]) + n = 16 + fake_trajectory = torch.randn(2, n, d_in) + with patch("ef_vfm.models.flow_model.odeint", return_value=fake_trajectory): + result = flow.sample(n) + for i, k in enumerate(d["categories"]): + col = d["d_numerical"] + i + assert (result[:, col] >= 0).all() + assert (result[:, col] < k).all() + + +def test_sample_returns_cpu(dims): + d = dims + flow = _make_flow(d["d_numerical"], d["categories"]) + d_in = d["d_numerical"] + sum(d["categories"]) + fake_trajectory = torch.randn(2, 4, d_in) + with patch("ef_vfm.models.flow_model.odeint", return_value=fake_trajectory): + result = flow.sample(4) + assert result.device == torch.device('cpu') + + +def test_sample_single_sample(dims): + d = dims + flow = _make_flow(d["d_numerical"], d["categories"]) + d_in = d["d_numerical"] + sum(d["categories"]) + fake_trajectory = torch.randn(2, 1, d_in) + with patch("ef_vfm.models.flow_model.odeint", return_value=fake_trajectory): + result = flow.sample(1) + d_out = d["d_numerical"] + len(d["categories"]) + assert result.shape == (1, d_out) + + +# ---- to_one_hot tests ---- + +def test_to_one_hot_shape(dims): + d = dims + flow = _make_flow(d["d_numerical"], d["categories"]) + cats = d["categories"] + x_cat = torch.stack([torch.randint(0, k, (8,)) for k in cats], dim=1) + oh = flow.to_one_hot(x_cat) + assert oh.shape == (8, sum(cats)) + + +def test_to_one_hot_roundtrip(dims): + d = dims + flow = _make_flow(d["d_numerical"], d["categories"]) + cats = d["categories"] + x_cat = torch.stack([torch.randint(0, k, (8,)) for k in cats], dim=1) + oh = flow.to_one_hot(x_cat) + # Recover indices via argmax per category slice + idx = 0 + for i, k in enumerate(cats): + recovered = oh[:, idx:idx + k].argmax(dim=1) + assert torch.equal(recovered, x_cat[:, i]) + idx += k + + +def test_to_one_hot_binary_values(dims): + d = dims + flow = _make_flow(d["d_numerical"], d["categories"]) + cats = d["categories"] + x_cat = torch.stack([torch.randint(0, k, (8,)) for k in cats], dim=1) + oh = flow.to_one_hot(x_cat) + assert set(oh.unique().tolist()).issubset({0, 1}) + + +# ---- Regression tests ---- + +def test_regression_d_in_no_extra_len(): + """d_in must be num_numerical + sum(num_classes), NOT + len(num_classes).""" + d_numerical = 4 + categories = np.array([3, 5, 2]) + flow = _make_flow(d_numerical, categories) + expected_d_in = d_numerical + sum(categories) # 14, not 17 + assert flow.num_numerical_features + sum(flow.num_classes) == expected_d_in + + +def test_regression_sampling_indices_correct(): + """Categorical argmax must go to columns [d_num, d_num+1, ...], not [0, 1, ...].""" + d_numerical = 4 + categories = np.array([3, 5, 2]) + n = 10 + d_in = d_numerical + sum(categories) + d_out = d_numerical + len(categories) + + # Simulate the post-processing from sample() + out = torch.randn(n, d_in) + sample = torch.zeros(n, d_out) + sample[:, :d_numerical] = out[:, :d_numerical] + + idx = d_numerical # correct starting index + for i, val in enumerate(categories): + col = d_numerical + i # correct column + sample[:, col] = torch.argmax(out[:, idx:idx + val], dim=1) + idx += val + + # Numerical columns must be untouched + assert torch.allclose(sample[:, :d_numerical], out[:, :d_numerical]) + # Categorical columns at correct positions + for i, val in enumerate(categories): + col = d_numerical + i + assert (sample[:, col] >= 0).all() + assert (sample[:, col] < val).all() + + +def test_regression_d_out_correct(): + """d_out must be d_num + len(categories).""" + d_numerical = 4 + categories = np.array([3, 5, 2]) + flow = _make_flow(d_numerical, categories) + expected_d_out = d_numerical + len(categories) # 7 + assert expected_d_out == 7 + + +# ---- Velocity tests ---- + +def test_velocity_output_shape(dims): + d = dims + cats_list = list(d["categories"]) + model = UniModMLP(d["d_numerical"], cats_list, 1, d["d_token"], + n_head=1, factor=4, dim_t=64, activation='gelu') + vel = Velocity(model) + d_in = d["d_numerical"] + sum(d["categories"]) + x = torch.randn(d["batch_size"], d_in) + t = torch.tensor(0.5) + out = vel(t, x) + assert out.shape == (d["batch_size"], d_in) + + +def test_velocity_scalar_t_broadcast(dims): + d = dims + cats_list = list(d["categories"]) + model = UniModMLP(d["d_numerical"], cats_list, 1, d["d_token"], + n_head=1, factor=4, dim_t=64, activation='gelu') + vel = Velocity(model) + d_in = d["d_numerical"] + sum(d["categories"]) + x = torch.randn(d["batch_size"], d_in) + # Scalar t should work (gets broadcast internally) + t = torch.tensor(0.3) + out = vel(t, x) + assert out.shape == x.shape diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_mlp.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_mlp.py new file mode 100644 index 0000000000000000000000000000000000000000..0cf9ad4d6832d792cb65a1bb01bdc784385f9fcd --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_mlp.py @@ -0,0 +1,85 @@ +import torch +import torch.nn as nn +from ef_vfm.modules.main_modules import MLP, PositionalEmbedding + + +# ---- PositionalEmbedding tests ---- + +def test_positional_embedding_shape(): + pe = PositionalEmbedding(num_channels=64) + x = torch.rand(8) + out = pe(x) + assert out.shape == (8, 64) + + +def test_positional_embedding_bounded(): + pe = PositionalEmbedding(num_channels=64) + x = torch.rand(8) + out = pe(x) + assert out.min() >= -1.0 + assert out.max() <= 1.0 + + +def test_positional_embedding_deterministic(): + pe = PositionalEmbedding(num_channels=64) + x = torch.tensor([0.1, 0.5, 0.9]) + out1 = pe(x) + out2 = pe(x) + assert torch.equal(out1, out2) + + +def test_positional_embedding_different_timesteps(): + pe = PositionalEmbedding(num_channels=64) + t1 = torch.tensor([0.1]) + t2 = torch.tensor([0.9]) + assert not torch.allclose(pe(t1), pe(t2)) + + +# ---- MLP tests ---- + +def test_mlp_output_shape(make_mlp): + mlp = make_mlp(d_in=32, dim_t=64) + x = torch.randn(8, 32) + t = torch.rand(8) + out = mlp(x, t) + assert out.shape == (8, 32) + + +def test_mlp_use_mlp_true(make_mlp): + mlp = make_mlp(d_in=32, dim_t=64, use_mlp=True) + assert isinstance(mlp.mlp, nn.Sequential) + + +def test_mlp_use_mlp_false(make_mlp): + mlp = make_mlp(d_in=32, dim_t=64, use_mlp=False) + assert isinstance(mlp.mlp, nn.Linear) + + +def test_mlp_time_conditioning(make_mlp): + mlp = make_mlp(d_in=32, dim_t=64) + mlp.eval() + x = torch.randn(4, 32) + t1 = torch.zeros(4) + t2 = torch.ones(4) + out1 = mlp(x, t1) + out2 = mlp(x, t2) + assert not torch.allclose(out1, out2) + + +def test_mlp_gradient_flows(make_mlp): + mlp = make_mlp(d_in=32, dim_t=64) + x = torch.randn(4, 32) + t = torch.rand(4) + out = mlp(x, t) + out.sum().backward() + assert mlp.proj.weight.grad is not None and mlp.proj.weight.grad.abs().sum() > 0 + assert mlp.map_noise.num_channels == 64 # sanity check on PE config + + +def test_mlp_different_dim_t(make_mlp): + for dim_t in [32, 128, 256]: + mlp = make_mlp(d_in=16, dim_t=dim_t) + x = torch.randn(4, 16) + t = torch.rand(4) + out = mlp(x, t) + assert out.shape == (4, 16) diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_reconstructor.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_reconstructor.py new file mode 100644 index 0000000000000000000000000000000000000000..cdc39880d19f644fb8ac6b457af6a8cb3d83cbfa --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_reconstructor.py @@ -0,0 +1,51 @@ +import torch +import numpy as np +from ef_vfm.modules.transformer import Reconstructor + + +def test_output_shapes_mixed(make_reconstructor, dims): + d = dims + r = make_reconstructor(d["d_numerical"], d["categories"], d["d_token"]) + seq_len = d["d_numerical"] + len(d["categories"]) + h = torch.randn(d["batch_size"], seq_len, d["d_token"]) + x_num, x_cat = r(h) + assert x_num.shape == (d["batch_size"], d["d_numerical"]) + assert len(x_cat) == len(d["categories"]) + for i, k in enumerate(d["categories"]): + assert x_cat[i].shape == (d["batch_size"], k) + + +def test_categorical_count(make_reconstructor, dims): + d = dims + r = make_reconstructor(d["d_numerical"], d["categories"], d["d_token"]) + seq_len = d["d_numerical"] + len(d["categories"]) + h = torch.randn(d["batch_size"], seq_len, d["d_token"]) + _, x_cat = r(h) + assert len(x_cat) == len(d["categories"]) + + +def test_empty_categories(make_reconstructor): + r = make_reconstructor(4, np.array([]), 16) + h = torch.randn(8, 4, 16) + x_num, x_cat = r(h) + assert x_num.shape == (8, 4) + assert len(x_cat) == 0 + + +def test_weight_shape(make_reconstructor, dims): + d = dims + r = make_reconstructor(d["d_numerical"], d["categories"], d["d_token"]) + assert r.weight.shape == (d["d_numerical"], d["d_token"]) + + +def test_gradient_flows(make_reconstructor, dims): + d = dims + r = make_reconstructor(d["d_numerical"], d["categories"], d["d_token"]) + seq_len = d["d_numerical"] + len(d["categories"]) + h = torch.randn(d["batch_size"], seq_len, d["d_token"]) + x_num, x_cat = r(h) + loss = x_num.sum() + sum(c.sum() for c in x_cat) + loss.backward() + assert r.weight.grad is not None and r.weight.grad.abs().sum() > 0 + for recon in r.cat_recons: + assert recon.weight.grad is not None diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_tokenizer.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..ea8c55737d473605c2bb1c87f0394fad64baeb18 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_tokenizer.py @@ -0,0 +1,85 @@ +import torch +import numpy as np + + +def test_forward_shape_mixed(make_tokenizer, make_dummy_inputs, dims): + tok = make_tokenizer(dims["d_numerical"], dims["categories"], dims["d_token"]) + x_num, x_cat_oh, _, _ = make_dummy_inputs(dims["d_numerical"], dims["categories"], dims["batch_size"]) + out = tok(x_num, x_cat_oh) + expected_seq = 1 + dims["d_numerical"] + len(dims["categories"]) + assert out.shape == (dims["batch_size"], expected_seq, dims["d_token"]) + + +def test_forward_shape_numerical_only(make_tokenizer, make_dummy_inputs, dims_numerical_only): + d = dims_numerical_only + tok = make_tokenizer(d["d_numerical"], d["categories"], d["d_token"]) + x_num, _, _, _ = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"]) + out = tok(x_num, None) + expected_seq = 1 + d["d_numerical"] + assert out.shape == (d["batch_size"], expected_seq, d["d_token"]) + + +def test_forward_shape_single_feature(make_tokenizer, make_dummy_inputs, dims_single): + d = dims_single + tok = make_tokenizer(d["d_numerical"], d["categories"], d["d_token"]) + x_num, x_cat_oh, _, _ = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"]) + out = tok(x_num, x_cat_oh) + expected_seq = 1 + d["d_numerical"] + len(d["categories"]) + assert out.shape == (d["batch_size"], expected_seq, d["d_token"]) + + +def test_n_tokens_property(make_tokenizer, dims): + tok = make_tokenizer(dims["d_numerical"], dims["categories"], dims["d_token"]) + expected = dims["d_numerical"] + 1 + len(dims["categories"]) + assert tok.n_tokens == expected + + +def test_n_tokens_numerical_only(make_tokenizer, dims_numerical_only): + d = dims_numerical_only + tok = make_tokenizer(d["d_numerical"], d["categories"], d["d_token"]) + assert tok.n_tokens == d["d_numerical"] + 1 + + +def test_cls_token_position(make_tokenizer, make_dummy_inputs, dims): + tok = make_tokenizer(dims["d_numerical"], dims["categories"], dims["d_token"], bias=False) + x_num, x_cat_oh, _, _ = make_dummy_inputs(dims["d_numerical"], dims["categories"], dims["batch_size"]) + out = tok(x_num, x_cat_oh) + # CLS token: ones * weight[0], so all batch rows should have the same CLS token + cls_tokens = out[:, 0, :] + assert torch.allclose(cls_tokens[0], cls_tokens[1]) + assert torch.allclose(cls_tokens[0], tok.weight[0]) + + +def test_bias_vs_no_bias(make_tokenizer, make_dummy_inputs, dims): + d = dims + tok_bias = make_tokenizer(d["d_numerical"], d["categories"], d["d_token"], bias=True) + tok_no_bias = make_tokenizer(d["d_numerical"], d["categories"], d["d_token"], bias=False) + assert tok_bias.bias is not None + assert tok_no_bias.bias is None + + +def test_category_offsets_values(make_tokenizer): + cats = np.array([3, 5, 2]) + tok = make_tokenizer(4, cats, 16) + assert torch.equal(tok.category_offsets, torch.tensor([0, 3, 8])) + assert torch.equal(tok.category_ends, torch.tensor([3, 8, 10])) + + +def test_cat_weight_shape(make_tokenizer, dims): + tok = make_tokenizer(dims["d_numerical"], dims["categories"], dims["d_token"]) + assert tok.cat_weight.shape == (sum(dims["categories"]), dims["d_token"]) + + +def test_weight_shape(make_tokenizer, dims): + tok = make_tokenizer(dims["d_numerical"], dims["categories"], dims["d_token"]) + assert tok.weight.shape == (dims["d_numerical"] + 1, dims["d_token"]) + + +def test_gradient_flows(make_tokenizer, make_dummy_inputs, dims): + tok = make_tokenizer(dims["d_numerical"], dims["categories"], dims["d_token"]) + x_num, x_cat_oh, _, _ = make_dummy_inputs(dims["d_numerical"], dims["categories"], dims["batch_size"]) + out = tok(x_num, x_cat_oh) + out.sum().backward() + assert tok.weight.grad is not None and tok.weight.grad.abs().sum() > 0 + assert tok.cat_weight.grad is not None and tok.cat_weight.grad.abs().sum() > 0 + assert tok.bias.grad is not None and tok.bias.grad.abs().sum() > 0 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_trainer.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..592c538d2aa1f8f34098a0d7c6c4fc0b1f0c5ddf --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_trainer.py @@ -0,0 +1,98 @@ +import torch +import numpy as np + + +# ---- Gradient clipping tests ---- + +def test_grad_clipping_applied(make_trainer, tmp_path): + trainer = make_trainer(max_grad_norm=0.5, tmp_path=tmp_path) + batch = next(iter(trainer.train_iter)) + trainer._run_step(batch, closs_weight=1.0, dloss_weight=1.0) + # After clipping, total gradient norm should be <= max_grad_norm (with tolerance) + total_norm = torch.nn.utils.clip_grad_norm_(trainer.flow.parameters(), float('inf')) + # Gradients were already clipped in _run_step, then optimizer.step() zeroed them. + # So we re-run to check: do a fresh forward-backward without step + trainer.optimizer.zero_grad() + dloss, closs = trainer.flow.mixed_loss(batch.to(trainer.device)) + (dloss + closs).backward() + torch.nn.utils.clip_grad_norm_(trainer.flow.parameters(), 0.5) + total_norm = 0.0 + for p in trainer.flow.parameters(): + if p.grad is not None: + total_norm += p.grad.data.norm(2).item() ** 2 + total_norm = total_norm ** 0.5 + assert total_norm <= 0.5 + 1e-6 + + +def test_grad_clipping_disabled(make_trainer, tmp_path): + trainer = make_trainer(max_grad_norm=0, tmp_path=tmp_path) + assert trainer.max_grad_norm == 0 + + +def test_run_step_returns_losses(make_trainer, tmp_path): + trainer = make_trainer(tmp_path=tmp_path) + batch = next(iter(trainer.train_iter)) + dloss, closs = trainer._run_step(batch, closs_weight=1.0, dloss_weight=1.0) + assert isinstance(dloss, torch.Tensor) + assert isinstance(closs, torch.Tensor) + assert torch.isfinite(dloss) + assert torch.isfinite(closs) + + +# ---- LR warmup tests ---- + +def test_warmup_lr_linear_ramp(make_trainer, tmp_path): + init_lr = 0.01 + warmup = 5 + trainer = make_trainer(lr=init_lr, warmup_epochs=warmup, tmp_path=tmp_path) + # Simulate warmup epochs + for epoch in range(warmup): + expected_lr = init_lr * (epoch + 1) / warmup + if trainer.warmup_epochs > 0 and (epoch + 1) <= trainer.warmup_epochs: + warmup_lr = trainer.init_lr * (epoch + 1) / trainer.warmup_epochs + for pg in trainer.optimizer.param_groups: + pg["lr"] = warmup_lr + actual_lr = trainer.optimizer.param_groups[0]["lr"] + assert abs(actual_lr - expected_lr) < 1e-8, f"Epoch {epoch}: expected {expected_lr}, got {actual_lr}" + + +def test_warmup_overrides_scheduler(make_trainer, tmp_path): + trainer = make_trainer(warmup_epochs=10, lr_scheduler='reduce_lr_on_plateau', tmp_path=tmp_path) + initial_lr = trainer.optimizer.param_groups[0]["lr"] + # During warmup, scheduler.step should NOT be called (we just set LR directly) + # Simulate epoch 1 warmup + warmup_lr = trainer.init_lr * 1 / trainer.warmup_epochs + for pg in trainer.optimizer.param_groups: + pg["lr"] = warmup_lr + assert trainer.optimizer.param_groups[0]["lr"] == warmup_lr + assert warmup_lr < initial_lr # warmup starts lower + + +def test_no_warmup_when_zero(make_trainer, tmp_path): + trainer = make_trainer(warmup_epochs=0, tmp_path=tmp_path) + assert trainer.warmup_epochs == 0 + # LR should be the init_lr from the start + assert trainer.optimizer.param_groups[0]["lr"] == trainer.init_lr + + +# ---- LR scheduler tests ---- + +def test_anneal_lr(make_trainer, tmp_path): + trainer = make_trainer(lr=0.01, steps=100, lr_scheduler='anneal', tmp_path=tmp_path) + trainer._anneal_lr(50) + expected = 0.01 * (1 - 50 / 100) + assert abs(trainer.optimizer.param_groups[0]["lr"] - expected) < 1e-8 + + +# ---- EMA tests ---- + +def test_ema_model_created(make_trainer, tmp_path): + trainer = make_trainer(tmp_path=tmp_path) + # EMA model should exist and have same structure as flow._vf_fn + assert trainer.ema_model is not None + ema_params = list(trainer.ema_model.parameters()) + model_params = list(trainer.flow._vf_fn.parameters()) + assert len(ema_params) == len(model_params) + # EMA params should be detached (requires_grad=False) + for p in ema_params: + assert not p.requires_grad diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_transformer.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..ff56e884615e818841fbb912f8ef4e9961729197 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_transformer.py @@ -0,0 +1,73 @@ +import pytest +import torch +from ef_vfm.modules.transformer import Transformer + + +def test_output_shape_preserved(make_transformer): + t = make_transformer(d_token=16, n_layers=2) + x = torch.randn(4, 5, 16) + out = t(x) + assert out.shape == x.shape + + +def test_activation_gelu(make_transformer): + t = make_transformer(d_token=16, activation='gelu') + x = torch.randn(4, 5, 16) + out = t(x) + assert out.shape == x.shape + + +def test_activation_silu(make_transformer): + t = make_transformer(d_token=16, activation='silu') + x = torch.randn(4, 5, 16) + out = t(x) + assert out.shape == x.shape + + +def test_activation_relu(make_transformer): + t = make_transformer(d_token=16, activation='relu') + x = torch.randn(4, 5, 16) + out = t(x) + assert out.shape == x.shape + + +def test_invalid_activation_raises(): + with pytest.raises(ValueError, match="Unknown activation"): + Transformer(2, 16, 1, 16, 4, activation='bad') + + +def test_prenorm_first_layer_no_norm0(): + t = Transformer(2, 16, 1, 16, 4, prenormalization=True) + assert 'norm0' not in t.layers[0] + # Second layer should have norm0 + assert 'norm0' in t.layers[1] + + +def test_no_prenorm_all_layers_have_norm0(): + t = Transformer(2, 16, 1, 16, 4, prenormalization=False) + for layer in t.layers: + assert 'norm0' in layer + + +def test_single_layer(): + t = Transformer(1, 16, 1, 16, 4) + x = torch.randn(4, 5, 16) + out = t(x) + assert out.shape == x.shape + + +def test_multi_layer(): + t = Transformer(4, 16, 1, 16, 4) + x = torch.randn(4, 5, 16) + out = t(x) + assert out.shape == x.shape + + +def test_gradient_flows(make_transformer): + t = make_transformer(d_token=16, n_layers=2) + x = torch.randn(4, 5, 16, requires_grad=True) + out = t(x) + out.sum().backward() + assert x.grad is not None and x.grad.abs().sum() > 0 + # Check gradients through at least the first layer's linear0 + assert t.layers[0]['linear0'].weight.grad is not None diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_unimodmlp.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_unimodmlp.py new file mode 100644 index 0000000000000000000000000000000000000000..d935e7c48dba78fd7e4821287628aa861aa6d1b4 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_unimodmlp.py @@ -0,0 +1,72 @@ +import torch +import numpy as np + + +def test_forward_shapes_mixed(make_unimodmlp, make_dummy_inputs, dims): + d = dims + model = make_unimodmlp(d["d_numerical"], d["categories"], d_token=d["d_token"]) + x_num, x_cat_oh, _, t = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"]) + x_num_pred, x_cat_pred = model(x_num, x_cat_oh, t) + assert x_num_pred.shape == (d["batch_size"], d["d_numerical"]) + assert x_cat_pred.shape == (d["batch_size"], sum(d["categories"])) + + +def test_forward_shapes_numerical_only(make_unimodmlp, make_dummy_inputs, dims_numerical_only): + d = dims_numerical_only + model = make_unimodmlp(d["d_numerical"], d["categories"], d_token=d["d_token"]) + x_num, _, _, t = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"]) + x_cat = torch.zeros(d["batch_size"], 0) + x_num_pred, x_cat_pred = model(x_num, x_cat, t) + assert x_num_pred.shape == (d["batch_size"], d["d_numerical"]) + # When no categories, cat_pred should be zeros with shape matching x_cat + assert x_cat_pred.shape[0] == d["batch_size"] + assert torch.all(x_cat_pred == 0) + + +def test_forward_shapes_single_feature(make_unimodmlp, make_dummy_inputs, dims_single): + d = dims_single + model = make_unimodmlp(d["d_numerical"], d["categories"], d_token=d["d_token"]) + x_num, x_cat_oh, _, t = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"]) + x_num_pred, x_cat_pred = model(x_num, x_cat_oh, t) + assert x_num_pred.shape == (d["batch_size"], d["d_numerical"]) + assert x_cat_pred.shape == (d["batch_size"], sum(d["categories"])) + + +def test_d_in_computation(make_unimodmlp, dims): + d = dims + model = make_unimodmlp(d["d_numerical"], d["categories"], d_token=d["d_token"]) + expected = d["d_token"] * (d["d_numerical"] + len(d["categories"])) + assert model.mlp.proj.in_features == expected + + +def test_output_dtypes(make_unimodmlp, make_dummy_inputs, dims): + d = dims + model = make_unimodmlp(d["d_numerical"], d["categories"], d_token=d["d_token"]) + x_num, x_cat_oh, _, t = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"]) + x_num_pred, x_cat_pred = model(x_num, x_cat_oh, t) + assert x_num_pred.dtype == torch.float32 + assert x_cat_pred.dtype == torch.float32 + + +def test_gradient_flows_end_to_end(make_unimodmlp, make_dummy_inputs, dims): + d = dims + model = make_unimodmlp(d["d_numerical"], d["categories"], d_token=d["d_token"]) + x_num, x_cat_oh, _, t = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"]) + x_num_pred, x_cat_pred = model(x_num, x_cat_oh, t) + loss = x_num_pred.sum() + x_cat_pred.sum() + loss.backward() + params_with_grad = sum(1 for p in model.parameters() if p.grad is not None and p.grad.abs().sum() > 0) + total_params = sum(1 for _ in model.parameters()) + # Transformer.head is defined but unused in forward(), so not all params get gradients + assert params_with_grad > total_params * 0.8, f"Only {params_with_grad}/{total_params} params got gradients" + + +def test_different_activations(make_unimodmlp, make_dummy_inputs, dims): + d = dims + x_num, x_cat_oh, _, t = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"]) + for act in ['relu', 'gelu', 'silu']: + model = make_unimodmlp(d["d_numerical"], d["categories"], d_token=d["d_token"], activation=act) + x_num_pred, x_cat_pred = model(x_num, x_cat_oh, t) + assert x_num_pred.shape == (d["batch_size"], d["d_numerical"]) + assert torch.isfinite(x_num_pred).all() + assert torch.isfinite(x_cat_pred).all() diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_utils.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fbce0db0ac74052a4038dee89fd753b9d97717aa --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/tests/test_utils.py @@ -0,0 +1,49 @@ +import torch +import numpy as np + +from utils_train import update_ema, concat_y_to_X + + +# ---- update_ema tests ---- + +def test_update_ema_basic(): + target = [torch.tensor([1.0, 2.0])] + source = [torch.tensor([3.0, 4.0])] + target[0].requires_grad_(False) + rate = 0.9 + update_ema(target, source, rate=rate) + expected = 0.9 * torch.tensor([1.0, 2.0]) + 0.1 * torch.tensor([3.0, 4.0]) + assert torch.allclose(target[0], expected) + + +def test_update_ema_rate_zero(): + target = [torch.tensor([1.0, 2.0])] + source = [torch.tensor([3.0, 4.0])] + target[0].requires_grad_(False) + update_ema(target, source, rate=0.0) + assert torch.allclose(target[0], torch.tensor([3.0, 4.0])) + + +def test_update_ema_rate_one(): + target = [torch.tensor([1.0, 2.0])] + source = [torch.tensor([3.0, 4.0])] + target[0].requires_grad_(False) + update_ema(target, source, rate=1.0) + assert torch.allclose(target[0], torch.tensor([1.0, 2.0])) + + +# ---- concat_y_to_X tests ---- + +def test_concat_y_to_X_with_X(): + X = np.array([[1, 2], [3, 4]]) + y = np.array([10, 20]) + result = concat_y_to_X(X, y) + expected = np.array([[10, 1, 2], [20, 3, 4]]) + np.testing.assert_array_equal(result, expected) + + +def test_concat_y_to_X_without_X(): + y = np.array([10, 20, 30]) + result = concat_y_to_X(None, y) + expected = np.array([[10], [20], [30]]) + np.testing.assert_array_equal(result, expected) diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/utils_train.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/utils_train.py new file mode 100644 index 0000000000000000000000000000000000000000..f00c40d190a763f011526ef4aa11e5e960ce2b7b --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime/utils_train.py @@ -0,0 +1,183 @@ +import numpy as np +import os + +import src +from torch.utils.data import Dataset + +import torch + + +class TabularDataset(Dataset): + def __init__(self, X_num, X_cat): + self.X_num = X_num + self.X_cat = X_cat + + def __getitem__(self, index): + this_num = self.X_num[index] + this_cat = self.X_cat[index] + + sample = (this_num, this_cat) + + return sample + + def __len__(self): + return self.X_num.shape[0] + +class EFVFMDataset(Dataset): + def __init__(self, dataname, data_dir, info, isTrain=True, dequant_dist='none', int_dequant_factor=0.0): + self.dataname = dataname + self.data_dir = data_dir + self.info = info + self.isTrain = isTrain + + X_num, X_cat, categories, d_numerical, num_inverse, int_inverse, cat_inverse = preprocess(data_dir, dequant_dist, int_dequant_factor, task_type = info['task_type'], inverse=True) + categories = np.array(categories) + + X_train_num, _ = X_num + X_train_cat, _ = X_cat + + X_train_num, X_test_num = X_num + X_train_cat, X_test_cat = X_cat + + X_train_num, X_test_num = torch.tensor(X_train_num).float(), torch.tensor(X_test_num).float() + X_train_cat, X_test_cat = torch.tensor(X_train_cat), torch.tensor(X_test_cat) + + self.X = torch.cat((X_train_num, X_train_cat), dim=1) if isTrain else torch.cat((X_test_num, X_test_cat), dim=1) + self.num_inverse = num_inverse + self.int_inverse = int_inverse + self.cat_inverse = cat_inverse + self.d_numerical = d_numerical + self.categories = categories + + def __getitem__(self, index): + return self.X[index] + + def __len__(self): + return self.X.shape[0] + +def preprocess(dataset_path, dequant_dist='none', int_dequant_factor=0.0, task_type = 'binclass', inverse = False, cat_encoding = None, concat = True): + + T_dict = {} + + T_dict['normalization'] = "quantile" + T_dict['num_nan_policy'] = 'mean' + T_dict['cat_nan_policy'] = None + T_dict['cat_min_frequency'] = None + T_dict['cat_encoding'] = cat_encoding + T_dict['y_policy'] = "default" + T_dict['dequant_dist'] = dequant_dist + T_dict['int_dequant_factor'] = int_dequant_factor + + T = src.Transformations(**T_dict) + + dataset = make_dataset( + data_path = dataset_path, + T = T, + task_type = task_type, + change_val = False, + concat = concat, + ) + + if cat_encoding is None: + X_num = dataset.X_num + X_cat = dataset.X_cat + + X_train_num, X_test_num = X_num['train'], X_num['test'] + X_train_cat, X_test_cat = X_cat['train'], X_cat['test'] + + categories = src.get_categories(X_train_cat) + d_numerical = X_train_num.shape[1] + + X_num = (X_train_num, X_test_num) + X_cat = (X_train_cat, X_test_cat) + + + if inverse: + num_inverse = dataset.num_transform.inverse_transform if dataset.num_transform is not None else lambda x: x + int_inverse = dataset.int_transform.inverse_transform if dataset.int_transform is not None else lambda x: x + cat_inverse = dataset.cat_transform.inverse_transform if dataset.cat_transform is not None else lambda x: x + + return X_num, X_cat, categories, d_numerical, num_inverse, int_inverse, cat_inverse + else: + return X_num, X_cat, categories, d_numerical + else: + return dataset + + +def update_ema(target_params, source_params, rate=0.999): + """ + Update target parameters to be closer to those of source parameters using + an exponential moving average. + :param target_params: the target parameter sequence. + :param source_params: the source parameter sequence. + :param rate: the EMA rate (closer to 1 means slower). + """ + for target, source in zip(target_params, source_params): + target.detach().mul_(rate).add_(source.detach(), alpha=1 - rate) + + + +def concat_y_to_X(X, y): + if X is None: + return y.reshape(-1, 1) + return np.concatenate([y.reshape(-1, 1), X], axis=1) + + +def make_dataset( + data_path: str, + T: src.Transformations, + task_type, + change_val: bool, + concat = True, +): + + # classification + if task_type == 'binclass' or task_type == 'multiclass': + X_cat = {} if os.path.exists(os.path.join(data_path, 'X_cat_train.npy')) else None + X_num = {} if os.path.exists(os.path.join(data_path, 'X_num_train.npy')) else None + y = {} if os.path.exists(os.path.join(data_path, 'y_train.npy')) else None + + for split in ['train', 'test']: + X_num_t, X_cat_t, y_t = src.read_pure_data(data_path, split) + if X_num is not None: + X_num[split] = X_num_t + if X_cat is not None: + if concat: + X_cat_t = concat_y_to_X(X_cat_t, y_t) + X_cat[split] = X_cat_t + if y is not None: + y[split] = y_t + else: + # regression + X_cat = {} if os.path.exists(os.path.join(data_path, 'X_cat_train.npy')) else None + X_num = {} if os.path.exists(os.path.join(data_path, 'X_num_train.npy')) else None + y = {} if os.path.exists(os.path.join(data_path, 'y_train.npy')) else None + + for split in ['train', 'test']: + X_num_t, X_cat_t, y_t = src.read_pure_data(data_path, split) + if X_num is not None: + if concat: + X_num_t = concat_y_to_X(X_num_t, y_t) + X_num[split] = X_num_t + if X_cat is not None: + X_cat[split] = X_cat_t + if y is not None: + y[split] = y_t + + info = src.load_json(os.path.join(data_path, 'info.json')) + int_col_idx_wrt_num = info['int_col_idx_wrt_num'] + + D = src.Dataset( + X_num, + X_cat, + y, + int_col_idx_wrt_num, + y_info={}, + task_type=src.TaskType(info['task_type']), + n_classes=info.get('n_classes') + ) + + if change_val: + D = src.change_val(D) + + return src.transform_dataset(D, T, None) \ No newline at end of file diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_tabbyflow_train.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_tabbyflow_train.py new file mode 100644 index 0000000000000000000000000000000000000000..e0ca76b3c8106e2a07171dcacb5b2362041392f4 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/_tabbyflow_train.py @@ -0,0 +1,33 @@ + +import os, shutil, subprocess, sys +root = r"/workspace/ef-vfm" +rt = r"/work/output-Benchmark-trainonly-v1/n14/tabbyflow/tabbyflow-n14-20260510_205357/_efvfm_runtime" +name = r"pipeline_n14" +src = r"/work/output-Benchmark-trainonly-v1/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14" + +shutil.rmtree(rt, ignore_errors=True) + +def _ignore(_, names): + skip = {"__pycache__", "data", "synthetic", "result", "results", "ckpt"} + return [n for n in names if n in skip or n.endswith(".pyc")] + +shutil.copytree(root, rt, ignore=_ignore) +dst_data = os.path.join(rt, "data", name) +dst_syn = os.path.join(rt, "synthetic", name) +shutil.rmtree(dst_data, ignore_errors=True) +os.makedirs(os.path.dirname(dst_data), exist_ok=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(rt) +os.environ["PYTHONPATH"] = rt + 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, os.path.join(rt, "main.py"), + "--dataname", name, "--mode", "train", "--gpu", "0", + "--no_wandb", "--exp_name", r"adapter_efvfm", +]) diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/input_snapshot.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/input_snapshot.json new file mode 100644 index 0000000000000000000000000000000000000000..08865fd252ae77127c65516f5840c6fe4e1385f5 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/input_snapshot.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cb19f1f9abf2b8f00b8196f9ab1c2fd918d4549f286ecafc1a77a6b02f3fddfc +size 1361 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/public_gate/normalized_schema_snapshot.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/public_gate/normalized_schema_snapshot.json new file mode 100644 index 0000000000000000000000000000000000000000..e95bb9f1507ba3dcc217e156d288a4c218d5ce0e --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/public_gate/normalized_schema_snapshot.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1039de91400208739668ec5dbba162e50476ffb8f7bc2c41c34a9e152d1a1fd7 +size 25212 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/public_gate/public_gate_report.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/public_gate/public_gate_report.json new file mode 100644 index 0000000000000000000000000000000000000000..3042bd53a693121e438e327a754bb37ba7d23620 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/public_gate/public_gate_report.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d0323cb1844f3ed9d898f3dd78211792dbc408cc2661f88cffa593a96fe919f2 +size 920 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/public_gate/staged_input_manifest.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/public_gate/staged_input_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..7228da5d2e8ccaadf00a8c55116fca4fe8b299d6 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/public_gate/staged_input_manifest.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e703263efe5252ca342fd36a435af89cd740582c2077b6ca56aded84f7ba0dc3 +size 26048 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/run_config.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/run_config.json new file mode 100644 index 0000000000000000000000000000000000000000..2d28d692f26d7204171a29f1e36e2711679dfe86 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/run_config.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1b30746e463e4f1d88b0320a69258b9f6019887dab3f6b885714d757b39197b3 +size 1826 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/runtime_result.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/runtime_result.json new file mode 100644 index 0000000000000000000000000000000000000000..264af620f6808bbe046c3024f01acb4d9d7efb54 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/runtime_result.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ee38302acda918a6d99afb34126ceaa08d27618e88df8a5701833dfcd4e67c50 +size 1108 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/staged/public/staged_features.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/staged/public/staged_features.json new file mode 100644 index 0000000000000000000000000000000000000000..764ec9270aa6a452ad32f774e4eb007bf24ca4ec --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/staged/public/staged_features.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2ceb242f15c8115703b617ca54db02ff27dff41d99dd4f9af89bb5fcb513e5bb +size 5032 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/staged/public/test.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/staged/public/test.csv new file mode 100644 index 0000000000000000000000000000000000000000..f0047af47ae70bd3483af5c9474d2baa67f629bb --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/staged/public/test.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6c58f97d23ce9ec15dde2caf4ba02105c2839eb4b1e1bb7f5183e0661fec4ecd +size 88640 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/staged/public/train.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/staged/public/train.csv new file mode 100644 index 0000000000000000000000000000000000000000..3eb127a41257f73db9bdc048d746e032df1602e7 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/staged/public/train.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c185607e5260848288c1fe3ee266131707a54e9f5e053f1234c019f315783fac +size 700663 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/staged/public/val.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/staged/public/val.csv new file mode 100644 index 0000000000000000000000000000000000000000..a5a6f693df47fd7a53d30e1da2c9caaa2edf2d23 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/staged/public/val.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:efcb8ee58a24ce4397213b3c4df4826fbcc6662da77b0919ff4e1935d12e2e89 +size 87578 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/staged/tabbyflow/adapter_report.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/staged/tabbyflow/adapter_report.json new file mode 100644 index 0000000000000000000000000000000000000000..bfd3b91ae612ef464b5b56a6a513a3173ca14535 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/staged/tabbyflow/adapter_report.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:47a2a9d8123d8abefd07f18537eb103e7af8d4250006ded408dc1c8425413239 +size 329 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/staged/tabbyflow/adapter_transforms_applied.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/staged/tabbyflow/adapter_transforms_applied.json new file mode 100644 index 0000000000000000000000000000000000000000..6f3aaa01a627a955d2022165805d2786c0da78ba --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/staged/tabbyflow/adapter_transforms_applied.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945 +size 2 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/staged/tabbyflow/model_input_manifest.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/staged/tabbyflow/model_input_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..8b4fdb91e3e6755740b1425275f0a56b76bd0005 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/staged/tabbyflow/model_input_manifest.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d9698033eef7a3c1e860fdea47b664b5a6c91fa5aaa8a6ac72cc2446ceaad749 +size 26253 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/X_num_test.npy b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/X_num_test.npy new file mode 100644 index 0000000000000000000000000000000000000000..58dcffe35f9c3d2be06bfacd6463afc29f469621 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/X_num_test.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e252b63332f6d0348986fa99b50bd0f50a4842a6535d987c77e35ec94dca2304 +size 41132 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/X_num_train.npy b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/X_num_train.npy new file mode 100644 index 0000000000000000000000000000000000000000..829ebc8714db6fb18f342ce0609de9b685c8a4c8 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/X_num_train.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b976aada0f39493df222408da25c8093fae5ed29c88a963352f6c5924720bfcb +size 326528 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/X_num_val.npy b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/X_num_val.npy new file mode 100644 index 0000000000000000000000000000000000000000..f9b501abfa8648ee74efcaddf531803aee3c5f5c --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/X_num_val.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:43682ea64d3dccdcaf67f0c922556fe78e3cd216b7456a914a5e169e2b52f5a8 +size 40724 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/info.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/info.json new file mode 100644 index 0000000000000000000000000000000000000000..349bd7f0dfb9558da57b1bb6f8027d081b2f8ffe --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/info.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:575631118d21657a7a362ba5a330d6fff150a3d78c4ba038ffb878dd37c75cd5 +size 9435 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/real.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/real.csv new file mode 100644 index 0000000000000000000000000000000000000000..3eb127a41257f73db9bdc048d746e032df1602e7 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/real.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c185607e5260848288c1fe3ee266131707a54e9f5e053f1234c019f315783fac +size 700663 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/staged_features.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/staged_features.json new file mode 100644 index 0000000000000000000000000000000000000000..764ec9270aa6a452ad32f774e4eb007bf24ca4ec --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/staged_features.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2ceb242f15c8115703b617ca54db02ff27dff41d99dd4f9af89bb5fcb513e5bb +size 5032 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/test.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/test.csv new file mode 100644 index 0000000000000000000000000000000000000000..f0047af47ae70bd3483af5c9474d2baa67f629bb --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/test.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6c58f97d23ce9ec15dde2caf4ba02105c2839eb4b1e1bb7f5183e0661fec4ecd +size 88640 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/train.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/train.csv new file mode 100644 index 0000000000000000000000000000000000000000..3eb127a41257f73db9bdc048d746e032df1602e7 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/train.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c185607e5260848288c1fe3ee266131707a54e9f5e053f1234c019f315783fac +size 700663 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/val.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/val.csv new file mode 100644 index 0000000000000000000000000000000000000000..a5a6f693df47fd7a53d30e1da2c9caaa2edf2d23 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/val.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:efcb8ee58a24ce4397213b3c4df4826fbcc6662da77b0919ff4e1935d12e2e89 +size 87578 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/y_test.npy b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/y_test.npy new file mode 100644 index 0000000000000000000000000000000000000000..5651fa99fbfba7f7fa1d0ad15aebc466b7a7cc53 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/y_test.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2e6b805a842cf97508b8a3789499fc698c44e659e45b100fb80d666ad2f96a74 +size 1736 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/y_train.npy b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/y_train.npy new file mode 100644 index 0000000000000000000000000000000000000000..0849049b021bfe542c1221ec2b7369cecd5e2165 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/y_train.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ee738812eaaf4a819a6c9f861ee2e99873bd2842f80c68eb380cc38033938b74 +size 12928 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/y_val.npy b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/y_val.npy new file mode 100644 index 0000000000000000000000000000000000000000..87b51e4ebfe724b015106152ef10e69ffd69b53b --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/tabular_bundle/pipeline_n14/y_val.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0df86b75b6fc8fea3f161682beaa867a5bb7dbe36f9331e7d36176459da70720 +size 1720 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/train_20260510_205358.log b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/train_20260510_205358.log new file mode 100644 index 0000000000000000000000000000000000000000..19013ca3f52ae1bddf9412b94dcf1ea7d02c78c0 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260510_205357/train_20260510_205358.log @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9b73b71d59332d1c04e45b27505f1cdeb6298aacb5c307fb4ed6d44c58b92185 +size 2904 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/.gitignore b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..5fe5c08858a9f78b16a14e3d3757641d03307c72 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/.gitignore @@ -0,0 +1,174 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# 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 logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_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 stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_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/adult +data/beijing +data/default +data/magic +data/news +data/shoppers + +wandb/ + +*.DS_Store diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/LICENCE b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/LICENCE new file mode 100644 index 0000000000000000000000000000000000000000..421b2ef006d92669068729de1866b3dde6b3fd45 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/LICENCE @@ -0,0 +1,7 @@ +Copyright 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. diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/README.md b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ffe4e59cce3dd04f5d51853fb14ac71daa561843 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/README.md @@ -0,0 +1,128 @@ +# Exponential Family Variational Flow Matching for Tabular Data Generation + +

+ + MIT License + + + Openreview + + + Paper URL + +

+ +
+ Model Logo +

Figure 1: Exponential Family Variational Flow Matching (EF-VFM) is a generative modeling framework designed for mixed continuous +and discrete variables. By leveraging the exponential family and a mean-field assumption, EF-VFM efficiently matches the sufficient +statistics of the distributions via learned probability paths, ensuring state-of-the-art fidelity and diversity in synthetic data.

+
+ +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 --mode train --exp_name ``` + +where `````` is the name of the dataset you want to train on, and `````` is the name of your experiment. + +Current Options of `````` 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 ```. + +## Sampling and Evaluating TabbyFlow (Density, MLE, C2ST) + +To sample synthetic tables from trained EF-VFM models and evaluate them, run + +```python main.py --dataname --mode test --report --no_wandb --exp_name ``` + +where `````` and `````` 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///. + +## 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 ``` + +Similarly, the results will be printed out in the terminal and added to ./eval/report_runs/// + +## 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 `````` + +```python main.py --dataname _dcr --mode train``` + +Then, test the models on DCR with the same `_dcr` suffix + +```python main.py --dataname _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). diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ckpt/pipeline_n14/adapter_efvfm/config.pkl b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ckpt/pipeline_n14/adapter_efvfm/config.pkl new file mode 100644 index 0000000000000000000000000000000000000000..1083edc56615c0f246ed1e9dd8b2a719dc57a3b5 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ckpt/pipeline_n14/adapter_efvfm/config.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2e2ef004c98f11706babcffcc024e8b92a94bc49d1c183ae7be6b32a375d2dd5 +size 918 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ckpt/pipeline_n14/adapter_efvfm/ema_model_100.pt b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ckpt/pipeline_n14/adapter_efvfm/ema_model_100.pt new file mode 100644 index 0000000000000000000000000000000000000000..5b7f22ff278034c01fedd9269537bb318d0996f1 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ckpt/pipeline_n14/adapter_efvfm/ema_model_100.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ac8cff6a156f7828989e08c362ff576be661a3d372973df34dd5f1d39cef913c +size 43744829 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ckpt/pipeline_n14/adapter_efvfm/model_100.pt b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ckpt/pipeline_n14/adapter_efvfm/model_100.pt new file mode 100644 index 0000000000000000000000000000000000000000..77e074f0a3b31bed45ff90d35385e9480d699442 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ckpt/pipeline_n14/adapter_efvfm/model_100.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:646b89ef91739ee6f8d83716b89cb720066c51d28acdd33a14f67f61e83d4fa7 +size 43744477 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/configs/ef_vfm_configs.toml b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/configs/ef_vfm_configs.toml new file mode 100644 index 0000000000000000000000000000000000000000..da1df42825e99fb19a331757d981a43fd5c25472 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/configs/ef_vfm_configs.toml @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:677698232b3ea325b54527cccdc11c49fadb971129a77065e71d64aa7567ddb6 +size 674 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/X_num_test.npy b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/X_num_test.npy new file mode 100644 index 0000000000000000000000000000000000000000..58dcffe35f9c3d2be06bfacd6463afc29f469621 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/X_num_test.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e252b63332f6d0348986fa99b50bd0f50a4842a6535d987c77e35ec94dca2304 +size 41132 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/X_num_train.npy b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/X_num_train.npy new file mode 100644 index 0000000000000000000000000000000000000000..829ebc8714db6fb18f342ce0609de9b685c8a4c8 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/X_num_train.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b976aada0f39493df222408da25c8093fae5ed29c88a963352f6c5924720bfcb +size 326528 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/X_num_val.npy b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/X_num_val.npy new file mode 100644 index 0000000000000000000000000000000000000000..f9b501abfa8648ee74efcaddf531803aee3c5f5c --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/X_num_val.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:43682ea64d3dccdcaf67f0c922556fe78e3cd216b7456a914a5e169e2b52f5a8 +size 40724 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/cache__0__quantile__mean__None__None__None__default__none__0__0904553a19c875643139fd2363e49697.pickle b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/cache__0__quantile__mean__None__None__None__default__none__0__0904553a19c875643139fd2363e49697.pickle new file mode 100644 index 0000000000000000000000000000000000000000..6f98db94fe4c76599a81cb859b288049df860b2b --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/cache__0__quantile__mean__None__None__None__default__none__0__0904553a19c875643139fd2363e49697.pickle @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:76de81e6b0bed8647d5646418ce64387dc23edebf82a82eed1495fa11accdf30 +size 404992 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/info.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/info.json new file mode 100644 index 0000000000000000000000000000000000000000..349bd7f0dfb9558da57b1bb6f8027d081b2f8ffe --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/info.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:575631118d21657a7a362ba5a330d6fff150a3d78c4ba038ffb878dd37c75cd5 +size 9435 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/real.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/real.csv new file mode 100644 index 0000000000000000000000000000000000000000..3eb127a41257f73db9bdc048d746e032df1602e7 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/real.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c185607e5260848288c1fe3ee266131707a54e9f5e053f1234c019f315783fac +size 700663 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/staged_features.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/staged_features.json new file mode 100644 index 0000000000000000000000000000000000000000..764ec9270aa6a452ad32f774e4eb007bf24ca4ec --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/staged_features.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2ceb242f15c8115703b617ca54db02ff27dff41d99dd4f9af89bb5fcb513e5bb +size 5032 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/test.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/test.csv new file mode 100644 index 0000000000000000000000000000000000000000..f0047af47ae70bd3483af5c9474d2baa67f629bb --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/test.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6c58f97d23ce9ec15dde2caf4ba02105c2839eb4b1e1bb7f5183e0661fec4ecd +size 88640 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/train.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/train.csv new file mode 100644 index 0000000000000000000000000000000000000000..3eb127a41257f73db9bdc048d746e032df1602e7 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/train.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c185607e5260848288c1fe3ee266131707a54e9f5e053f1234c019f315783fac +size 700663 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/val.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/val.csv new file mode 100644 index 0000000000000000000000000000000000000000..a5a6f693df47fd7a53d30e1da2c9caaa2edf2d23 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/val.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:efcb8ee58a24ce4397213b3c4df4826fbcc6662da77b0919ff4e1935d12e2e89 +size 87578 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/y_test.npy b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/y_test.npy new file mode 100644 index 0000000000000000000000000000000000000000..5651fa99fbfba7f7fa1d0ad15aebc466b7a7cc53 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/y_test.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2e6b805a842cf97508b8a3789499fc698c44e659e45b100fb80d666ad2f96a74 +size 1736 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/y_train.npy b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/y_train.npy new file mode 100644 index 0000000000000000000000000000000000000000..0849049b021bfe542c1221ec2b7369cecd5e2165 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/y_train.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ee738812eaaf4a819a6c9f861ee2e99873bd2842f80c68eb380cc38033938b74 +size 12928 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/y_val.npy b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/y_val.npy new file mode 100644 index 0000000000000000000000000000000000000000..87b51e4ebfe724b015106152ef10e69ffd69b53b --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/data/pipeline_n14/y_val.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0df86b75b6fc8fea3f161682beaa867a5bb7dbe36f9331e7d36176459da70720 +size 1720 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/download_dataset.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/download_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..427dbbdc686039d81b03aa05d721d06c5b0dcd47 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/download_dataset.py @@ -0,0 +1,49 @@ +import os +from urllib import request +import 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) + \ No newline at end of file diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ef_vfm/configs/ef_vfm_configs.toml b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ef_vfm/configs/ef_vfm_configs.toml new file mode 100644 index 0000000000000000000000000000000000000000..da1df42825e99fb19a331757d981a43fd5c25472 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ef_vfm/configs/ef_vfm_configs.toml @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:677698232b3ea325b54527cccdc11c49fadb971129a77065e71d64aa7567ddb6 +size 674 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ef_vfm/main.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ef_vfm/main.py new file mode 100644 index 0000000000000000000000000000000000000000..d3e0966c01ffb317e0d8cb94b6f293992dbfbdc1 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ef_vfm/main.py @@ -0,0 +1,246 @@ +import glob +import json +import os +import pickle +import random + +import numpy as np +from ef_vfm.metrics import TabMetrics +from ef_vfm.modules.main_modules import UniModMLP +from ef_vfm.models.flow_model import ExpVFM +from ef_vfm.trainer import Trainer +import src +import torch + +from torch.utils.data import DataLoader +import argparse +import 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' diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ef_vfm/metrics.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ef_vfm/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..4f104427533ac37610c92216b135fdeba3d181be --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ef_vfm/metrics.py @@ -0,0 +1,306 @@ +from copy import deepcopy +import numpy as np +import torch +import pandas as pd +# Metrics +from eval.mle.mle import get_evaluator +from eval.visualize_density import plot_density +from sdmetrics.reports.single_table import QualityReport, DiagnosticReport +from sdmetrics.single_table import LogisticDetection +from 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, metadata \ No newline at end of file diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ef_vfm/models/flow_model.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ef_vfm/models/flow_model.py new file mode 100644 index 0000000000000000000000000000000000000000..ca312ec2c1d6d517d270f315454db914e4610c41 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ef_vfm/models/flow_model.py @@ -0,0 +1,207 @@ +import torch.nn.functional as F +import torch +import numpy as np +import os +from 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) + solver = os.environ.get("EFVFM_ODE_SOLVER", "dopri5").strip() or "dopri5" + rtol = float(os.environ.get("EFVFM_ODE_RTOL", "1e-5")) + atol = float(os.environ.get("EFVFM_ODE_ATOL", "1e-5")) + fallback_enabled = os.environ.get("EFVFM_ODE_FALLBACK", "1").strip().lower() not in ("0", "false", "no") + fallback_steps = max(3, int(os.environ.get("EFVFM_RK4_STEPS", "32"))) + try: + trajectory = odeint(vf, x0, t, method=solver, rtol=rtol, atol=atol) + except Exception as e: + if (not fallback_enabled) or ("underflow in dt" not in str(e) and solver == "rk4"): + raise + t_fb = torch.linspace(0.0, 0.999, fallback_steps, device=dev) + trajectory = odeint(vf, x0, t_fb, method="rk4") + 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_t diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ef_vfm/modules/main_modules.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ef_vfm/modules/main_modules.py new file mode 100644 index 0000000000000000000000000000000000000000..46dceb368af3302e55d5e448a2ffede4db122977 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ef_vfm/modules/main_modules.py @@ -0,0 +1,102 @@ +from typing import Callable, Union + +from ef_vfm.modules.transformer import Reconstructor, Tokenizer, Transformer +import torch +import torch.nn as nn +import 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_pred diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ef_vfm/modules/transformer.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ef_vfm/modules/transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..98334864ad8befdc6e23fe5f64d5e50bf5907cee --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ef_vfm/modules/transformer.py @@ -0,0 +1,269 @@ +import torch +import torch.nn as nn +import torch.nn.init as nn_init +import torch.nn.functional as F +from 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_cat diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ef_vfm/trainer.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ef_vfm/trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..eef113e930d00d7b80310b03b072384548fd31b0 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ef_vfm/trainer.py @@ -0,0 +1,557 @@ +import os +import glob +import time +import torch +from torch.optim.lr_scheduler import ReduceLROnPlateau +import numpy as np +import pandas as pd +import 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_df \ No newline at end of file diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/eval/eval_quality.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/eval/eval_quality.py new file mode 100644 index 0000000000000000000000000000000000000000..c7f4f9409e5a207087ab59104d2f970a17341ba5 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/eval/eval_quality.py @@ -0,0 +1,149 @@ +import glob +import numpy as np +import pandas as pd +import os +import sys +import json + +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +from sklearn.preprocessing import OneHotEncoder +from synthcity.metrics import eval_statistical +from synthcity.plugins.core.dataloader import GenericDataLoader + +pd.options.mode.chained_assignment = None + +import argparse + +parser = argparse.ArgumentParser() +parser.add_argument('--dataname', type=str) +parser.add_argument('--exp_name', type=str, default=None) + + +args = parser.parse_args() + +def evaluate_quality(real_path, syn_path, info_path): + with open(info_path, 'r') as f: + info = json.load(f) + + syn_data = pd.read_csv(syn_path) + real_data = pd.read_csv(real_path) + + + ''' Special treatment for default dataset and CoDi model ''' + + real_data.columns = range(len(real_data.columns)) + syn_data.columns = range(len(syn_data.columns)) + + num_col_idx = info['num_col_idx'] + cat_col_idx = info['cat_col_idx'] + target_col_idx = info['target_col_idx'] + if info['task_type'] == 'regression': + num_col_idx += target_col_idx + else: + cat_col_idx += target_col_idx + + num_real_data = real_data[num_col_idx] + cat_real_data = real_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 = syn_data[num_col_idx] + cat_syn_data = syn_data[cat_col_idx] + + num_syn_data_np = num_syn_data.to_numpy() + + # cat_syn_data_np = np.array + cat_syn_data_np = cat_syn_data.to_numpy().astype('str') + + encoder = OneHotEncoder() + 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() + + le_real_data = pd.DataFrame(np.concatenate((num_real_data_np, cat_real_data_oh), axis = 1)).astype(float) + le_real_num = pd.DataFrame(num_real_data_np).astype(float) + le_real_cat = pd.DataFrame(cat_real_data_oh).astype(float) + + + le_syn_data = pd.DataFrame(np.concatenate((num_syn_data_np, cat_syn_data_oh), axis = 1)).astype(float) + le_syn_num = pd.DataFrame(num_syn_data_np).astype(float) + le_syn_cat = pd.DataFrame(cat_syn_data_oh).astype(float) + + # Check for nan + if le_syn_data.isnull().values.any(): + nan_coordinate = np.isnan(le_syn_data.to_numpy()).nonzero() + nan_row = np.unique(nan_coordinate[0]) + print(f"Synthetic data contains NaN at row {nan_row}: ") + print(le_syn_data.iloc[nan_row]) + return None, None + + + np.set_printoptions(precision=4) + + result = [] + + print('=========== All Features ===========') + print('Data shape: ', le_syn_data.shape) + + X_syn_loader = GenericDataLoader(le_syn_data) + X_real_loader = GenericDataLoader(le_real_data) + + quality_evaluator = eval_statistical.AlphaPrecision() + qual_res = quality_evaluator.evaluate(X_real_loader, X_syn_loader) + qual_res = { + k: v for (k, v) in qual_res.items() if "naive" in k + } # use the naive implementation of AlphaPrecision + qual_score = np.mean(list(qual_res.values())) + + print('alpha precision: {:.6f}, beta recall: {:.6f}'.format(qual_res['delta_precision_alpha_naive'], qual_res['delta_coverage_beta_naive'] )) + + Alpha_Precision_all = qual_res['delta_precision_alpha_naive'] + Beta_Recall_all = qual_res['delta_coverage_beta_naive'] + + return Alpha_Precision_all, Beta_Recall_all + +if __name__ == '__main__': + exp_name = args.exp_name + assert exp_name is not None, "Experiment name must be provided" + dataname = args.dataname + data_dir = f'data/{dataname}' + info_path = f'{data_dir}/info.json' + real_path = f'synthetic/{dataname}/real.csv' + + sample_dir = f"eval/report_runs/{exp_name}/{dataname}/all_samples" + sample_paths = glob.glob(os.path.join(sample_dir, "*.csv")) + print(f"{len(sample_paths )} samples loaded from {sample_dir}") + + alphas, betas = [], [] + for syn_path in sample_paths: + alpha_precision, beta_recall = evaluate_quality(real_path, syn_path, info_path) + if (alpha_precision is None) or (beta_recall is None): + continue + alphas.append(alpha_precision) + betas.append(beta_recall) + + alphas = np.array(alphas) + betas = np.array(betas) + alpha_percent = alphas * 100 + beta_percent = betas * 100 + + quality = pd.DataFrame({ + 'alpha': alpha_percent, + 'beta': beta_percent + }) + avg = quality.mean(axis=0).round(2) + std = quality.std(axis=0).round(2) + quality_avg_std = pd.concat([avg, std], axis=1, ignore_index=True) + quality_avg_std.columns = ["avg", "std"] + quality_avg_std.index = ["alpha", "beta"] + + save_dir = os.path.dirname(sample_dir) + quality.to_csv(os.path.join(save_dir, "quality.csv"), index=True) + avg_std = pd.read_csv(os.path.join(save_dir, "avg_std.csv"), index_col=0) + avg_std = pd.concat([avg_std, quality_avg_std]) + print(avg_std) + avg_std.to_csv(os.path.join(save_dir, "avg_std.csv"), index=True) diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/eval/mle/mle.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/eval/mle/mle.py new file mode 100644 index 0000000000000000000000000000000000000000..0cfb8766d1bf207b3abe48a1142f7ef436a6eae8 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/eval/mle/mle.py @@ -0,0 +1,781 @@ +import numpy as np +import pandas as pd +from xgboost import XGBClassifier, XGBRegressor +from sklearn.ensemble import AdaBoostClassifier, RandomForestClassifier, RandomForestRegressor +from sklearn.linear_model import LogisticRegression, LinearRegression +from sklearn.neural_network import MLPClassifier, MLPRegressor +from sklearn.preprocessing import OneHotEncoder, LabelEncoder +from sklearn.tree import DecisionTreeClassifier +from sklearn.metrics import classification_report, accuracy_score, f1_score, precision_score, recall_score, roc_auc_score +from sklearn.metrics import explained_variance_score, mean_squared_error, mean_absolute_error, r2_score +from sklearn.model_selection import ParameterGrid +from sklearn.utils._testing import ignore_warnings +from sklearn.exceptions import ConvergenceWarning +import logging +from prdc import compute_prdc +from tqdm import tqdm + +CATEGORICAL = "categorical" +CONTINUOUS = "continuous" + +_MODELS = { + 'binclass': [ # 184 + # { + # 'class': DecisionTreeClassifier, # 48 + # 'kwargs': { + # 'max_depth': [4, 8, 16, 32], + # 'min_samples_split': [2, 4, 8], + # 'min_samples_leaf': [1, 2, 4, 8] + # } + # }, + # { + # 'class': AdaBoostClassifier, # 4 + # 'kwargs': { + # 'n_estimators': [10, 50, 100, 200] + # } + # }, + # { + # 'class': LogisticRegression, # 36 + # 'kwargs': { + # 'solver': ['lbfgs'], + # 'n_jobs': [-1], + # 'max_iter': [10, 50, 100, 200], + # 'C': [0.01, 0.1, 1.0], + # 'tol': [1e-01, 1e-02, 1e-04] + # } + # }, + # { + # 'class': MLPClassifier, # 12 + # 'kwargs': { + # 'hidden_layer_sizes': [(100, ), (200, ), (100, 100)], + # 'max_iter': [50, 100], + # 'alpha': [0.0001, 0.001] + # } + # }, + # { + # 'class': RandomForestClassifier, # 48 + # 'kwargs': { + # 'max_depth': [8, 16, None], + # 'min_samples_split': [2, 4, 8], + # 'min_samples_leaf': [1, 2, 4, 8], + # 'n_jobs': [-1] + + # } + # }, + { + 'class': XGBClassifier, # 36 + 'kwargs': { + 'n_estimators': [10, 50, 100], + 'min_child_weight': [1, 10], + 'max_depth': [5, 10, 20], + 'gamma': [0.0, 1.0], + 'objective': ['binary:logistic'], + 'nthread': [-1], + 'tree_method': ['gpu_hist'] + }, + } + + ], + 'multiclass': [ # 132 + + # { + # 'class': MLPClassifier, # 12 + # 'kwargs': { + # 'hidden_layer_sizes': [(100, ), (200, ), (100, 100)], + # 'max_iter': [50, 100], + # 'alpha': [0.0001, 0.001] + # } + # }, + # { + # 'class': DecisionTreeClassifier, # 48 + # 'kwargs': { + # 'max_depth': [4, 8, 16, 32], + # 'min_samples_split': [2, 4, 8], + # 'min_samples_leaf': [1, 2, 4, 8] + # } + # }, + # { + # 'class': RandomForestClassifier, # 36 + # 'kwargs': { + # 'max_depth': [8, 16, None], + # 'min_samples_split': [2, 4, 8], + # 'min_samples_leaf': [1, 2, 4, 8], + # 'n_jobs': [-1] + + # } + # }, + { + 'class': XGBClassifier, # 36 + 'kwargs': { + 'n_estimators': [10, 50, 100], + 'min_child_weight': [1, 10], + 'max_depth': [5, 10, 20], + 'gamma': [0.0, 1.0], + 'objective': ['binary:logistic'], + 'nthread': [-1], + 'tree_method': ['gpu_hist'] + } + } + + ], + 'regression': [ # 84 + # { + # 'class': LinearRegression, + # }, + # { + # 'class': MLPRegressor, # 12 + # 'kwargs': { + # 'hidden_layer_sizes': [(100, ), (200, ), (100, 100)], + # 'max_iter': [50, 100], + # 'alpha': [0.0001, 0.001] + # } + #}, + { + 'class': XGBRegressor, # 36 + 'kwargs': { + 'n_estimators': [10, 50, 100], + 'min_child_weight': [1, 10], + 'max_depth': [5, 10, 20], + 'gamma': [0.0, 1.0], + 'objective': ['reg:linear'], + 'nthread': [-1], + 'tree_method': ['gpu_hist'] + } + }, + # { + # 'class': RandomForestRegressor, # 36 + # 'kwargs': { + # 'max_depth': [8, 16, None], + # 'min_samples_split': [2, 4, 8], + # 'min_samples_leaf': [1, 2, 4, 8], + # 'n_jobs': [-1] + # } + # } + ] +} + +def feat_transform(data, info, label_encoder = None, encoders = None, cmax = None, cmin = None): + num_col_idx = info['num_col_idx'] + cat_col_idx = info['cat_col_idx'] + target_col_idx = info['target_col_idx'] + + num_cols = len(num_col_idx + cat_col_idx + target_col_idx) + features = [] + + if not encoders: + encoders = dict() + for idx in range(num_cols): + col = data[:, idx] + + if idx in target_col_idx: + + if info['task_type'] != 'regression': + + if not label_encoder: + label_encoder = LabelEncoder() + label_encoder.fit(col) + + encoded_labels = label_encoder.transform(col) + labels = encoded_labels + else: + col = col.astype(np.float32) + labels = col.astype(np.float32) + + continue + + if idx in num_col_idx: + col = col.astype(np.float32) + + if not cmin: + cmin = col.min() + + if not cmax: + cmax = col.max() + + if cmin >= 0 and cmax >= 1e3: + feature = np.log(np.maximum(col, 1e-2)) + + else: + feature = (col - cmin) / (cmax - cmin) * 5 + + elif idx in cat_col_idx: + encoder = encoders.get(idx) + col = col.reshape(-1, 1) + if encoder: + feature = encoder.transform(col) + else: + # encoder = OneHotEncoder(sparse=False, handle_unknown='ignore') + encoder = OneHotEncoder(sparse_output=False, handle_unknown='ignore') # New in version 1.2: sparse was renamed to sparse_output + encoders[idx] = encoder + feature = encoder.fit_transform(col) + + + features.append(feature) + features = np.column_stack(features) + return features, labels, label_encoder, encoders, cmax, cmin + + +def prepare_ml_problem(train, test, info, val=None): + # test_X, test_y, label_encoder, encoders = feat_transform(test, info) + # train_X, train_y, _, _ = feat_transform(train, info, label_encoder, encoders) + + train_X, train_y, label_encoder, encoders, cmax, cmin = feat_transform(train, info) + test_X, test_y, _, _ , _, _ = feat_transform(test, info, label_encoder, encoders, cmax, cmin) + + if val is not None: + val_X, val_y, _, _, _, _ = feat_transform(val, info, label_encoder, encoders, cmax, cmin) + else: + total_train_num = train_X.shape[0] + val_num = int(total_train_num / 9) + + total_train_idx = np.arange(total_train_num) + np.random.shuffle(total_train_idx) + train_idx = total_train_idx[val_num:] + val_idx = total_train_idx[:val_num] + + + + # val_X, val_y = train_X[val_idx], train_y[val_idx] + # train_X, train_y = train_X[train_idx], train_y[train_idx] + + # model = _MODELS[info['task_type']] + + # return train_X, train_y, train_X, train_y, test_X, test_y, model + + + + val_X, val_y = train_X[val_idx], train_y[val_idx] + train_X, train_y = train_X[train_idx], train_y[train_idx] + + model = _MODELS[info['task_type']] + + return train_X, train_y, val_X, val_y, test_X, test_y, model + +class FeatureMaker: + + def __init__(self, metadata, label_column='label', label_type='int', sample=50000): + self.columns = metadata['columns'] + self.label_column = label_column + self.label_type = label_type + self.sample = sample + self.encoders = dict() + + def make_features(self, data): + data = data.copy() + np.random.shuffle(data) + data = data[:self.sample] + + features = [] + labels = [] + + for index, cinfo in enumerate(self.columns): + col = data[:, index] + if cinfo['name'] == self.label_column: + if self.label_type == 'int': + labels = col.astype(int) + elif self.label_type == 'float': + labels = col.astype(float) + else: + assert 0, 'unkown label type' + continue + + if cinfo['type'] == CONTINUOUS: + cmin = cinfo['min'] + cmax = cinfo['max'] + if cmin >= 0 and cmax >= 1e3: + feature = np.log(np.maximum(col, 1e-2)) + + else: + feature = (col - cmin) / (cmax - cmin) * 5 + + else: + if cinfo['size'] <= 2: + feature = col + + else: + encoder = self.encoders.get(index) + col = col.reshape(-1, 1) + if encoder: + feature = encoder.transform(col) + else: + encoder = OneHotEncoder(sparse=False, handle_unknown='ignore') + self.encoders[index] = encoder + feature = encoder.fit_transform(col) + + features.append(feature) + + features = np.column_stack(features) + + return features, labels + + +def _prepare_ml_problem(train, val, test, metadata, eval): + fm = FeatureMaker(metadata) + x_trains, y_trains = [], [] + + for i in train: + x_train, y_train = fm.make_features(i) + x_trains.append(x_train) + y_trains.append(y_train) + + x_val, y_val = fm.make_features(val) + if eval is None: + x_test = None + y_test = None + else: + x_test, y_test = fm.make_features(test) + model = _MODELS[metadata['problem_type']] + + return x_trains, y_trains, x_val, y_val, x_test, y_test, model + + +def _weighted_f1(y_test, pred): + report = classification_report(y_test, pred, output_dict=True) + classes = list(report.keys())[:-3] + proportion = [ report[i]['support'] / len(y_test) for i in classes] + weighted_f1 = np.sum(list(map(lambda i, prop: report[i]['f1-score']* (1-prop)/(len(classes)-1), classes, proportion))) + return weighted_f1 + + +@ignore_warnings(category=ConvergenceWarning) +def _evaluate_multi_classification(train, test, info, val=None): + x_trains, y_trains, x_valid, y_valid, x_test, y_test, classifiers = prepare_ml_problem(train, test, info, val=val) + best_f1_scores = [] + unique_labels = np.unique(y_trains) + + + best_f1_scores = [] + best_weighted_scores = [] + best_auroc_scores = [] + best_acc_scores = [] + best_avg_scores = [] + + for model_spec in classifiers: + model_class = model_spec['class'] + model_kwargs = model_spec.get('kwargs', dict()) + model_repr = model_class.__name__ + + unique_labels = np.unique(y_trains) + + param_set = list(ParameterGrid(model_kwargs)) + + results = [] + for param in tqdm(param_set): + model = model_class(**param) + + try: + model.fit(x_trains, y_trains) + except: + pass + + if len(unique_labels) != len(np.unique(y_valid)): + pred = [unique_labels[0]] * len(x_valid) + pred_prob = np.array([1.] * len(x_valid)) + else: + pred = model.predict(x_valid) + pred_prob = model.predict_proba(x_valid) + + macro_f1 = f1_score(y_valid, pred, average='macro') + weighted_f1 = _weighted_f1(y_valid, pred) + acc = accuracy_score(y_valid, pred) + + # 3. auroc + # size = [a["size"] for a in metadata["columns"] if a["name"] == "label"][0] + size = len(set(unique_labels)) + rest_label = set(range(size)) - set(unique_labels) + tmp = [] + j = 0 + for i in range(size): + if i in rest_label: + tmp.append(np.array([0] * y_valid.shape[0])[:,np.newaxis]) + else: + try: + tmp.append(pred_prob[:,[j]]) + except: + tmp.append(pred_prob[:, np.newaxis]) + j += 1 + + roc_auc = roc_auc_score(np.eye(size)[y_valid], np.hstack(tmp), multi_class='ovr') + + results.append( + { + "name": model_repr, + "param": param, + "macro_f1": macro_f1, + "weighted_f1": weighted_f1, + "roc_auc": roc_auc, + "accuracy": acc + } + ) + + results = pd.DataFrame(results) + results['avg'] = results.loc[:, ['macro_f1', 'weighted_f1', 'roc_auc']].mean(axis=1) + best_f1_param = results.param[results.macro_f1.idxmax()] + best_weighted_param = results.param[results.weighted_f1.idxmax()] + best_auroc_param = results.param[results.roc_auc.idxmax()] + best_acc_param = results.param[results.accuracy.idxmax()] + best_avg_param = results.param[results.avg.idxmax()] + + + # test the best model + results = pd.DataFrame(results) + # best_param = results.param[results.macro_f1.idxmax()] + + def _calc(best_model): + best_scores = [] + + x_train = x_trains + y_train = y_trains + + try: + best_model.fit(x_train, y_train) + except: + pass + + if len(unique_labels) != len(np.unique(y_test)): + pred = [unique_labels[0]] * len(x_test) + pred_prob = np.array([1.] * len(x_test)) + else: + pred = best_model.predict(x_test) + pred_prob = best_model.predict_proba(x_test) + + macro_f1 = f1_score(y_test, pred, average='macro') + weighted_f1 = _weighted_f1(y_test, pred) + acc = accuracy_score(y_test, pred) + + # 3. auroc + size = len(set(unique_labels)) + rest_label = set(range(size)) - set(unique_labels) + tmp = [] + j = 0 + for i in range(size): + if i in rest_label: + tmp.append(np.array([0] * y_test.shape[0])[:,np.newaxis]) + else: + try: + tmp.append(pred_prob[:,[j]]) + except: + tmp.append(pred_prob[:, np.newaxis]) + j += 1 + roc_auc = roc_auc_score(np.eye(size)[y_test], np.hstack(tmp), multi_class='ovr') + + best_scores.append( + { + "name": model_repr, + "macro_f1": macro_f1, + "weighted_f1": weighted_f1, + "roc_auc": roc_auc, + "accuracy": acc + } + ) + return pd.DataFrame(best_scores) + + def _df(dataframe): + return { + "name": model_repr, + "macro_f1": dataframe.macro_f1.values[0], + "roc_auc": dataframe.roc_auc.values[0], + "weighted_f1": dataframe.weighted_f1.values[0], + "accuracy": dataframe.accuracy.values[0], + } + + best_f1_scores.append(_df(_calc(model_class(**best_f1_param)))) + best_weighted_scores.append(_df(_calc(model_class(**best_weighted_param)))) + best_auroc_scores.append(_df(_calc(model_class(**best_auroc_param)))) + best_acc_scores.append(_df(_calc(model_class(**best_acc_param)))) + best_avg_scores.append(_df(_calc(model_class(**best_avg_param)))) + + return best_f1_scores, best_weighted_scores, best_auroc_scores, best_acc_scores, best_avg_scores + +@ignore_warnings(category=ConvergenceWarning) +def _evaluate_binary_classification(train, test, info, val=None): + x_trains, y_trains, x_valid, y_valid, x_test, y_test, classifiers = prepare_ml_problem(train, test, info, val=val) + + unique_labels = np.unique(y_trains) + + best_f1_scores = [] + best_weighted_scores = [] + best_auroc_scores = [] + best_acc_scores = [] + best_avg_scores = [] + + for model_spec in classifiers: + + model_class = model_spec['class'] + model_kwargs = model_spec.get('kwargs', dict()) + model_repr = model_class.__name__ + + unique_labels = np.unique(y_trains) + + param_set = list(ParameterGrid(model_kwargs)) + + results = [] + for param in tqdm(param_set): + model = model_class(**param) + + try: + model.fit(x_trains, y_trains) + except ValueError: + pass + + if len(unique_labels) == 1: + pred = [unique_labels[0]] * len(x_valid) + pred_prob = np.array([1.] * len(x_valid)) + else: + pred = model.predict(x_valid) + pred_prob = model.predict_proba(x_valid) + + binary_f1 = f1_score(y_valid, pred, average='binary') + weighted_f1 = _weighted_f1(y_valid, pred) + acc = accuracy_score(y_valid, pred) + precision = precision_score(y_valid, pred, average='binary') + recall = recall_score(y_valid, pred, average='binary') + macro_f1 = f1_score(y_valid, pred, average='macro') + + # auroc + size = 2 + rest_label = set(range(size)) - set(unique_labels) + tmp = [] + j = 0 + for i in range(size): + if i in rest_label: + tmp.append(np.array([0] * y_valid.shape[0])[:,np.newaxis]) + else: + try: + tmp.append(pred_prob[:,[j]]) + except: + tmp.append(pred_prob[:, np.newaxis]) + j += 1 + roc_auc = roc_auc_score(np.eye(size)[y_valid], np.hstack(tmp)) + + results.append( + { + "name": model_repr, + "param": param, + "binary_f1": binary_f1, + "weighted_f1": weighted_f1, + "roc_auc": roc_auc, + "accuracy": acc, + "precision": precision, + "recall": recall, + "macro_f1": macro_f1 + } + ) + + + # test the best model + results = pd.DataFrame(results) + results['avg'] = results.loc[:, ['binary_f1', 'weighted_f1', 'roc_auc']].mean(axis=1) + best_f1_param = results.param[results.binary_f1.idxmax()] + best_weighted_param = results.param[results.weighted_f1.idxmax()] + best_auroc_param = results.param[results.roc_auc.idxmax()] + best_acc_param = results.param[results.accuracy.idxmax()] + best_avg_param = results.param[results.avg.idxmax()] + + + def _calc(best_model): + best_scores = [] + + best_model.fit(x_trains, y_trains) + + if len(unique_labels) == 1: + pred = [unique_labels[0]] * len(x_test) + pred_prob = np.array([1.] * len(x_test)) + else: + pred = best_model.predict(x_test) + pred_prob = best_model.predict_proba(x_test) + + binary_f1 = f1_score(y_test, pred, average='binary') + weighted_f1 = _weighted_f1(y_test, pred) + acc = accuracy_score(y_test, pred) + precision = precision_score(y_test, pred, average='binary') + recall = recall_score(y_test, pred, average='binary') + macro_f1 = f1_score(y_test, pred, average='macro') + + # auroc + size = 2 + rest_label = set(range(size)) - set(unique_labels) + tmp = [] + j = 0 + for i in range(size): + if i in rest_label: + tmp.append(np.array([0] * y_test.shape[0])[:,np.newaxis]) + else: + try: + tmp.append(pred_prob[:,[j]]) + except: + tmp.append(pred_prob[:, np.newaxis]) + j += 1 + try: + roc_auc = roc_auc_score(np.eye(size)[y_test], np.hstack(tmp)) + except ValueError: + tmp[1] = tmp[1].reshape(20000, 1) + roc_auc = roc_auc_score(np.eye(size)[y_test], np.hstack(tmp)) + + best_scores.append( + { + "name": model_repr, + # "param": param, + "binary_f1": binary_f1, + "weighted_f1": weighted_f1, + "roc_auc": roc_auc, + "accuracy": acc, + "precision": precision, + "recall": recall, + "macro_f1": macro_f1 + } + ) + + return pd.DataFrame(best_scores) + def _df(dataframe): + return { + "name": model_repr, + "binary_f1": dataframe.binary_f1.values[0], + "roc_auc": dataframe.roc_auc.values[0], + "weighted_f1": dataframe.weighted_f1.values[0], + "accuracy": dataframe.accuracy.values[0], + } + + best_f1_scores.append(_df(_calc(model_class(**best_f1_param)))) + best_weighted_scores.append(_df(_calc(model_class(**best_weighted_param)))) + best_auroc_scores.append(_df(_calc(model_class(**best_auroc_param)))) + best_acc_scores.append(_df(_calc(model_class(**best_acc_param)))) + best_avg_scores.append(_df(_calc(model_class(**best_avg_param)))) + + return best_f1_scores, best_weighted_scores, best_auroc_scores, best_acc_scores, best_avg_scores + +@ignore_warnings(category=ConvergenceWarning) +def _evaluate_regression(train, test, info, val=None): + + x_trains, y_trains, x_valid, y_valid, x_test, y_test, regressors = prepare_ml_problem(train, test, info, val=val) + + + best_r2_scores = [] + best_ev_scores = [] + best_mae_scores = [] + best_rmse_scores = [] + best_avg_scores = [] + + y_trains = np.log(np.clip(y_trains, 1, 20000)) + y_test = np.log(np.clip(y_test, 1, 20000)) + + for model_spec in regressors: + model_class = model_spec['class'] + model_kwargs = model_spec.get('kwargs', dict()) + model_repr = model_class.__name__ + + param_set = list(ParameterGrid(model_kwargs)) + + results = [] + for param in tqdm(param_set): + model = model_class(**param) + model.fit(x_trains, y_trains) + pred = model.predict(x_valid) + + r2 = r2_score(y_valid, pred) + explained_variance = explained_variance_score(y_valid, pred) + mean_squared = mean_squared_error(y_valid, pred) + root_mean_squared = np.sqrt(mean_squared) + mean_absolute = mean_absolute_error(y_valid, pred) + + results.append( + { + "name": model_repr, + "param": param, + "r2": r2, + "explained_variance": explained_variance, + "mean_squared": mean_squared, + "mean_absolute": mean_absolute, + "rmse": root_mean_squared + } + ) + + results = pd.DataFrame(results) + # results['avg'] = results.loc[:, ['r2', 'rmse']].mean(axis=1) + best_r2_param = results.param[results.r2.idxmax()] + best_ev_param = results.param[results.explained_variance.idxmax()] + best_mae_param = results.param[results.mean_absolute.idxmin()] + best_rmse_param = results.param[results.rmse.idxmin()] + # best_avg_param = results.param[results.avg.idxmax()] + + def _calc(best_model): + best_scores = [] + x_train, y_train = x_trains, y_trains + + best_model.fit(x_train, y_train) + pred = best_model.predict(x_test) + + r2 = r2_score(y_test, pred) + explained_variance = explained_variance_score(y_test, pred) + mean_squared = mean_squared_error(y_test, pred) + root_mean_squared = np.sqrt(mean_squared) + mean_absolute = mean_absolute_error(y_test, pred) + + best_scores.append( + { + "name": model_repr, + "param": param, + "r2": r2, + "explained_variance": explained_variance, + "mean_squared": mean_squared, + "mean_absolute": mean_absolute, + "rmse": root_mean_squared + } + ) + + return pd.DataFrame(best_scores) + + def _df(dataframe): + return { + "name": model_repr, + "r2": dataframe.r2.values[0].astype(float), + "explained_variance": dataframe.explained_variance.values[0].astype(float), + "MAE": dataframe.mean_absolute.values[0].astype(float), + "RMSE": dataframe.rmse.values[0].astype(float), + } + + best_r2_scores.append(_df(_calc(model_class(**best_r2_param)))) + best_ev_scores.append(_df(_calc(model_class(**best_ev_param)))) + best_mae_scores.append(_df(_calc(model_class(**best_mae_param)))) + best_rmse_scores.append(_df(_calc(model_class(**best_rmse_param)))) + + return best_r2_scores, best_rmse_scores + +@ignore_warnings(category=ConvergenceWarning) +def compute_diversity(train, fake): + nearest_k = 5 + if train.shape[0] >= 50000: + num = np.random.randint(0, train.shape[0], 50000) + real_features = train[num] + fake_features_lst = [i[num] for i in fake] + else: + num = train.shape[0] + real_features = train[:num] + fake_features_lst = [i[:num] for i in fake] + scores = [] + for i, data in enumerate(fake_features_lst): + fake_features = data + metrics = compute_prdc(real_features=real_features, + fake_features=fake_features, + nearest_k=nearest_k) + metrics['i'] = i + scores.append(metrics) + return pd.DataFrame(scores).mean(axis=0), pd.DataFrame(scores).std(axis=0) + +_EVALUATORS = { + 'binclass': _evaluate_binary_classification, + 'multiclass': _evaluate_multi_classification, + 'regression': _evaluate_regression +} + +def get_evaluator(problem_type): + return _EVALUATORS[problem_type] + + +def compute_scores(train, test, synthesized_data, metadata, eval): + a, b, c = _EVALUATORS[metadata['problem_type']](train=train, test=test, fake=synthesized_data, metadata=metadata, eval=eval) + if eval is None: + return a.mean(axis=0), a.std(axis=0), a[['name','param']] + else: + return a.mean(axis=0), a.std(axis=0) + diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/eval/mle/tabular_dataload.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/eval/mle/tabular_dataload.py new file mode 100644 index 0000000000000000000000000000000000000000..d5561f456cdc32ca553f00c01f1c4b868aef37cb --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/eval/mle/tabular_dataload.py @@ -0,0 +1,111 @@ +# coding=utf-8 +# Copyright 2020 The Google Research Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# pylint: skip-file +"""Return training and evaluation/test datasets from config files.""" +import torch +import numpy as np +import pandas as pd +from tabular_transformer import GeneralTransformer +import json +import logging +import os + +CATEGORICAL = "categorical" +CONTINUOUS = "continuous" + +LOGGER = logging.getLogger(__name__) + +DATA_PATH = os.path.join(os.path.dirname(__file__), 'tabular_datasets') + +def _load_json(path): + with open(path) as json_file: + return json.load(json_file) + + +def _load_file(filename, loader): + local_path = os.path.join(DATA_PATH, filename) + + if loader == np.load: + return loader(local_path, allow_pickle=True) + return loader(local_path) + + +def _get_columns(metadata): + categorical_columns = list() + + for column_idx, column in enumerate(metadata['columns']): + if column['type'] == CATEGORICAL: + categorical_columns.append(column_idx) + + return categorical_columns + + +def load_data(name): + data_dir = f'data/{name}' + info_path = f'{data_dir}/info.json' + + train = pd.read_csv(f'{data_dir}/train.csv').to_numpy() + test = pd.read_csv(f'{data_dir}/test.csv').to_numpy() + + with open(f'{data_dir}/info.json', 'r') as f: + info = json.load(f) + + task_type = info['task_type'] + + num_cols = info['num_col_idx'] + cat_cols = info['cat_col_idx'] + target_cols = info['target_col_idx'] + + if task_type != 'regression': + cat_cols = cat_cols + target_cols + + return train, test, (cat_cols, info) + + +def get_dataset(FLAGS, evaluation=False): + + batch_size = FLAGS.training_batch_size if not evaluation else FLAGS.eval_batch_size + + if batch_size % torch.cuda.device_count() != 0: + raise ValueError(f'Batch sizes ({batch_size} must be divided by' + f'the number of devices ({torch.cuda.device_count()})') + + + # Create dataset builders for tabular data. + train, test, cols = load_data(FLAGS.dataname) + cols_idx = list(np.arange(train.shape[1])) + dis_idx = cols[0] + con_idx = [x for x in cols_idx if x not in dis_idx] + + #split continuous and categorical + train_con = train[:,con_idx] + train_dis = train[:,dis_idx] + + #new index + cat_idx_ = list(np.arange(train_dis.shape[1]))[:len(cols[0])] + + transformer_con = GeneralTransformer() + transformer_dis = GeneralTransformer() + + transformer_con.fit(train_con, []) + transformer_dis.fit(train_dis, cat_idx_) + + train_con_data = transformer_con.transform(train_con) + train_dis_data = transformer_dis.transform(train_dis) + + + return train, train_con_data, train_dis_data, test, (transformer_con, transformer_dis, cols[1]), con_idx, dis_idx + \ No newline at end of file diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/eval/mle/tabular_transformer.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/eval/mle/tabular_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..571e86a298d4b973484c7fd488819e86b5f14d30 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/eval/mle/tabular_transformer.py @@ -0,0 +1,110 @@ +import numpy as np +import pandas as pd + +CATEGORICAL = "categorical" +CONTINUOUS = "continuous" + +class Transformer: + + @staticmethod + def get_metadata(data, categorical_columns=tuple()): + meta = [] + + df = pd.DataFrame(data) + for index in df: + column = df[index] + + if index in categorical_columns: + mapper = column.value_counts().index.tolist() + meta.append({ + "name": index, + "type": CATEGORICAL, + "size": len(mapper), + "i2s": mapper + }) + else: + meta.append({ + "name": index, + "type": CONTINUOUS, + "min": column.min(), + "max": column.max(), + }) + + return meta + + def fit(self, data, categorical_columns=tuple()): + raise NotImplementedError + + def transform(self, data): + raise NotImplementedError + + def inverse_transform(self, data): + raise NotImplementedError + + +class GeneralTransformer(Transformer): + + def __init__(self, act='tanh'): + self.act = act + self.meta = None + self.output_dim = None + + def fit(self, data, categorical_columns=tuple()): + self.meta = self.get_metadata(data, categorical_columns) + self.output_dim = 0 + for info in self.meta: + if info['type'] in [CONTINUOUS]: + self.output_dim += 1 + else: + self.output_dim += info['size'] + + def transform(self, data): + data_t = [] + self.output_info = [] + for id_, info in enumerate(self.meta): + col = data[:, id_] + if info['type'] == CONTINUOUS: + col = (col - (info['min'])) / (info['max'] - info['min']) + if self.act == 'tanh': + col = col * 2 - 1 + data_t.append(col.reshape([-1, 1])) + self.output_info.append((1, self.act)) + + else: + col_t = np.zeros([len(data), info['size']]) + idx = list(map(info['i2s'].index, col)) + col_t[np.arange(len(data)), idx] = 1 + data_t.append(col_t) + self.output_info.append((info['size'], 'softmax')) + + return np.concatenate(data_t, axis=1) + + def inverse_transform(self, data): + if self.meta[1]['type'] == CONTINUOUS: + data_t = np.zeros([len(data), len(self.meta)]) + else: + dtype = np.dtype('U50') + data_t = np.empty([len(data), len(self.meta)], dtype=dtype) + + + data = data.copy() + for id_, info in enumerate(self.meta): + + if info['type'] == CONTINUOUS: + current = data[:, 0] + data = data[:, 1:] + + if self.act == 'tanh': + current = (current + 1) / 2 + + current = np.clip(current, 0, 1) + data_t[:, id_] = current * (info['max'] - info['min']) + info['min'] + + else: + current = data[:, :info['size']] + data = data[:, info['size']:] + idx = np.argmax(current, axis=1) + recovered = list(map(info['i2s'].__getitem__, idx)) + + data_t[:, id_] = recovered + return data_t diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/eval/visualize_density.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/eval/visualize_density.py new file mode 100644 index 0000000000000000000000000000000000000000..d7ee36fac552e916bbb238796e2fb2af1ebe5d50 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/eval/visualize_density.py @@ -0,0 +1,85 @@ +# %% +import numpy as np +import pandas as pd +import torch +import os + +import json + +# Metrics +from sdmetrics.visualization import get_column_plot + +import plotly.io as pio +from PIL import Image +from io import BytesIO + +from tqdm import tqdm +import argparse + +def main(args): + dataname = args.dataname + sample_file_name = args.sample_file_name + + syn_path = f'synthetic/{dataname}/{sample_file_name}' + real_path = f'synthetic/{dataname}/real.csv' + + syn_data = pd.read_csv(syn_path) + real_data = pd.read_csv(real_path) + + print((real_data[:2])) + + data_dir = f'data/{dataname}' + with open(f'{data_dir}/info.json', 'r') as f: + info = json.load(f) + + big_img = plot_density(syn_data, real_data, info) + + save_dir = f"eval/density_graphs/{dataname}" + if not os.path.exists(save_dir): + os.makedirs(save_dir) + save_path = os.path.join(save_dir, sample_file_name.replace('.csv', '.png')) + big_img.save(save_path) + print(f"Saved density graph to {save_path}") + +def plot_density(syn_data, real_data, info, num_per_row=3): + column_names = info['column_names'] + num_cat = len(column_names) + num_col = num_per_row + num_row = (num_cat-1)//num_col+1 + + imgs = [] + for i, col in tqdm(enumerate(column_names), total = len(column_names)): + # plot_type = 'bar' if i in info['cat_col_idx'] else 'distplot' + plot_type = 'bar' if info['metadata']['columns'][str(i)]['sdtype'] == 'categorical' else 'distplot' + if plot_type == 'distplot' and (syn_data[col][0] == syn_data[col]).all(): # to tackle a very weird bug + # If the continuous data all aggregate at a single value, get_column_plot() cannot plot a density curve for it. + # So, we perturb one entry of the cont data by a small amount + print(f"\n ALERT: the generated samples column_{i} with name '{col}' all has the same value of {syn_data[col][0]} \n") + syn_data[col][0] += 1e-5 + fig = get_column_plot( + real_data=real_data, + synthetic_data=syn_data, + column_name=col, + plot_type=plot_type + ) + + img_bytes = pio.to_image(fig, format='png') + img = Image.open(BytesIO(img_bytes)) + imgs.append(img) + + width, height = imgs[0].size + big_img = Image.new('RGB', (width * num_col, height * num_row)) + for i, img in enumerate(imgs): + coordinate = (i%num_col * width, i//num_col * height) + big_img.paste(img, coordinate) + return big_img + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + + parser.add_argument('--dataname', type=str, default='adult') + parser.add_argument('--sample_file_name', type=str, default='tabsyn.csv') + + args = parser.parse_args() + + main(args) \ No newline at end of file diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/main.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/main.py new file mode 100644 index 0000000000000000000000000000000000000000..130d47e75031b33569dd660e79609e5eb0d5fcf5 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/main.py @@ -0,0 +1,263 @@ +import glob +import json +import os +import pickle +import random + +import numpy as np +from ef_vfm.metrics import TabMetrics +from ef_vfm.modules.main_modules import UniModMLP +from ef_vfm.models.flow_model import ExpVFM +from ef_vfm.trainer import Trainer +import src +import torch + +from torch.utils.data import DataLoader +import argparse +import 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"]) + + _train_batch = os.environ.get("EFVFM_TRAIN_BATCH_SIZE", "").strip() + if _train_batch and args.mode == "train": + raw_config["train"]["main"]["batch_size"] = max(1, int(_train_batch)) + _check_val = os.environ.get("EFVFM_CHECK_VAL_EVERY", "").strip() + if _check_val and args.mode == "train": + raw_config["train"]["main"]["check_val_every"] = max(1, int(_check_val)) + _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.') + parser.add_argument('--mode', type=str, default='train', choices=['train', 'test'], help='Run mode.') + parser.add_argument('--exp_name', type=str, default=None, help='Experiment name.') + parser.add_argument('--no_wandb', action='store_true', help='Disable wandb online logging.') + parser.add_argument('--debug', action='store_true', help='Enable debug mode.') + parser.add_argument('--deterministic', action='store_true', help='Enable deterministic execution.') + parser.add_argument('--num_samples_to_generate', type=int, default=None, help='Number of rows to generate in test mode.') + parser.add_argument('--ckpt_path', type=str, default=None, help='Checkpoint path for test mode.') + parser.add_argument('--report', action='store_true', help='Run report evaluation in test mode.') + parser.add_argument('--num_runs', type=int, default=1, help='Number of report runs.') + + 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' + + main(args) diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/process_dataset.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/process_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..38004d944f5ebe15a1147df0bc9e0e1abdef3ed5 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/process_dataset.py @@ -0,0 +1,492 @@ +import numpy as np +import pandas as pd +import os +import sys +import json +import argparse + +from sklearn.preprocessing import OrdinalEncoder +from sklearn import model_selection + +TYPE_TRANSFORM ={ + 'float', np.float32, + 'str', str, + 'int', int +} + +INFO_PATH = 'data/Info' + +parser = argparse.ArgumentParser(description='process dataset') + +# General configs +parser.add_argument('--dataname', type=str, default=None, help='Name of dataset.') +args = parser.parse_args() + +def preprocess_beijing(): + with open(f'{INFO_PATH}/beijing.json', 'r') as f: + info = json.load(f) + + data_path = info['raw_data_path'] + + data_df = pd.read_csv(data_path) + columns = data_df.columns + + data_df = data_df[columns[1:]] + + + df_cleaned = data_df.dropna() + df_cleaned.to_csv(info['data_path'], index = False) + +def preprocess_beijing_dcr(): + with open(f'{INFO_PATH}/beijing_dcr.json', 'r') as f: + info = json.load(f) + + data_path = info['raw_data_path'] + + data_df = pd.read_csv(data_path) + columns = data_df.columns + + data_df = data_df[columns[1:]] + + df_cleaned = data_df.dropna() + df_cleaned.to_csv(info['data_path'], index = False) + +def preprocess_news(remove_cat=False): + name = 'news' if not remove_cat else 'news_nocat' + with open(f'{INFO_PATH}/{name}.json', 'r') as f: + info = json.load(f) + + data_path = info['raw_data_path'] + data_df = pd.read_csv(data_path) + data_df = data_df.drop('url', axis=1) + + columns = np.array(data_df.columns.tolist()) + + cat_columns1 = columns[list(range(12,18))] + cat_columns2 = columns[list(range(30,38))] + + if not remove_cat: + cat_col1 = data_df[cat_columns1].astype(int).to_numpy().argmax(axis = 1) + cat_col2 = data_df[cat_columns2].astype(int).to_numpy().argmax(axis = 1) + + data_df = data_df.drop(cat_columns2, axis=1) + data_df = data_df.drop(cat_columns1, axis=1) + + if not remove_cat: + data_df['data_channel'] = cat_col1 + data_df['weekday'] = cat_col2 + + data_save_path = f'data/{name}/{name}.csv' + data_df.to_csv(f'{data_save_path}', index = False) + + columns = np.array(data_df.columns.tolist()) + num_columns = columns[list(range(45))] + cat_columns = ['data_channel', 'weekday'] if not remove_cat else [] + target_columns = columns[[45]] + + info['num_col_idx'] = list(range(45)) + info['cat_col_idx'] = [46, 47] if not remove_cat else [] + info['target_col_idx'] = [45] + info['data_path'] = data_save_path + + with open(f'{INFO_PATH}/{name}.json', 'w') as file: + json.dump(info, file, indent=4) + +def preprocess_news_dcr(remove_cat=False): + name = 'news_dcr' if not remove_cat else 'news_nocat_dcr' + with open(f'{INFO_PATH}/{name}.json', 'r') as f: + info = json.load(f) + + data_path = info['raw_data_path'] + data_df = pd.read_csv(data_path) + data_df = data_df.drop('url', axis=1) + + columns = np.array(data_df.columns.tolist()) + + cat_columns1 = columns[list(range(12,18))] + cat_columns2 = columns[list(range(30,38))] + + if not remove_cat: + cat_col1 = data_df[cat_columns1].astype(int).to_numpy().argmax(axis = 1) + cat_col2 = data_df[cat_columns2].astype(int).to_numpy().argmax(axis = 1) + + data_df = data_df.drop(cat_columns2, axis=1) + data_df = data_df.drop(cat_columns1, axis=1) + + if not remove_cat: + data_df['data_channel'] = cat_col1 + data_df['weekday'] = cat_col2 + + data_save_path = f'data/{name}/{name}.csv' + data_df.to_csv(f'{data_save_path}', index = False) + + columns = np.array(data_df.columns.tolist()) + num_columns = columns[list(range(45))] + cat_columns = ['data_channel', 'weekday'] if not remove_cat else [] + target_columns = columns[[45]] + + info['num_col_idx'] = list(range(45)) + info['cat_col_idx'] = [46, 47] if not remove_cat else [] + info['target_col_idx'] = [45] + info['data_path'] = data_save_path + + with open(f'{INFO_PATH}/{name}.json', 'w') as file: + json.dump(info, file, indent=4) + + +def get_column_name_mapping(data_df, num_col_idx, cat_col_idx, target_col_idx, column_names = None): + + if not column_names: + column_names = np.array(data_df.columns.tolist()) + + idx_mapping = {} + + curr_num_idx = 0 + curr_cat_idx = len(num_col_idx) + curr_target_idx = curr_cat_idx + len(cat_col_idx) + + for idx in range(len(column_names)): + + if idx in num_col_idx: + idx_mapping[int(idx)] = curr_num_idx + curr_num_idx += 1 + elif idx in cat_col_idx: + idx_mapping[int(idx)] = curr_cat_idx + curr_cat_idx += 1 + else: + idx_mapping[int(idx)] = curr_target_idx + curr_target_idx += 1 + + inverse_idx_mapping = {} + for k, v in idx_mapping.items(): + inverse_idx_mapping[int(v)] = k + + idx_name_mapping = {} + + for i in range(len(column_names)): + idx_name_mapping[int(i)] = column_names[i] + + return idx_mapping, inverse_idx_mapping, idx_name_mapping + + +def train_val_test_split(data_df, cat_columns, num_train = 0, num_test = 0): + total_num = data_df.shape[0] + idx = np.arange(total_num) + + seed = 1234 + + while True: + np.random.seed(seed) + np.random.shuffle(idx) + + train_idx = idx[:num_train] + test_idx = idx[-num_test:] + + train_df = data_df.loc[train_idx] + test_df = data_df.loc[test_idx] + + flag = 0 + for i in cat_columns: + if len(set(train_df[i])) != len(set(data_df[i])): + flag = 1 + break + + if flag == 0: + break + else: + seed += 1 + + return train_df, test_df, seed + + +def process_data(name): + + if name == 'news': + preprocess_news() + elif name == 'news_nocat': + preprocess_news(remove_cat=True) + elif name == 'news_dcr': + preprocess_news_dcr() + elif name == 'beijing': + preprocess_beijing() + elif name == 'beijing_dcr': + preprocess_beijing_dcr() + + with open(f'{INFO_PATH}/{name}.json', 'r') as f: + info = json.load(f) + + data_path = info['data_path'] + if info['file_type'] == 'csv': + data_df = pd.read_csv(data_path, header = info['header']) + + elif info['file_type'] == 'xls': + data_df = pd.read_excel(data_path, sheet_name='Data', header=1) + data_df = data_df.drop('ID', axis=1) + + num_data = data_df.shape[0] + + column_names = info['column_names'] if info['column_names'] else data_df.columns.tolist() + + num_col_idx = info['num_col_idx'] + cat_col_idx = info['cat_col_idx'] + target_col_idx = info['target_col_idx'] + + num_columns = [column_names[i] for i in num_col_idx] + cat_columns = [column_names[i] for i in cat_col_idx] + target_columns = [column_names[i] for i in target_col_idx] + + 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) + + has_val = bool(info['val_path']) + 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 + if info['test_path']: + + # if testing data is given + test_path = info['test_path'] + + 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 + with open(test_path, 'r') as f: + lines = f.readlines()[1:] + test_save_path = f'data/{name}/test.data' + if not os.path.exists(test_save_path): + with open(test_save_path, 'a') as f1: + for line in lines: + save_line = line.strip('\n').strip('.') + f1.write(f'{save_line}\n') + + test_df = pd.read_csv(test_save_path, header = None) + else: + test_df = pd.read_csv(test_path, header = info['header']) + + if has_val: # currently you cannot have a val path without a test path + val_path = info['val_path'] + val_df = pd.read_csv(val_path, header = info['header']) + + train_df = data_df + + 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 + complete_df = pd.concat([train_df, test_df, val_df], axis = 0, ignore_index=True) + num_data = complete_df.shape[0] + num_train = int(num_data*0.5) + num_test = num_data - num_train + complete_df.rename(columns = idx_name_mapping, inplace=True) + train_df, test_df, seed = train_val_test_split(complete_df, cat_columns, num_train, num_test) + + else: + # Train/ Test Split, 90% Training (50% for dcr eval exclusively), 10% Testing (Validation set will be selected from Training set) + if "dcr" in name: + num_train = int(num_data*0.5) + else: + num_train = int(num_data*0.9) + num_test = num_data - num_train + + train_df, test_df, seed = train_val_test_split(data_df, cat_columns, num_train, num_test) + + complete_df = pd.concat([train_df, test_df, val_df], axis = 0) + name_idx_mapping = {val: key for key, val in idx_name_mapping.items()} + int_columns = [] + int_col_idx = [] + int_col_idx_wrt_num = [] + for i, col_idx in enumerate(num_col_idx): + col = column_names[col_idx] + col_data = complete_df.iloc[:,col_idx] + is_int = (col_data%1 == 0).all() + if is_int: + int_columns.append(col) + int_col_idx.append(name_idx_mapping[col]) + int_col_idx_wrt_num.append(i) + info['int_col_idx'] = int_col_idx + info['int_columns'] = int_columns + info['int_col_idx_wrt_num'] = int_col_idx_wrt_num + + train_df.columns = range(len(train_df.columns)) + test_df.columns = range(len(test_df.columns)) + val_df.columns = range(len(val_df.columns)) + + print(name, train_df.shape, val_df.shape, test_df.shape, data_df.shape) + + col_info = {} + + for col_idx in num_col_idx: + col_info[col_idx] = {} + col_info['type'] = 'numerical' + col_info['max'] = float(train_df[col_idx].max()) + col_info['min'] = float(train_df[col_idx].min()) + + for col_idx in cat_col_idx: + col_info[col_idx] = {} + col_info['type'] = 'categorical' + col_info['categorizes'] = list(set(train_df[col_idx])) + + for col_idx in target_col_idx: + if info['task_type'] == 'regression': + col_info[col_idx] = {} + col_info['type'] = 'numerical' + col_info['max'] = float(train_df[col_idx].max()) + col_info['min'] = float(train_df[col_idx].min()) + else: + col_info[col_idx] = {} + col_info['type'] = 'categorical' + col_info['categorizes'] = list(set(train_df[col_idx])) + + info['column_info'] = col_info + + train_df.rename(columns = idx_name_mapping, inplace=True) + test_df.rename(columns = idx_name_mapping, inplace=True) + val_df.rename(columns = idx_name_mapping, inplace=True) + + for col in num_columns: + if (train_df[col] == ' ?').sum() > 0: + print(col) + import pdb; pdb.set_trace() + if (train_df[col] == '?').sum() > 0: + print(col) + import pdb; pdb.set_trace() + train_df.loc[train_df[col] == '?', col] = np.nan + for col in cat_columns: + train_df.loc[train_df[col] == '?', col] = 'nan' + for col in num_columns: + if (test_df[col] == ' ?').sum() > 0: + print(col) + import pdb; pdb.set_trace() + if (test_df[col] == '?').sum() > 0: + print(col) + import pdb; pdb.set_trace() + test_df.loc[test_df[col] == '?', col] = np.nan + for col in cat_columns: + test_df.loc[test_df[col] == '?', col] = 'nan' + for col in num_columns: + val_df.loc[val_df[col] == '?', col] = np.nan + for col in cat_columns: + val_df.loc[val_df[col] == '?', col] = 'nan' + + if train_df.isna().any().any(): + print("Training data contains nan in the numerical cols") + import pdb; pdb.set_trace() + + X_num_train = train_df[num_columns].to_numpy().astype(np.float32) + X_cat_train = train_df[cat_columns].to_numpy() + y_train = train_df[target_columns].to_numpy() + + X_num_test = test_df[num_columns].to_numpy().astype(np.float32) + X_cat_test = test_df[cat_columns].to_numpy() + y_test = test_df[target_columns].to_numpy() + + X_num_val = val_df[num_columns].to_numpy().astype(np.float32) + X_cat_val = val_df[cat_columns].to_numpy() + y_val = val_df[target_columns].to_numpy() + + save_dir = f'data/{name}' + np.save(f'{save_dir}/X_num_train.npy', X_num_train) + np.save(f'{save_dir}/X_cat_train.npy', X_cat_train) + np.save(f'{save_dir}/y_train.npy', y_train) + + np.save(f'{save_dir}/X_num_test.npy', X_num_test) + np.save(f'{save_dir}/X_cat_test.npy', X_cat_test) + np.save(f'{save_dir}/y_test.npy', y_test) + + if has_val: + np.save(f'{save_dir}/X_num_val.npy', X_num_val) + np.save(f'{save_dir}/X_cat_val.npy', X_cat_val) + np.save(f'{save_dir}/y_val.npy', y_val) + + train_df[num_columns] = train_df[num_columns].astype(np.float32) + test_df[num_columns] = test_df[num_columns].astype(np.float32) + val_df[num_columns] = val_df[num_columns].astype(np.float32) + + train_df.to_csv(f'{save_dir}/train.csv', index = False) + test_df.to_csv(f'{save_dir}/test.csv', index = False) + if has_val: + val_df.to_csv(f'{save_dir}/val.csv', index = False) + + if not os.path.exists(f'synthetic/{name}'): + os.makedirs(f'synthetic/{name}') + + train_df.to_csv(f'synthetic/{name}/real.csv', index = False) + test_df.to_csv(f'synthetic/{name}/test.csv', index = False) + + if has_val: + val_df.to_csv(f'synthetic/{name}/val.csv', index = False) + + print('Numerical', X_num_train.shape) + print('Categorical', X_cat_train.shape) + + info['column_names'] = column_names + info['train_num'] = train_df.shape[0] + info['test_num'] = test_df.shape[0] + info['val_num'] = val_df.shape[0] + + info['idx_mapping'] = idx_mapping + info['inverse_idx_mapping'] = inverse_idx_mapping + info['idx_name_mapping'] = idx_name_mapping + + metadata = {'columns': {}} + 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'] + + for i in num_col_idx: + metadata['columns'][i] = {} + metadata['columns'][i]['sdtype'] = 'numerical' + metadata['columns'][i]['computer_representation'] = 'Float' + + for i in cat_col_idx: + metadata['columns'][i] = {} + metadata['columns'][i]['sdtype'] = 'categorical' + + if task_type == 'regression': + + for i in target_col_idx: + metadata['columns'][i] = {} + metadata['columns'][i]['sdtype'] = 'numerical' + metadata['columns'][i]['computer_representation'] = 'Float' + + else: + for i in target_col_idx: + metadata['columns'][i] = {} + metadata['columns'][i]['sdtype'] = 'categorical' + + info['metadata'] = metadata + + with open(f'{save_dir}/info.json', 'w') as file: + json.dump(info, file, indent=4) + + print(f'Processing and Saving {name} Successfully!') + + print(name) + print('Total', info['train_num'] + info['test_num']) + print('Train', info['train_num']) + print('Val', info['val_num']) + print('Test', info['test_num']) + if info['task_type'] == 'regression': + num = len(info['num_col_idx'] + info['target_col_idx']) + cat = len(info['cat_col_idx']) + else: + cat = len(info['cat_col_idx'] + info['target_col_idx']) + num = len(info['num_col_idx']) + print('Num', num) + print('Int', len(info['int_col_idx'])) + print('Cat', cat) + +if __name__ == "__main__": + + if args.dataname: + process_data(args.dataname) + else: + for name in [ + 'adult', + 'default', + 'shoppers', + 'magic', + 'beijing', + 'news', + 'news_nocat', + 'adult_dcr', + 'default_dcr', + 'shoppers_dcr', + 'beijing_dcr', + 'news_dcr', + ]: + process_data(name) + diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/pyproject.toml b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..57737114306b42c08aa9fb800a23b6f746693bab --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/pyproject.toml @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bc2d5c09fdbd3457c0f7cdd1a92c8e44ea3b2ff1316a2b718865fb7e8059da36 +size 1029 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/result/pipeline_n14/adapter_efvfm/100/all_results.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/result/pipeline_n14/adapter_efvfm/100/all_results.json new file mode 100644 index 0000000000000000000000000000000000000000..27ad9dc2daf1ebb80b6c774ca4eff03d1724cfa4 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/result/pipeline_n14/adapter_efvfm/100/all_results.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e01e9dd13dde5e27da73e622be284b20337f66d3274f28b121b770395ba7aa7a +size 129 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/result/pipeline_n14/adapter_efvfm/100/ema/all_results.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/result/pipeline_n14/adapter_efvfm/100/ema/all_results.json new file mode 100644 index 0000000000000000000000000000000000000000..87dbdea684ce7b975e6cff3bfa6db6ba8232bd74 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/result/pipeline_n14/adapter_efvfm/100/ema/all_results.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d486d78d827bb47e7633d7a8ee545fe56cc2aa4ad133a685ff69db74555e1478 +size 129 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/result/pipeline_n14/adapter_efvfm/100/ema/samples.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/result/pipeline_n14/adapter_efvfm/100/ema/samples.csv new file mode 100644 index 0000000000000000000000000000000000000000..eb63755c15ea8fb10bfd36c5aea8ec52b9cae84a --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/result/pipeline_n14/adapter_efvfm/100/ema/samples.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8af08061a56e214860583e1d5c64907354be8ad55bb4111ffadbca782f436bd8 +size 280452 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/result/pipeline_n14/adapter_efvfm/100/ema/shapes.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/result/pipeline_n14/adapter_efvfm/100/ema/shapes.csv new file mode 100644 index 0000000000000000000000000000000000000000..8d659d6b48979e5c41d7d0c6ab5ccb22e5a5f38c --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/result/pipeline_n14/adapter_efvfm/100/ema/shapes.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ecada5fd19082371dd35a8aa717b6e1849502b442ec3eb7764d2f68dae7f94a2 +size 1649 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/result/pipeline_n14/adapter_efvfm/100/ema/trends.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/result/pipeline_n14/adapter_efvfm/100/ema/trends.csv new file mode 100644 index 0000000000000000000000000000000000000000..457e2dea2df785a0011ff1077d6f550965288229 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/result/pipeline_n14/adapter_efvfm/100/ema/trends.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ba81b319e3d32c273ba55de76b34000f3612e0e13a241214ffd0cca46359d336 +size 147231 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/result/pipeline_n14/adapter_efvfm/100/samples.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/result/pipeline_n14/adapter_efvfm/100/samples.csv new file mode 100644 index 0000000000000000000000000000000000000000..0ee2d9d2004f0a23e18ca9fd285675b59d2897fa --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/result/pipeline_n14/adapter_efvfm/100/samples.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1bd0fb8b36df6a7aa6de043038a7040ee5826c962eb42ffc81540c57bf18bd6c +size 851261 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/result/pipeline_n14/adapter_efvfm/100/shapes.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/result/pipeline_n14/adapter_efvfm/100/shapes.csv new file mode 100644 index 0000000000000000000000000000000000000000..86269e386d7f09e6d716cbbc164e1cee93186292 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/result/pipeline_n14/adapter_efvfm/100/shapes.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:14e4169ad707ec4684c3527d584331b03331b6c9c7267d5276887ab43eaf6033 +size 1588 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/result/pipeline_n14/adapter_efvfm/100/trends.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/result/pipeline_n14/adapter_efvfm/100/trends.csv new file mode 100644 index 0000000000000000000000000000000000000000..d12cfaa7c7b47d573b64aae10f9561a13243a48f --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/result/pipeline_n14/adapter_efvfm/100/trends.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5f1db43ed9e141c081d7186a7d4485db0f15612603ef79fe0cc58801c6b2d959 +size 87579 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/src/__init__.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/src/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..07d7a4057f36847f7accf4ca148d590d8b4fc80f --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/src/__init__.py @@ -0,0 +1,11 @@ +import torch +from icecream import install + +torch.set_num_threads(1) +install() + +from . import env # noqa +from .data import * # noqa +from .env import * # noqa +from .metrics import * # noqa +from .util import * # noqa \ No newline at end of file diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/src/data.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/src/data.py new file mode 100644 index 0000000000000000000000000000000000000000..c6906ba122d1ff276b7f475b7f6e7c3440580654 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/src/data.py @@ -0,0 +1,780 @@ +import hashlib +from collections import Counter +from copy import deepcopy +from dataclasses import astuple, dataclass, replace +from importlib.resources import path +from pathlib import Path +from typing import Any, Literal, Optional, Union, cast, Tuple, Dict, List + +import numpy as np +import pandas as pd +from sklearn.model_selection import train_test_split +from sklearn.pipeline import make_pipeline +import sklearn.preprocessing +import torch +import os +from category_encoders import LeaveOneOutEncoder +from sklearn.impute import SimpleImputer +from sklearn.preprocessing import StandardScaler +from scipy.spatial.distance import cdist + +from . import env, util +from .metrics import calculate_metrics as calculate_metrics_ +from .util import TaskType, load_json + +ArrayDict = Dict[str, np.ndarray] +TensorDict = Dict[str, torch.Tensor] + + +CAT_MISSING_VALUE = 'nan' +CAT_RARE_VALUE = '__rare__' +Normalization = Literal['standard', 'quantile', 'minmax'] +NumNanPolicy = Literal['drop-rows', 'mean'] +CatNanPolicy = Literal['most_frequent'] +CatEncoding = Literal['one-hot', 'counter'] +YPolicy = Literal['default'] +DEQUANT_DIST = Literal['uniform', 'beta', 'round', 'none'] + + +class StandardScaler1d(StandardScaler): + def partial_fit(self, X, *args, **kwargs): + assert X.ndim == 1 + return super().partial_fit(X[:, None], *args, **kwargs) + + def transform(self, X, *args, **kwargs): + assert X.ndim == 1 + return super().transform(X[:, None], *args, **kwargs).squeeze(1) + + def inverse_transform(self, X, *args, **kwargs): + assert X.ndim == 1 + return super().inverse_transform(X[:, None], *args, **kwargs).squeeze(1) + + +def get_category_sizes(X: Union[torch.Tensor, np.ndarray]) -> List[int]: + XT = X.T.cpu().tolist() if isinstance(X, torch.Tensor) else X.T.tolist() + return [len(set(x)) for x in XT] + + +@dataclass(frozen=False) +class Dataset: + X_num: Optional[ArrayDict] + X_cat: Optional[ArrayDict] + y: ArrayDict + int_col_idx_wrt_num: list + y_info: Dict[str, Any] + task_type: TaskType + n_classes: Optional[int] + + @classmethod + def from_dir(cls, dir_: Union[Path, str]) -> 'Dataset': + dir_ = Path(dir_) + splits = [k for k in ['train', 'test'] if dir_.joinpath(f'y_{k}.npy').exists()] + + def load(item) -> ArrayDict: + return { + x: cast(np.ndarray, np.load(dir_ / f'{item}_{x}.npy', allow_pickle=True)) # type: ignore[code] + for x in splits + } + + if Path(dir_ / 'info.json').exists(): + info = util.load_json(dir_ / 'info.json') + else: + info = None + return Dataset( + load('X_num') if dir_.joinpath('X_num_train.npy').exists() else None, + load('X_cat') if dir_.joinpath('X_cat_train.npy').exists() else None, + load('y'), + {}, + TaskType(info['task_type']), + info.get('n_classes'), + ) + + @property + def is_binclass(self) -> bool: + return self.task_type == TaskType.BINCLASS + + @property + def is_multiclass(self) -> bool: + return self.task_type == TaskType.MULTICLASS + + @property + def is_regression(self) -> bool: + return self.task_type == TaskType.REGRESSION + + @property + def n_num_features(self) -> int: + return 0 if self.X_num is None else self.X_num['train'].shape[1] + + @property + def n_cat_features(self) -> int: + return 0 if self.X_cat is None else self.X_cat['train'].shape[1] + + @property + def n_features(self) -> int: + return self.n_num_features + self.n_cat_features + + def size(self, part: Optional[str]) -> int: + return sum(map(len, self.y.values())) if part is None else len(self.y[part]) + + @property + def nn_output_dim(self) -> int: + if self.is_multiclass: + assert self.n_classes is not None + return self.n_classes + else: + return 1 + + def get_category_sizes(self, part: str) -> List[int]: + return [] if self.X_cat is None else get_category_sizes(self.X_cat[part]) + + def calculate_metrics( + self, + predictions: Dict[str, np.ndarray], + prediction_type: Optional[str], + ) -> Dict[str, Any]: + metrics = { + x: calculate_metrics_( + self.y[x], predictions[x], self.task_type, prediction_type, self.y_info + ) + for x in predictions + } + if self.task_type == TaskType.REGRESSION: + score_key = 'rmse' + score_sign = -1 + else: + score_key = 'accuracy' + score_sign = 1 + for part_metrics in metrics.values(): + part_metrics['score'] = score_sign * part_metrics[score_key] + return metrics + +def change_val(dataset: Dataset, val_size: float = 0.2): + # should be done before transformations + + y = np.concatenate([dataset.y['train'], dataset.y['val']], axis=0) + + ixs = np.arange(y.shape[0]) + if dataset.is_regression: + train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777) + else: + train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777, stratify=y) + + dataset.y['train'] = y[train_ixs] + dataset.y['val'] = y[val_ixs] + + if dataset.X_num is not None: + X_num = np.concatenate([dataset.X_num['train'], dataset.X_num['val']], axis=0) + dataset.X_num['train'] = X_num[train_ixs] + dataset.X_num['val'] = X_num[val_ixs] + + if dataset.X_cat is not None: + X_cat = np.concatenate([dataset.X_cat['train'], dataset.X_cat['val']], axis=0) + dataset.X_cat['train'] = X_cat[train_ixs] + dataset.X_cat['val'] = X_cat[val_ixs] + + return dataset + +def num_process_nans(dataset: Dataset, policy: Optional[NumNanPolicy]) -> Dataset: + + assert dataset.X_num is not None + nan_masks = {k: np.isnan(v) for k, v in dataset.X_num.items()} + if not any(x.any() for x in nan_masks.values()): # type: ignore[code] + # assert policy is None + print('No NaNs in numerical features, skipping') + return dataset + + assert policy is not None + if policy == 'drop-rows': + valid_masks = {k: ~v.any(1) for k, v in nan_masks.items()} + assert valid_masks[ + 'test' + ].all(), 'Cannot drop test rows, since this will affect the final metrics.' + new_data = {} + for data_name in ['X_num', 'X_cat', 'y']: + data_dict = getattr(dataset, data_name) + if data_dict is not None: + new_data[data_name] = { + k: v[valid_masks[k]] for k, v in data_dict.items() + } + dataset = replace(dataset, **new_data) + elif policy == 'mean': + new_values = np.nanmean(dataset.X_num['train'], axis=0) + X_num = deepcopy(dataset.X_num) + for k, v in X_num.items(): + num_nan_indices = np.where(nan_masks[k]) + v[num_nan_indices] = np.take(new_values, num_nan_indices[1]) + dataset = replace(dataset, X_num=X_num) + else: + assert util.raise_unknown('policy', policy) + return dataset + + +# Inspired by: https://github.com/yandex-research/rtdl/blob/a4c93a32b334ef55d2a0559a4407c8306ffeeaee/lib/data.py#L20 +def normalize( + X: ArrayDict, normalization: Normalization, seed: Optional[int], return_normalizer : bool = False +) -> ArrayDict: + X_train = X['train'] + if normalization == 'standard': + normalizer = sklearn.preprocessing.StandardScaler() + elif normalization == 'minmax': + normalizer = sklearn.preprocessing.MinMaxScaler() + elif normalization == 'quantile': + normalizer = sklearn.preprocessing.QuantileTransformer( + output_distribution='normal', + n_quantiles=max(min(X['train'].shape[0] // 30, 1000), 10), + subsample=int(1e9), + random_state=seed, + ) + # noise = 1e-3 + # if noise > 0: + # assert seed is not None + # stds = np.std(X_train, axis=0, keepdims=True) + # noise_std = noise / np.maximum(stds, noise) # type: ignore[code] + # X_train = X_train + noise_std * np.random.default_rng(seed).standard_normal( + # X_train.shape + # ) + else: + util.raise_unknown('normalization', normalization) + + normalizer.fit(X_train) + if return_normalizer: + return {k: normalizer.transform(v) for k, v in X.items()}, normalizer + return {k: normalizer.transform(v) for k, v in X.items()} + +class dequantizer: + def __init__( + self, + dequant_dist: DEQUANT_DIST, + int_col_idx_wrt_num: list, + int_dequant_factor: float, + # return_dequantizer: bool = False + ): + self.dequant_dist = dequant_dist + self.int_col_idx_wrt_num = int_col_idx_wrt_num + self.int_dequant_factor = int_dequant_factor + def transform(self, X): + X_int = X[:, self.int_col_idx_wrt_num] + if self.dequant_dist == 'uniform': + X[:, self.int_col_idx_wrt_num] = X_int+ np.random.uniform(size=X_int.shape) * self.int_dequant_factor + elif self.dequant_dist == 'beta': + 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 + elif self.dequant_dist in ['round', 'none']: + pass + return X + def inverse_transform(self, X): + X_int = X[:, self.int_col_idx_wrt_num] + if self.dequant_dist == 'uniform': + X[:, self.int_col_idx_wrt_num] = np.floor(X_int) + elif self.dequant_dist == 'beta': + X[:, self.int_col_idx_wrt_num] = np.rint(X_int) + elif self.dequant_dist == 'round': + X[:, self.int_col_idx_wrt_num] = np.rint(X_int) + elif self.dequant_dist == 'none': + pass + return X + + + # if return_dequantizer: + # return {k: transform(v) for k, v in X.items()}, inverse_transform + # return {k: transform(v) for k, v in X.items()} + +def cat_process_nans(X: ArrayDict, policy: Optional[CatNanPolicy]) -> ArrayDict: + assert X is not None + nan_masks = {k: v == CAT_MISSING_VALUE for k, v in X.items()} + if any(x.any() for x in nan_masks.values()): # type: ignore[code] + if policy is None: + X_new = X + elif policy == 'most_frequent': + imputer = SimpleImputer(missing_values=CAT_MISSING_VALUE, strategy=policy) # type: ignore[code] + imputer.fit(X['train']) + X_new = {k: cast(np.ndarray, imputer.transform(v)) for k, v in X.items()} + else: + util.raise_unknown('categorical NaN policy', policy) + else: + assert policy is None + X_new = X + return X_new + + +def cat_drop_rare(X: ArrayDict, min_frequency: float) -> ArrayDict: + assert 0.0 < min_frequency < 1.0 + min_count = round(len(X['train']) * min_frequency) + X_new = {x: [] for x in X} + for column_idx in range(X['train'].shape[1]): + counter = Counter(X['train'][:, column_idx].tolist()) + popular_categories = {k for k, v in counter.items() if v >= min_count} + for part in X_new: + X_new[part].append( + [ + (x if x in popular_categories else CAT_RARE_VALUE) + for x in X[part][:, column_idx].tolist() + ] + ) + return {k: np.array(v).T for k, v in X_new.items()} + + +def cat_encode( + X: ArrayDict, + encoding: Optional[CatEncoding], + y_train: Optional[np.ndarray], + seed: Optional[int], + return_encoder : bool = False +) -> Tuple[ArrayDict, bool, Optional[Any]]: # (X, is_converted_to_numerical) + if encoding != 'counter': + y_train = None + + # Step 1. Map strings to 0-based ranges + + if encoding is None: + unknown_value = np.iinfo('int64').max - 3 + oe = sklearn.preprocessing.OrdinalEncoder( + handle_unknown='use_encoded_value', # type: ignore[code] + unknown_value=unknown_value, # type: ignore[code] + dtype='int64', # type: ignore[code] + ).fit(X['train']) + encoder = make_pipeline(oe) + encoder.fit(X['train']) + X = {k: encoder.transform(v) for k, v in X.items()} + max_values = X['train'].max(axis=0) + for part in X.keys(): + if part == 'train': continue + for column_idx in range(X[part].shape[1]): + X[part][X[part][:, column_idx] == unknown_value, column_idx] = ( + max_values[column_idx] + 1 + ) + if return_encoder: + return (X, False, encoder) + return (X, False) + + # Step 2. Encode. + + elif encoding == 'one-hot': + ohe = sklearn.preprocessing.OneHotEncoder( + handle_unknown='ignore', sparse_output=False, dtype=np.float32 # type: ignore[code] + ) + encoder = make_pipeline(ohe) + + # encoder.steps.append(('ohe', ohe)) + encoder.fit(X['train']) + X = {k: encoder.transform(v) for k, v in X.items()} + + elif encoding == 'counter': + assert y_train is not None + assert seed is not None + loe = LeaveOneOutEncoder(sigma=0.1, random_state=seed, return_df=False) + encoder.steps.append(('loe', loe)) + encoder.fit(X['train'], y_train) + X = {k: encoder.transform(v).astype('float32') for k, v in X.items()} # type: ignore[code] + if not isinstance(X['train'], pd.DataFrame): + X = {k: v.values for k, v in X.items()} # type: ignore[code] + else: + util.raise_unknown('encoding', encoding) + + if return_encoder: + return X, True, encoder # type: ignore[code] + return (X, True) + + +def build_target( + y: ArrayDict, policy: Optional[YPolicy], task_type: TaskType +) -> Tuple[ArrayDict, Dict[str, Any]]: + info: Dict[str, Any] = {'policy': policy} + if policy is None: + pass + elif policy == 'default': + if task_type == TaskType.REGRESSION: + mean, std = float(y['train'].mean()), float(y['train'].std()) + y = {k: (v - mean) / std for k, v in y.items()} + info['mean'] = mean + info['std'] = std + else: + util.raise_unknown('policy', policy) + return y, info + + +@dataclass(frozen=True) +class Transformations: + seed: int = 0 + normalization: Optional[Normalization] = None + num_nan_policy: Optional[NumNanPolicy] = None + cat_nan_policy: Optional[CatNanPolicy] = None + cat_min_frequency: Optional[float] = None + cat_encoding: Optional[CatEncoding] = None + y_policy: Optional[YPolicy] = 'default' + dequant_dist: Optional[DEQUANT_DIST] = None + int_dequant_factor: Optional[float] = 0.0 + + +def transform_dataset( + dataset: Dataset, + transformations: Transformations, + cache_dir: Optional[Path], + return_transforms: bool = False +) -> Dataset: + # WARNING: the order of transformations matters. Moreover, the current + # implementation is not ideal in that sense. + if cache_dir is not None: + transformations_md5 = hashlib.md5( + str(transformations).encode('utf-8') + ).hexdigest() + transformations_str = '__'.join(map(str, astuple(transformations))) + cache_path = ( + cache_dir / f'cache__{transformations_str}__{transformations_md5}.pickle' + ) + if cache_path.exists(): + cache_transformations, value = util.load_pickle(cache_path) + if transformations == cache_transformations: + print( + f"Using cached features: {cache_dir.name + '/' + cache_path.name}" + ) + return value + else: + raise RuntimeError(f'Hash collision for {cache_path}') + else: + cache_path = None + + if dataset.X_num is not None: + dataset = num_process_nans(dataset, transformations.num_nan_policy) + + num_transform = None + int_transform = None + cat_transform = None + X_num = dataset.X_num + + int_col_idx_wrt_num = dataset.int_col_idx_wrt_num + if X_num is not None and int_col_idx_wrt_num and transformations.dequant_dist is not None: + int_transform = dequantizer( + transformations.dequant_dist, + int_col_idx_wrt_num, + transformations.int_dequant_factor, + ) + X_num = {k: int_transform.transform(v) for k, v in X_num.items()} + + if X_num is not None and transformations.normalization is not None: + has_num = all([x.shape[1]>0 for x in dataset.X_num.values()]) + if has_num: + X_num, num_transform = normalize( + X_num, + transformations.normalization, + transformations.seed, + return_normalizer=True + ) + num_transform = num_transform + + if dataset.X_cat is None: + assert transformations.cat_nan_policy is None + assert transformations.cat_min_frequency is None + # assert transformations.cat_encoding is None + X_cat = None + else: + has_cat = all([x.shape[1]>0 for x in dataset.X_cat.values()]) + if not has_cat: + assert transformations.cat_nan_policy is None + assert transformations.cat_min_frequency is None + X_cat = dataset.X_cat + for split in X_cat.keys(): # a patch to make sure that the empty array is transformed into int dtype + X_cat[split] = X_cat[split].astype(np.int64) + else: + X_cat = cat_process_nans(dataset.X_cat, transformations.cat_nan_policy) + + if transformations.cat_min_frequency is not None: + X_cat = cat_drop_rare(X_cat, transformations.cat_min_frequency) + X_cat, is_num, cat_transform = cat_encode( + X_cat, + transformations.cat_encoding, + dataset.y['train'], + transformations.seed, + return_encoder=True + ) + + if is_num: + X_num = ( + X_cat + if X_num is None + else {x: np.hstack([X_num[x], X_cat[x]]) for x in X_num} + ) + X_cat = None + + + y, y_info = build_target(dataset.y, transformations.y_policy, dataset.task_type) + + dataset = replace(dataset, X_num=X_num, X_cat=X_cat, y=y, y_info=y_info) + dataset.num_transform = num_transform + dataset.int_transform = int_transform + dataset.cat_transform = cat_transform + + if cache_path is not None: + util.dump_pickle((transformations, dataset), cache_path) + # if return_transforms: + # return dataset, num_transform, cat_transform + return dataset + + +def build_dataset( + path: Union[str, Path], + transformations: Transformations, + cache: bool +) -> Dataset: + path = Path(path) + dataset = Dataset.from_dir(path) + return transform_dataset(dataset, transformations, path if cache else None) + + +def prepare_tensors( + dataset: Dataset, device: Union[str, torch.device] +) -> Tuple[Optional[TensorDict], Optional[TensorDict], TensorDict]: + X_num, X_cat, Y = ( + None if x is None else {k: torch.as_tensor(v) for k, v in x.items()} + for x in [dataset.X_num, dataset.X_cat, dataset.y] + ) + if device.type != 'cpu': + X_num, X_cat, Y = ( + None if x is None else {k: v.to(device) for k, v in x.items()} + for x in [X_num, X_cat, Y] + ) + assert X_num is not None + assert Y is not None + if not dataset.is_multiclass: + Y = {k: v.float() for k, v in Y.items()} + return X_num, X_cat, Y + +############### +## DataLoader## +############### + +class TabDataset(torch.utils.data.Dataset): + def __init__( + self, dataset : Dataset, split : Literal['train', 'val', 'test'] + ): + super().__init__() + + self.X_num = torch.from_numpy(dataset.X_num[split]) if dataset.X_num is not None else None + self.X_cat = torch.from_numpy(dataset.X_cat[split]) if dataset.X_cat is not None else None + self.y = torch.from_numpy(dataset.y[split]) + + assert self.y is not None + assert self.X_num is not None or self.X_cat is not None + + def __len__(self): + return len(self.y) + + def __getitem__(self, idx): + out_dict = { + 'y': self.y[idx].long() if self.y is not None else None, + } + + x = np.empty((0,)) + if self.X_num is not None: + x = self.X_num[idx] + if self.X_cat is not None: + x = torch.cat([x, self.X_cat[idx]], dim=0) + return x.float(), out_dict + +def prepare_dataloader( + dataset : Dataset, + split : str, + batch_size: int, +): + + torch_dataset = TabDataset(dataset, split) + loader = torch.utils.data.DataLoader( + torch_dataset, + batch_size=batch_size, + shuffle=(split == 'train'), + num_workers=1, + ) + while True: + yield from loader + +def prepare_torch_dataloader( + dataset : Dataset, + split : str, + shuffle : bool, + batch_size: int, +) -> torch.utils.data.DataLoader: + + torch_dataset = TabDataset(dataset, split) + loader = torch.utils.data.DataLoader(torch_dataset, batch_size=batch_size, shuffle=shuffle, num_workers=1) + + return loader + +def dataset_from_csv(paths : Dict[str, str], cat_features, target, T): + assert 'train' in paths + y = {} + X_num = {} + X_cat = {} if len(cat_features) else None + for split in paths.keys(): + df = pd.read_csv(paths[split]) + y[split] = df[target].to_numpy().astype(float) + if X_cat is not None: + X_cat[split] = df[cat_features].to_numpy().astype(str) + X_num[split] = df.drop(cat_features + [target], axis=1).to_numpy().astype(float) + + dataset = Dataset(X_num, X_cat, y, {}, None, len(np.unique(y['train']))) + return transform_dataset(dataset, T, None) + +class FastTensorDataLoader: + """ + A DataLoader-like object for a set of tensors that can be much faster than + TensorDataset + DataLoader because dataloader grabs individual indices of + the dataset and calls cat (slow). + Source: https://discuss.pytorch.org/t/dataloader-much-slower-than-manual-batching/27014/6 + """ + def __init__(self, *tensors, batch_size=32, shuffle=False): + """ + Initialize a FastTensorDataLoader. + :param *tensors: tensors to store. Must have the same length @ dim 0. + :param batch_size: batch size to load. + :param shuffle: if True, shuffle the data *in-place* whenever an + iterator is created out of this object. + :returns: A FastTensorDataLoader. + """ + assert all(t.shape[0] == tensors[0].shape[0] for t in tensors) + self.tensors = tensors + + self.dataset_len = self.tensors[0].shape[0] + self.batch_size = batch_size + self.shuffle = shuffle + + # Calculate # batches + n_batches, remainder = divmod(self.dataset_len, self.batch_size) + if remainder > 0: + n_batches += 1 + self.n_batches = n_batches + def __iter__(self): + if self.shuffle: + r = torch.randperm(self.dataset_len) + self.tensors = [t[r] for t in self.tensors] + self.i = 0 + return self + + def __next__(self): + if self.i >= self.dataset_len: + raise StopIteration + batch = tuple(t[self.i:self.i+self.batch_size] for t in self.tensors) + self.i += self.batch_size + return batch + + def __len__(self): + return self.n_batches + +def prepare_fast_dataloader( + D : Dataset, + split : str, + batch_size: int +): + + X = torch.from_numpy(np.concatenate([D.X_num[split], D.X_cat[split]], axis=1)).float() + dataloader = FastTensorDataLoader(X, batch_size=batch_size, shuffle=(split=='train')) + while True: + yield from dataloader + +def prepare_fast_torch_dataloader( + D : Dataset, + split : str, + batch_size: int +): + if D.X_cat is not None: + X = torch.from_numpy(np.concatenate([D.X_num[split], D.X_cat[split]], axis=1)).float() + else: + X = torch.from_numpy(D.X_num[split]).float() + y = torch.from_numpy(D.y[split]) + dataloader = FastTensorDataLoader(X, y, batch_size=batch_size, shuffle=(split=='train')) + return dataloader + +def round_columns(X_real, X_synth, columns): + for col in columns: + uniq = np.unique(X_real[:,col]) + dist = cdist(X_synth[:, col][:, np.newaxis].astype(float), uniq[:, np.newaxis].astype(float)) + X_synth[:, col] = uniq[dist.argmin(axis=1)] + return X_synth + +def concat_features(D : Dataset): + if D.X_num is None: + assert D.X_cat is not None + X = {k: pd.DataFrame(v, columns=range(D.n_features)) for k, v in D.X_cat.items()} + elif D.X_cat is None: + assert D.X_num is not None + X = {k: pd.DataFrame(v, columns=range(D.n_features)) for k, v in D.X_num.items()} + else: + X = { + part: pd.concat( + [ + pd.DataFrame(D.X_num[part], columns=range(D.n_num_features)), + pd.DataFrame( + D.X_cat[part], + columns=range(D.n_num_features, D.n_features), + ), + ], + axis=1, + ) + for part in D.y.keys() + } + + return X + +def concat_to_pd(X_num, X_cat, y): + if X_num is None: + return pd.concat([ + pd.DataFrame(X_cat, columns=list(range(X_cat.shape[1]))), + pd.DataFrame(y, columns=['y']) + ], axis=1) + if X_cat is not None: + return pd.concat([ + pd.DataFrame(X_num, columns=list(range(X_num.shape[1]))), + pd.DataFrame(X_cat, columns=list(range(X_num.shape[1], X_num.shape[1] + X_cat.shape[1]))), + pd.DataFrame(y, columns=['y']) + ], axis=1) + return pd.concat([ + pd.DataFrame(X_num, columns=list(range(X_num.shape[1]))), + pd.DataFrame(y, columns=['y']) + ], axis=1) + +def read_pure_data(path, split='train'): + y = np.load(os.path.join(path, f'y_{split}.npy'), allow_pickle=True) + X_num = None + X_cat = None + if os.path.exists(os.path.join(path, f'X_num_{split}.npy')): + X_num = np.load(os.path.join(path, f'X_num_{split}.npy'), allow_pickle=True) + if os.path.exists(os.path.join(path, f'X_cat_{split}.npy')): + X_cat = np.load(os.path.join(path, f'X_cat_{split}.npy'), allow_pickle=True) + + return X_num, X_cat, y + +def read_changed_val(path, val_size=0.2): + path = Path(path) + X_num_train, X_cat_train, y_train = read_pure_data(path, 'train') + X_num_val, X_cat_val, y_val = read_pure_data(path, 'val') + is_regression = load_json(path / 'info.json')['task_type'] == 'regression' + + y = np.concatenate([y_train, y_val], axis=0) + + ixs = np.arange(y.shape[0]) + if is_regression: + train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777) + else: + train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777, stratify=y) + y_train = y[train_ixs] + y_val = y[val_ixs] + + if X_num_train is not None: + X_num = np.concatenate([X_num_train, X_num_val], axis=0) + X_num_train = X_num[train_ixs] + X_num_val = X_num[val_ixs] + + if X_cat_train is not None: + X_cat = np.concatenate([X_cat_train, X_cat_val], axis=0) + X_cat_train = X_cat[train_ixs] + X_cat_val = X_cat[val_ixs] + + return X_num_train, X_cat_train, y_train, X_num_val, X_cat_val, y_val + +############# + +def load_dataset_info(dataset_dir_name: str) -> Dict[str, Any]: + path = Path("data/" + dataset_dir_name) + info = util.load_json(path / 'info.json') + info['size'] = info['train_size'] + info['val_size'] + info['test_size'] + info['n_features'] = info['n_num_features'] + info['n_cat_features'] + info['path'] = path + return info \ No newline at end of file diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/src/env.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/src/env.py new file mode 100644 index 0000000000000000000000000000000000000000..0b9dd619f31450414a9b31585aa58b9121834fbe --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/src/env.py @@ -0,0 +1,39 @@ +""" +Have not used in TabDDPM project. +""" + +import datetime +import os +import shutil +import typing as ty +from pathlib import Path + +PROJ = Path('tab-ddpm/').absolute().resolve() +EXP = PROJ / 'exp' +DATA = PROJ / 'data' + + +def get_path(path: ty.Union[str, Path]) -> Path: + if isinstance(path, str): + path = Path(path) + if not path.is_absolute(): + path = PROJ / path + return path.resolve() + + +def get_relative_path(path: ty.Union[str, Path]) -> Path: + return get_path(path).relative_to(PROJ) + + +def duplicate_path( + src: ty.Union[str, Path], alternative_project_dir: ty.Union[str, Path] +) -> None: + src = get_path(src) + alternative_project_dir = get_path(alternative_project_dir) + dst = alternative_project_dir / src.relative_to(PROJ) + dst.parent.mkdir(parents=True, exist_ok=True) + if dst.exists(): + dst = dst.with_name( + dst.name + '_' + datetime.datetime.now().strftime('%Y%m%dT%H%M%S') + ) + (shutil.copytree if src.is_dir() else shutil.copyfile)(src, dst) \ No newline at end of file diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/src/metrics.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/src/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..188a9be3f8e9d59b07688aa189a876660dbef7cd --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/src/metrics.py @@ -0,0 +1,157 @@ +import enum +from typing import Any, Optional, Tuple, Dict, Union, cast +from functools import partial + +import numpy as np +import scipy.special +import sklearn.metrics as skm + +from . import util +from .util import TaskType + + +class PredictionType(enum.Enum): + LOGITS = 'logits' + PROBS = 'probs' + +class MetricsReport: + def __init__(self, report: dict, task_type: TaskType): + self._res = {k: {} for k in report.keys()} + if task_type in (TaskType.BINCLASS, TaskType.MULTICLASS): + self._metrics_names = ["acc", "f1"] + for k in report.keys(): + self._res[k]["acc"] = report[k]["accuracy"] + self._res[k]["f1"] = report[k]["macro avg"]["f1-score"] + if task_type == TaskType.BINCLASS: + self._res[k]["roc_auc"] = report[k]["roc_auc"] + self._metrics_names.append("roc_auc") + + elif task_type == TaskType.REGRESSION: + self._metrics_names = ["r2", "rmse"] + for k in report.keys(): + self._res[k]["r2"] = report[k]["r2"] + self._res[k]["rmse"] = report[k]["rmse"] + else: + raise "Unknown TaskType!" + + def get_splits_names(self) -> list[str]: + return self._res.keys() + + def get_metrics_names(self) -> list[str]: + return self._metrics_names + + def get_metric(self, split: str, metric: str) -> float: + return self._res[split][metric] + + def get_val_score(self) -> float: + return self._res["val"]["r2"] if "r2" in self._res["val"] else self._res["val"]["f1"] + + def get_test_score(self) -> float: + return self._res["test"]["r2"] if "r2" in self._res["test"] else self._res["test"]["f1"] + + def print_metrics(self) -> None: + res = { + "val": {k: np.around(self._res["val"][k], 4) for k in self._res["val"]}, + "test": {k: np.around(self._res["test"][k], 4) for k in self._res["test"]} + } + + print("*"*100) + print("[val]") + print(res["val"]) + print("[test]") + print(res["test"]) + + return res + +class SeedsMetricsReport: + def __init__(self): + self._reports = [] + + def add_report(self, report: MetricsReport) -> None: + self._reports.append(report) + + def get_mean_std(self) -> dict: + res = {k: {} for k in ["train", "val", "test"]} + for split in self._reports[0].get_splits_names(): + for metric in self._reports[0].get_metrics_names(): + res[split][metric] = [x.get_metric(split, metric) for x in self._reports] + + agg_res = {k: {} for k in ["train", "val", "test"]} + for split in self._reports[0].get_splits_names(): + for metric in self._reports[0].get_metrics_names(): + for k, f in [("count", len), ("mean", np.mean), ("std", np.std)]: + agg_res[split][f"{metric}-{k}"] = f(res[split][metric]) + self._res = res + self._agg_res = agg_res + + return agg_res + + def print_result(self) -> dict: + res = {split: {k: float(np.around(self._agg_res[split][k], 4)) for k in self._agg_res[split]} for split in ["val", "test"]} + print("="*100) + print("EVAL RESULTS:") + print("[val]") + print(res["val"]) + print("[test]") + print(res["test"]) + print("="*100) + return res + +def calculate_rmse( + y_true: np.ndarray, y_pred: np.ndarray, std = None) -> float: + rmse = skm.mean_squared_error(y_true, y_pred) ** 0.5 + if std is not None: + rmse *= std + return rmse + + +def _get_labels_and_probs( + y_pred: np.ndarray, task_type: TaskType, prediction_type: Optional[PredictionType] +) -> Tuple[np.ndarray, Optional[np.ndarray]]: + assert task_type in (TaskType.BINCLASS, TaskType.MULTICLASS) + + if prediction_type is None: + return y_pred, None + + if prediction_type == PredictionType.LOGITS: + probs = ( + scipy.special.expit(y_pred) + if task_type == TaskType.BINCLASS + else scipy.special.softmax(y_pred, axis=1) + ) + elif prediction_type == PredictionType.PROBS: + probs = y_pred + else: + util.raise_unknown('prediction_type', prediction_type) + + assert probs is not None + labels = np.round(probs) if task_type == TaskType.BINCLASS else probs.argmax(axis=1) + return labels.astype('int64'), probs + + +def calculate_metrics( + y_true: np.ndarray, + y_pred: np.ndarray, + task_type: Union[str, TaskType], + prediction_type: Optional[Union[str, PredictionType]], + y_info: Dict[str, Any], +) -> Dict[str, Any]: + # Example: calculate_metrics(y_true, y_pred, 'binclass', 'logits', {}) + task_type = TaskType(task_type) + if prediction_type is not None: + prediction_type = PredictionType(prediction_type) + + if task_type == TaskType.REGRESSION: + assert prediction_type is None + assert 'std' in y_info + rmse = calculate_rmse(y_true, y_pred, y_info['std']) + r2 = skm.r2_score(y_true, y_pred) + result = {'rmse': rmse, 'r2': r2} + else: + labels, probs = _get_labels_and_probs(y_pred, task_type, prediction_type) + result = cast( + Dict[str, Any], skm.classification_report(y_true, labels, output_dict=True) + ) + if task_type == TaskType.BINCLASS: + result['roc_auc'] = skm.roc_auc_score(y_true, probs) + return result \ No newline at end of file diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/src/util.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/src/util.py new file mode 100644 index 0000000000000000000000000000000000000000..e105c961803b3bf0f8282e673eed8e84eaaa3891 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/src/util.py @@ -0,0 +1,347 @@ +import argparse +import atexit +import enum +import json +import os +import pickle +import shutil +import sys +import time +import uuid +from copy import deepcopy +from dataclasses import asdict, fields, is_dataclass +from pathlib import Path +from pprint import pprint +from typing import Any, Callable, List, Dict, Type, Optional, Tuple, TypeVar, Union, cast, get_args, get_origin + +import __main__ +import numpy as np +import tomli +import tomli_w +import torch +import typing as ty + +from . import env + +RawConfig = Dict[str, Any] +Report = Dict[str, Any] +T = TypeVar('T') + + +class Part(enum.Enum): + TRAIN = 'train' + VAL = 'val' + TEST = 'test' + + def __str__(self) -> str: + return self.value + + +class TaskType(enum.Enum): + BINCLASS = 'binclass' + MULTICLASS = 'multiclass' + REGRESSION = 'regression' + + def __str__(self) -> str: + return self.value + + + +def update_training_log(training_log, data, metrics): + def _update(log_part, data_part): + for k, v in data_part.items(): + if isinstance(v, dict): + _update(log_part.setdefault(k, {}), v) + elif isinstance(v, list): + log_part.setdefault(k, []).extend(v) + else: + log_part.setdefault(k, []).append(v) + + _update(training_log, data) + transposed_metrics = {} + for part, part_metrics in metrics.items(): + for metric_name, value in part_metrics.items(): + transposed_metrics.setdefault(metric_name, {})[part] = value + _update(training_log, transposed_metrics) + + +def raise_unknown(unknown_what: str, unknown_value: Any): + raise ValueError(f'Unknown {unknown_what}: {unknown_value}') + + +def _replace(data, condition, value): + def do(x): + if isinstance(x, dict): + return {k: do(v) for k, v in x.items()} + elif isinstance(x, list): + return [do(y) for y in x] + else: + return value if condition(x) else x + + return do(data) + + +_CONFIG_NONE = '__none__' + + +def unpack_config(config: RawConfig) -> RawConfig: + config = cast(RawConfig, _replace(config, lambda x: x == _CONFIG_NONE, None)) + return config + + +def pack_config(config: RawConfig) -> RawConfig: + config = cast(RawConfig, _replace(config, lambda x: x is None, _CONFIG_NONE)) + return config + + +def load_config(path: Union[Path, str]) -> Any: + with open(path, 'rb') as f: + return unpack_config(tomli.load(f)) + + +def dump_config(config: Any, path: Union[Path, str]) -> None: + with open(path, 'wb') as f: + tomli_w.dump(pack_config(config), f) + # check that there are no bugs in all these "pack/unpack" things + assert config == load_config(path) + + +def load_json(path: Union[Path, str], **kwargs) -> Any: + return json.loads(Path(path).read_text(), **kwargs) + + +def dump_json(x: Any, path: Union[Path, str], **kwargs) -> None: + kwargs.setdefault('indent', 4) + Path(path).write_text(json.dumps(x, **kwargs) + '\n') + + +def load_pickle(path: Union[Path, str], **kwargs) -> Any: + return pickle.loads(Path(path).read_bytes(), **kwargs) + + +def dump_pickle(x: Any, path: Union[Path, str], **kwargs) -> None: + Path(path).write_bytes(pickle.dumps(x, **kwargs)) + + +def load(path: Union[Path, str], **kwargs) -> Any: + return globals()[f'load_{Path(path).suffix[1:]}'](Path(path), **kwargs) + + +def dump(x: Any, path: Union[Path, str], **kwargs) -> Any: + return globals()[f'dump_{Path(path).suffix[1:]}'](x, Path(path), **kwargs) + + +def _get_output_item_path( + path: Union[str, Path], filename: str, must_exist: bool +) -> Path: + path = env.get_path(path) + if path.suffix == '.toml': + path = path.with_suffix('') + if path.is_dir(): + path = path / filename + else: + assert path.name == filename + assert path.parent.exists() + if must_exist: + assert path.exists() + return path + + +def load_report(path: Path) -> Report: + return load_json(_get_output_item_path(path, 'report.json', True)) + + +def dump_report(report: dict, path: Path) -> None: + dump_json(report, _get_output_item_path(path, 'report.json', False)) + + +def load_predictions(path: Path) -> Dict[str, np.ndarray]: + with np.load(_get_output_item_path(path, 'predictions.npz', True)) as predictions: + return {x: predictions[x] for x in predictions} + + +def dump_predictions(predictions: Dict[str, np.ndarray], path: Path) -> None: + np.savez(_get_output_item_path(path, 'predictions.npz', False), **predictions) + + +def dump_metrics(metrics: Dict[str, Any], path: Path) -> None: + dump_json(metrics, _get_output_item_path(path, 'metrics.json', False)) + + +def load_checkpoint(path: Path, *args, **kwargs) -> Dict[str, np.ndarray]: + return torch.load( + _get_output_item_path(path, 'checkpoint.pt', True), *args, **kwargs + ) + + +def get_device() -> torch.device: + if torch.cuda.is_available(): + assert os.environ.get('CUDA_VISIBLE_DEVICES') is not None + return torch.device('cuda:0') + else: + return torch.device('cpu') + + +def _print_sep(c, size=100): + print(c * size) + + +_LAST_SNAPSHOT_TIME = None + + +def backup_output(output_dir: Path) -> None: + backup_dir = os.environ.get('TMP_OUTPUT_PATH') + snapshot_dir = os.environ.get('SNAPSHOT_PATH') + if backup_dir is None: + assert snapshot_dir is None + return + assert snapshot_dir is not None + + try: + relative_output_dir = output_dir.relative_to(env.PROJ) + except ValueError: + return + + for dir_ in [backup_dir, snapshot_dir]: + new_output_dir = dir_ / relative_output_dir + prev_backup_output_dir = new_output_dir.with_name(new_output_dir.name + '_prev') + new_output_dir.parent.mkdir(exist_ok=True, parents=True) + if new_output_dir.exists(): + new_output_dir.rename(prev_backup_output_dir) + shutil.copytree(output_dir, new_output_dir) + # the case for evaluate.py which automatically creates configs + if output_dir.with_suffix('.toml').exists(): + shutil.copyfile( + output_dir.with_suffix('.toml'), new_output_dir.with_suffix('.toml') + ) + if prev_backup_output_dir.exists(): + shutil.rmtree(prev_backup_output_dir) + + global _LAST_SNAPSHOT_TIME + if _LAST_SNAPSHOT_TIME is None or time.time() - _LAST_SNAPSHOT_TIME > 10 * 60: + import nirvana_dl.snapshot # type: ignore[code] + + nirvana_dl.snapshot.dump_snapshot() + _LAST_SNAPSHOT_TIME = time.time() + print('The snapshot was saved!') + + +def _get_scores(metrics: Dict[str, Dict[str, Any]]) -> Optional[Dict[str, float]]: + return ( + {k: v['score'] for k, v in metrics.items()} + if 'score' in next(iter(metrics.values())) + else None + ) + + +def format_scores(metrics: Dict[str, Dict[str, Any]]) -> str: + return ' '.join( + f"[{x}] {metrics[x]['score']:.3f}" + for x in ['test', 'val', 'train'] + if x in metrics + ) + + +def finish(output_dir: Path, report: dict) -> None: + print() + _print_sep('=') + + metrics = report.get('metrics') + if metrics is not None: + scores = _get_scores(metrics) + if scores is not None: + dump_json(scores, output_dir / 'scores.json') + print(format_scores(metrics)) + _print_sep('-') + + dump_report(report, output_dir) + json_output_path = os.environ.get('JSON_OUTPUT_FILE') + if json_output_path: + try: + key = str(output_dir.relative_to(env.PROJ)) + except ValueError: + pass + else: + json_output_path = Path(json_output_path) + try: + json_data = json.loads(json_output_path.read_text()) + except (FileNotFoundError, json.decoder.JSONDecodeError): + json_data = {} + json_data[key] = load_json(output_dir / 'report.json') + json_output_path.write_text(json.dumps(json_data, indent=4)) + shutil.copyfile( + json_output_path, + os.path.join(os.environ['SNAPSHOT_PATH'], 'json_output.json'), + ) + + output_dir.joinpath('DONE').touch() + backup_output(output_dir) + print(f'Done! | {report.get("time")} | {output_dir}') + _print_sep('=') + print() + + +def from_dict(datacls: Type[T], data: dict) -> T: + assert is_dataclass(datacls) + data = deepcopy(data) + for field in fields(datacls): + if field.name not in data: + continue + if is_dataclass(field.type): + data[field.name] = from_dict(field.type, data[field.name]) + elif ( + get_origin(field.type) is Union + and len(get_args(field.type)) == 2 + and get_args(field.type)[1] is type(None) + and is_dataclass(get_args(field.type)[0]) + ): + if data[field.name] is not None: + data[field.name] = from_dict(get_args(field.type)[0], data[field.name]) + return datacls(**data) + + +def replace_factor_with_value( + config: RawConfig, + key: str, + reference_value: int, + bounds: Tuple[float, float], +) -> None: + factor_key = key + '_factor' + if factor_key not in config: + assert key in config + else: + assert key not in config + factor = config.pop(factor_key) + assert bounds[0] <= factor <= bounds[1] + config[key] = int(factor * reference_value) + + +def get_temporary_copy(path: Union[str, Path]) -> Path: + path = env.get_path(path) + assert not path.is_dir() and not path.is_symlink() + tmp_path = path.with_name( + path.stem + '___' + str(uuid.uuid4()).replace('-', '') + path.suffix + ) + shutil.copyfile(path, tmp_path) + atexit.register(lambda: tmp_path.unlink()) + return tmp_path + + +def get_python(): + python = Path('python3.9') + return str(python) if python.exists() else 'python' + +def get_catboost_config(real_data_path, is_cv=False): + ds_name = Path(real_data_path).name + C = load_json(f'tuned_models/catboost/{ds_name}_cv.json') + return C + +def get_categories(X_train_cat): + return ( + None + if X_train_cat is None + else [ + len(set(X_train_cat[:, i])) + for i in range(X_train_cat.shape[1]) + ] + ) \ No newline at end of file diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/synthetic/pipeline_n14/real.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/synthetic/pipeline_n14/real.csv new file mode 100644 index 0000000000000000000000000000000000000000..3eb127a41257f73db9bdc048d746e032df1602e7 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/synthetic/pipeline_n14/real.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c185607e5260848288c1fe3ee266131707a54e9f5e053f1234c019f315783fac +size 700663 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/synthetic/pipeline_n14/test.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/synthetic/pipeline_n14/test.csv new file mode 100644 index 0000000000000000000000000000000000000000..f0047af47ae70bd3483af5c9474d2baa67f629bb --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/synthetic/pipeline_n14/test.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6c58f97d23ce9ec15dde2caf4ba02105c2839eb4b1e1bb7f5183e0661fec4ecd +size 88640 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/synthetic/pipeline_n14/val.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/synthetic/pipeline_n14/val.csv new file mode 100644 index 0000000000000000000000000000000000000000..a5a6f693df47fd7a53d30e1da2c9caaa2edf2d23 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/synthetic/pipeline_n14/val.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:efcb8ee58a24ce4397213b3c4df4826fbcc6662da77b0919ff4e1935d12e2e89 +size 87578 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/conftest.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..f06feabdb2e28287232689c91868cc8e58730387 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/conftest.py @@ -0,0 +1,193 @@ +import pytest +import numpy as np +import torch +import torch.nn.functional as F +from unittest.mock import MagicMock + + +# --------------- dimension configs --------------- + +@pytest.fixture +def dims(): + """Standard mixed-data dimensions.""" + return {"d_numerical": 4, "categories": np.array([3, 5, 2]), "batch_size": 8, "d_token": 16} + + +@pytest.fixture +def dims_numerical_only(): + """Numerical-only scenario (no categorical features).""" + return {"d_numerical": 5, "categories": None, "batch_size": 8, "d_token": 16} + + +@pytest.fixture +def dims_single(): + """Minimal scenario: 1 numerical, 1 categorical with 2 classes.""" + return {"d_numerical": 1, "categories": np.array([2]), "batch_size": 4, "d_token": 8} + + +# --------------- dummy input factory --------------- + +@pytest.fixture +def make_dummy_inputs(): + """Factory: returns (x_num, x_cat_onehot, x_cat_int, timesteps) from any dims.""" + def _make(d_numerical, categories, batch_size): + torch.manual_seed(42) + x_num = torch.randn(batch_size, d_numerical) + if categories is not None and len(categories) > 0: + cat_parts = [] + for k in categories: + indices = torch.randint(0, k, (batch_size,)) + cat_parts.append(F.one_hot(indices, k).float()) + x_cat_onehot = torch.cat(cat_parts, dim=1) + x_cat_int = torch.stack( + [torch.randint(0, k, (batch_size,)) for k in categories], dim=1 + ) + else: + x_cat_onehot = None + x_cat_int = None + timesteps = torch.rand(batch_size) + return x_num, x_cat_onehot, x_cat_int, timesteps + return _make + + +# --------------- model factories --------------- + +@pytest.fixture +def make_tokenizer(): + from ef_vfm.modules.transformer import Tokenizer + def _make(d_numerical, categories, d_token, bias=True): + cats = list(categories) if categories is not None else None + return Tokenizer(d_numerical, cats, d_token, bias) + return _make + + +@pytest.fixture +def make_transformer(): + from ef_vfm.modules.transformer import Transformer + def _make(d_token, n_layers=2, n_heads=1, d_ffn_factor=4, activation='gelu'): + return Transformer(n_layers, d_token, n_heads, d_token, d_ffn_factor, activation=activation) + return _make + + +@pytest.fixture +def make_reconstructor(): + from ef_vfm.modules.transformer import Reconstructor + def _make(d_numerical, categories, d_token): + cats = list(categories) if categories is not None else [] + return Reconstructor(d_numerical, cats, d_token) + return _make + + +@pytest.fixture +def make_mlp(): + from ef_vfm.modules.main_modules import MLP + def _make(d_in, dim_t=128, use_mlp=True): + return MLP(d_in, dim_t=dim_t, use_mlp=use_mlp) + return _make + + +@pytest.fixture +def make_unimodmlp(): + from ef_vfm.modules.main_modules import UniModMLP + def _make(d_numerical, categories, d_token=16, n_layers=1, n_head=1, + factor=4, dim_t=64, activation='gelu'): + cats = list(categories) if categories is not None else [] + return UniModMLP( + d_numerical, cats, n_layers, d_token, + n_head=n_head, factor=factor, dim_t=dim_t, activation=activation, + ) + return _make + + +@pytest.fixture +def make_flow_model(): + from ef_vfm.modules.main_modules import UniModMLP + from ef_vfm.models.flow_model import ExpVFM + def _make(d_numerical, categories, d_token=16, n_layers=1, dim_t=64): + cats_list = list(categories) if categories is not None else [] + cats_np = np.array(cats_list) + model = UniModMLP( + d_numerical, cats_list, n_layers, d_token, + n_head=1, factor=4, dim_t=dim_t, activation='gelu', + ) + flow = ExpVFM( + num_classes=cats_np, + num_numerical_features=d_numerical, + vf_fn=model, + device=torch.device('cpu'), + ) + return flow + return _make + + +@pytest.fixture +def make_trainer(): + """Factory: creates a minimal Trainer with mocked external dependencies.""" + from ef_vfm.modules.main_modules import UniModMLP + from ef_vfm.models.flow_model import ExpVFM + from ef_vfm.trainer import Trainer + + def _make(d_numerical=4, categories=np.array([3, 5, 2]), + lr=0.001, max_grad_norm=1.0, warmup_epochs=0, + lr_scheduler='reduce_lr_on_plateau', steps=10, tmp_path=None): + + cats_list = list(categories) if categories is not None else [] + cats_np = np.array(cats_list) + + model = UniModMLP( + d_numerical, cats_list, 1, 16, + n_head=1, factor=4, dim_t=64, activation='gelu', + ) + flow = ExpVFM( + num_classes=cats_np, + num_numerical_features=d_numerical, + vf_fn=model, + device=torch.device('cpu'), + ) + + # Build a small synthetic dataset: [N, d_num + len(cats)] with int cat indices + n_samples = 32 + x_num = torch.randn(n_samples, d_numerical) + if len(cats_list) > 0: + x_cat = torch.stack( + [torch.randint(0, k, (n_samples,)) for k in cats_list], dim=1 + ).float() + data = torch.cat([x_num, x_cat], dim=1) + else: + data = x_num + + dataset = torch.utils.data.TensorDataset(data) + train_iter = torch.utils.data.DataLoader(dataset, batch_size=8, shuffle=False) + # DataLoader wraps in tuples; Trainer expects raw tensors, so use a wrapper + class _UnwrapLoader: + def __init__(self, loader): + self._loader = loader + def __iter__(self): + for (batch,) in self._loader: + yield batch + def __len__(self): + return len(self._loader) + + save_path = str(tmp_path) if tmp_path else "/tmp" + trainer = Trainer( + flow=flow, + train_iter=_UnwrapLoader(train_iter), + dataset=MagicMock(), + test_dataset=MagicMock(), + metrics=MagicMock(), + logger=MagicMock(), + lr=lr, + weight_decay=0, + steps=steps, + batch_size=8, + check_val_every=steps + 1, # never evaluate during test + sample_batch_size=8, + model_save_path=save_path, + result_save_path=save_path, + lr_scheduler=lr_scheduler, + max_grad_norm=max_grad_norm, + warmup_epochs=warmup_epochs, + device=torch.device('cpu'), + ) + return trainer + return _make diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/test_attention.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/test_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..6082db42ad2dff94440f4cc07659c57cf6326de4 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/test_attention.py @@ -0,0 +1,51 @@ +import pytest +import torch +from ef_vfm.modules.transformer import MultiheadAttention + + +def test_output_shape_single_head(): + attn = MultiheadAttention(d=16, n_heads=1, dropout=0.0) + x = torch.randn(4, 5, 16) + out = attn(x, x) + assert out.shape == (4, 5, 16) + + +def test_output_shape_multi_head(): + attn = MultiheadAttention(d=16, n_heads=4, dropout=0.0) + x = torch.randn(4, 5, 16) + out = attn(x, x) + assert out.shape == (4, 5, 16) + + +def test_no_W_out_single_head(): + attn = MultiheadAttention(d=16, n_heads=1, dropout=0.0) + assert attn.W_out is None + + +def test_W_out_exists_multi_head(): + attn = MultiheadAttention(d=16, n_heads=4, dropout=0.0) + assert attn.W_out is not None + + +def test_cross_attention_diff_seq_len(): + attn = MultiheadAttention(d=16, n_heads=1, dropout=0.0) + x_q = torch.randn(4, 3, 16) + x_kv = torch.randn(4, 7, 16) + out = attn(x_q, x_kv) + assert out.shape == (4, 3, 16) # output seq_len matches query + + +def test_invalid_d_nheads_raises(): + with pytest.raises(AssertionError): + MultiheadAttention(d=15, n_heads=4, dropout=0.0) + + +def test_gradient_flows(): + attn = MultiheadAttention(d=16, n_heads=2, dropout=0.0) + x = torch.randn(4, 5, 16, requires_grad=True) + out = attn(x, x) + out.sum().backward() + assert x.grad is not None and x.grad.abs().sum() > 0 + for name in ['W_q', 'W_k', 'W_v']: + param = getattr(attn, name) + assert param.weight.grad is not None and param.weight.grad.abs().sum() > 0 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/test_config.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/test_config.py new file mode 100644 index 0000000000000000000000000000000000000000..95c723f64388fe1259f0ba62f0ad8c6cf1051455 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/test_config.py @@ -0,0 +1,62 @@ +import os +from pathlib import Path + +from src.util import load_config +from ef_vfm.modules.main_modules import UniModMLP + + +CONFIG_PATH = Path(__file__).resolve().parent.parent / "ef_vfm" / "configs" / "ef_vfm_configs.toml" + + +def test_load_config_returns_dict(): + config = load_config(CONFIG_PATH) + assert isinstance(config, dict) + + +def test_config_has_expected_sections(): + config = load_config(CONFIG_PATH) + for key in ['data', 'unimodmlp_params', 'train', 'sample']: + assert key in config, f"Missing section '{key}'" + + +def test_unimodmlp_params_complete(): + config = load_config(CONFIG_PATH) + params = config['unimodmlp_params'] + required = ['num_layers', 'd_token', 'n_head', 'factor', 'bias', 'dim_t', 'use_mlp', 'activation'] + for key in required: + assert key in params, f"Missing param '{key}' in unimodmlp_params" + + +def test_activation_value_is_valid(): + config = load_config(CONFIG_PATH) + activation = config['unimodmlp_params']['activation'] + assert activation in ('relu', 'gelu', 'silu'), f"Invalid activation '{activation}'" + + +def test_train_main_has_new_params(): + """Verify the recently added config params are present.""" + config = load_config(CONFIG_PATH) + train = config['train']['main'] + assert 'max_grad_norm' in train + assert 'warmup_epochs' in train + assert isinstance(train['max_grad_norm'], (int, float)) + assert isinstance(train['warmup_epochs'], (int, float)) + + +def test_config_values_create_model(): + config = load_config(CONFIG_PATH) + params = config['unimodmlp_params'] + # Use dummy dimensions; the point is that config params are valid for the constructor + model = UniModMLP( + d_numerical=4, + categories=[3, 5, 2], + num_layers=params['num_layers'], + d_token=params['d_token'], + n_head=params['n_head'], + factor=params['factor'], + bias=params['bias'], + dim_t=params['dim_t'], + use_mlp=params['use_mlp'], + activation=params['activation'], + ) + assert model is not None diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/test_flow_model.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/test_flow_model.py new file mode 100644 index 0000000000000000000000000000000000000000..2bdc72bf2388cc70b56389463bdfd322b8badced --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/test_flow_model.py @@ -0,0 +1,219 @@ +import torch +import numpy as np +from unittest.mock import patch + +from ef_vfm.models.flow_model import ExpVFM, Velocity +from ef_vfm.modules.main_modules import UniModMLP + + +# ---- mixed_loss tests ---- + +def test_mixed_loss_returns_two_scalars(make_flow_model, make_dummy_inputs, dims): + d = dims + flow = make_flow_model(d["d_numerical"], d["categories"]) + _, _, x_cat_int, _ = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"]) + x_num = torch.randn(d["batch_size"], d["d_numerical"]) + x = torch.cat([x_num, x_cat_int.float()], dim=1) + d_loss, c_loss = flow.mixed_loss(x) + assert d_loss.dim() == 0 or d_loss.numel() == 1 + assert c_loss.dim() == 0 or c_loss.numel() == 1 + + +def test_mixed_loss_finite(make_flow_model, make_dummy_inputs, dims): + d = dims + flow = make_flow_model(d["d_numerical"], d["categories"]) + _, _, x_cat_int, _ = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"]) + x_num = torch.randn(d["batch_size"], d["d_numerical"]) + x = torch.cat([x_num, x_cat_int.float()], dim=1) + d_loss, c_loss = flow.mixed_loss(x) + assert torch.isfinite(d_loss).all() + assert torch.isfinite(c_loss).all() + + +def test_mixed_loss_gradients_flow(make_flow_model, make_dummy_inputs, dims): + d = dims + flow = make_flow_model(d["d_numerical"], d["categories"]) + _, _, x_cat_int, _ = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"]) + x_num = torch.randn(d["batch_size"], d["d_numerical"]) + x = torch.cat([x_num, x_cat_int.float()], dim=1) + d_loss, c_loss = flow.mixed_loss(x) + total = d_loss + c_loss + total.backward() + grads = [p.grad for p in flow.parameters() if p.grad is not None] + assert len(grads) > 0 + + +def test_mixed_loss_numerical_only(make_flow_model, make_dummy_inputs, dims_numerical_only): + d = dims_numerical_only + flow = make_flow_model(d["d_numerical"], d["categories"]) + x = torch.randn(d["batch_size"], d["d_numerical"]) + d_loss, c_loss = flow.mixed_loss(x) + assert d_loss.item() == 0.0 # no discrete features + assert c_loss.item() > 0.0 + + +# ---- sample tests (with mocked odeint) ---- + +def _make_flow(d_numerical, categories): + cats_list = list(categories) if categories is not None else [] + cats_np = np.array(cats_list) + model = UniModMLP(d_numerical, cats_list, 1, 16, n_head=1, factor=4, dim_t=64, activation='gelu') + return ExpVFM(cats_np, d_numerical, model, device=torch.device('cpu')) + + +def test_sample_output_shape(dims): + d = dims + flow = _make_flow(d["d_numerical"], d["categories"]) + d_in = d["d_numerical"] + sum(d["categories"]) + n = 5 + fake_trajectory = torch.randn(2, n, d_in) + with patch("ef_vfm.models.flow_model.odeint", return_value=fake_trajectory): + result = flow.sample(n) + d_out = d["d_numerical"] + len(d["categories"]) + assert result.shape == (n, d_out) + + +def test_sample_categorical_in_range(dims): + d = dims + flow = _make_flow(d["d_numerical"], d["categories"]) + d_in = d["d_numerical"] + sum(d["categories"]) + n = 16 + fake_trajectory = torch.randn(2, n, d_in) + with patch("ef_vfm.models.flow_model.odeint", return_value=fake_trajectory): + result = flow.sample(n) + for i, k in enumerate(d["categories"]): + col = d["d_numerical"] + i + assert (result[:, col] >= 0).all() + assert (result[:, col] < k).all() + + +def test_sample_returns_cpu(dims): + d = dims + flow = _make_flow(d["d_numerical"], d["categories"]) + d_in = d["d_numerical"] + sum(d["categories"]) + fake_trajectory = torch.randn(2, 4, d_in) + with patch("ef_vfm.models.flow_model.odeint", return_value=fake_trajectory): + result = flow.sample(4) + assert result.device == torch.device('cpu') + + +def test_sample_single_sample(dims): + d = dims + flow = _make_flow(d["d_numerical"], d["categories"]) + d_in = d["d_numerical"] + sum(d["categories"]) + fake_trajectory = torch.randn(2, 1, d_in) + with patch("ef_vfm.models.flow_model.odeint", return_value=fake_trajectory): + result = flow.sample(1) + d_out = d["d_numerical"] + len(d["categories"]) + assert result.shape == (1, d_out) + + +# ---- to_one_hot tests ---- + +def test_to_one_hot_shape(dims): + d = dims + flow = _make_flow(d["d_numerical"], d["categories"]) + cats = d["categories"] + x_cat = torch.stack([torch.randint(0, k, (8,)) for k in cats], dim=1) + oh = flow.to_one_hot(x_cat) + assert oh.shape == (8, sum(cats)) + + +def test_to_one_hot_roundtrip(dims): + d = dims + flow = _make_flow(d["d_numerical"], d["categories"]) + cats = d["categories"] + x_cat = torch.stack([torch.randint(0, k, (8,)) for k in cats], dim=1) + oh = flow.to_one_hot(x_cat) + # Recover indices via argmax per category slice + idx = 0 + for i, k in enumerate(cats): + recovered = oh[:, idx:idx + k].argmax(dim=1) + assert torch.equal(recovered, x_cat[:, i]) + idx += k + + +def test_to_one_hot_binary_values(dims): + d = dims + flow = _make_flow(d["d_numerical"], d["categories"]) + cats = d["categories"] + x_cat = torch.stack([torch.randint(0, k, (8,)) for k in cats], dim=1) + oh = flow.to_one_hot(x_cat) + assert set(oh.unique().tolist()).issubset({0, 1}) + + +# ---- Regression tests ---- + +def test_regression_d_in_no_extra_len(): + """d_in must be num_numerical + sum(num_classes), NOT + len(num_classes).""" + d_numerical = 4 + categories = np.array([3, 5, 2]) + flow = _make_flow(d_numerical, categories) + expected_d_in = d_numerical + sum(categories) # 14, not 17 + assert flow.num_numerical_features + sum(flow.num_classes) == expected_d_in + + +def test_regression_sampling_indices_correct(): + """Categorical argmax must go to columns [d_num, d_num+1, ...], not [0, 1, ...].""" + d_numerical = 4 + categories = np.array([3, 5, 2]) + n = 10 + d_in = d_numerical + sum(categories) + d_out = d_numerical + len(categories) + + # Simulate the post-processing from sample() + out = torch.randn(n, d_in) + sample = torch.zeros(n, d_out) + sample[:, :d_numerical] = out[:, :d_numerical] + + idx = d_numerical # correct starting index + for i, val in enumerate(categories): + col = d_numerical + i # correct column + sample[:, col] = torch.argmax(out[:, idx:idx + val], dim=1) + idx += val + + # Numerical columns must be untouched + assert torch.allclose(sample[:, :d_numerical], out[:, :d_numerical]) + # Categorical columns at correct positions + for i, val in enumerate(categories): + col = d_numerical + i + assert (sample[:, col] >= 0).all() + assert (sample[:, col] < val).all() + + +def test_regression_d_out_correct(): + """d_out must be d_num + len(categories).""" + d_numerical = 4 + categories = np.array([3, 5, 2]) + flow = _make_flow(d_numerical, categories) + expected_d_out = d_numerical + len(categories) # 7 + assert expected_d_out == 7 + + +# ---- Velocity tests ---- + +def test_velocity_output_shape(dims): + d = dims + cats_list = list(d["categories"]) + model = UniModMLP(d["d_numerical"], cats_list, 1, d["d_token"], + n_head=1, factor=4, dim_t=64, activation='gelu') + vel = Velocity(model) + d_in = d["d_numerical"] + sum(d["categories"]) + x = torch.randn(d["batch_size"], d_in) + t = torch.tensor(0.5) + out = vel(t, x) + assert out.shape == (d["batch_size"], d_in) + + +def test_velocity_scalar_t_broadcast(dims): + d = dims + cats_list = list(d["categories"]) + model = UniModMLP(d["d_numerical"], cats_list, 1, d["d_token"], + n_head=1, factor=4, dim_t=64, activation='gelu') + vel = Velocity(model) + d_in = d["d_numerical"] + sum(d["categories"]) + x = torch.randn(d["batch_size"], d_in) + # Scalar t should work (gets broadcast internally) + t = torch.tensor(0.3) + out = vel(t, x) + assert out.shape == x.shape diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/test_mlp.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/test_mlp.py new file mode 100644 index 0000000000000000000000000000000000000000..0cf9ad4d6832d792cb65a1bb01bdc784385f9fcd --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/test_mlp.py @@ -0,0 +1,85 @@ +import torch +import torch.nn as nn +from ef_vfm.modules.main_modules import MLP, PositionalEmbedding + + +# ---- PositionalEmbedding tests ---- + +def test_positional_embedding_shape(): + pe = PositionalEmbedding(num_channels=64) + x = torch.rand(8) + out = pe(x) + assert out.shape == (8, 64) + + +def test_positional_embedding_bounded(): + pe = PositionalEmbedding(num_channels=64) + x = torch.rand(8) + out = pe(x) + assert out.min() >= -1.0 + assert out.max() <= 1.0 + + +def test_positional_embedding_deterministic(): + pe = PositionalEmbedding(num_channels=64) + x = torch.tensor([0.1, 0.5, 0.9]) + out1 = pe(x) + out2 = pe(x) + assert torch.equal(out1, out2) + + +def test_positional_embedding_different_timesteps(): + pe = PositionalEmbedding(num_channels=64) + t1 = torch.tensor([0.1]) + t2 = torch.tensor([0.9]) + assert not torch.allclose(pe(t1), pe(t2)) + + +# ---- MLP tests ---- + +def test_mlp_output_shape(make_mlp): + mlp = make_mlp(d_in=32, dim_t=64) + x = torch.randn(8, 32) + t = torch.rand(8) + out = mlp(x, t) + assert out.shape == (8, 32) + + +def test_mlp_use_mlp_true(make_mlp): + mlp = make_mlp(d_in=32, dim_t=64, use_mlp=True) + assert isinstance(mlp.mlp, nn.Sequential) + + +def test_mlp_use_mlp_false(make_mlp): + mlp = make_mlp(d_in=32, dim_t=64, use_mlp=False) + assert isinstance(mlp.mlp, nn.Linear) + + +def test_mlp_time_conditioning(make_mlp): + mlp = make_mlp(d_in=32, dim_t=64) + mlp.eval() + x = torch.randn(4, 32) + t1 = torch.zeros(4) + t2 = torch.ones(4) + out1 = mlp(x, t1) + out2 = mlp(x, t2) + assert not torch.allclose(out1, out2) + + +def test_mlp_gradient_flows(make_mlp): + mlp = make_mlp(d_in=32, dim_t=64) + x = torch.randn(4, 32) + t = torch.rand(4) + out = mlp(x, t) + out.sum().backward() + assert mlp.proj.weight.grad is not None and mlp.proj.weight.grad.abs().sum() > 0 + assert mlp.map_noise.num_channels == 64 # sanity check on PE config + + +def test_mlp_different_dim_t(make_mlp): + for dim_t in [32, 128, 256]: + mlp = make_mlp(d_in=16, dim_t=dim_t) + x = torch.randn(4, 16) + t = torch.rand(4) + out = mlp(x, t) + assert out.shape == (4, 16) diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/test_reconstructor.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/test_reconstructor.py new file mode 100644 index 0000000000000000000000000000000000000000..cdc39880d19f644fb8ac6b457af6a8cb3d83cbfa --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/test_reconstructor.py @@ -0,0 +1,51 @@ +import torch +import numpy as np +from ef_vfm.modules.transformer import Reconstructor + + +def test_output_shapes_mixed(make_reconstructor, dims): + d = dims + r = make_reconstructor(d["d_numerical"], d["categories"], d["d_token"]) + seq_len = d["d_numerical"] + len(d["categories"]) + h = torch.randn(d["batch_size"], seq_len, d["d_token"]) + x_num, x_cat = r(h) + assert x_num.shape == (d["batch_size"], d["d_numerical"]) + assert len(x_cat) == len(d["categories"]) + for i, k in enumerate(d["categories"]): + assert x_cat[i].shape == (d["batch_size"], k) + + +def test_categorical_count(make_reconstructor, dims): + d = dims + r = make_reconstructor(d["d_numerical"], d["categories"], d["d_token"]) + seq_len = d["d_numerical"] + len(d["categories"]) + h = torch.randn(d["batch_size"], seq_len, d["d_token"]) + _, x_cat = r(h) + assert len(x_cat) == len(d["categories"]) + + +def test_empty_categories(make_reconstructor): + r = make_reconstructor(4, np.array([]), 16) + h = torch.randn(8, 4, 16) + x_num, x_cat = r(h) + assert x_num.shape == (8, 4) + assert len(x_cat) == 0 + + +def test_weight_shape(make_reconstructor, dims): + d = dims + r = make_reconstructor(d["d_numerical"], d["categories"], d["d_token"]) + assert r.weight.shape == (d["d_numerical"], d["d_token"]) + + +def test_gradient_flows(make_reconstructor, dims): + d = dims + r = make_reconstructor(d["d_numerical"], d["categories"], d["d_token"]) + seq_len = d["d_numerical"] + len(d["categories"]) + h = torch.randn(d["batch_size"], seq_len, d["d_token"]) + x_num, x_cat = r(h) + loss = x_num.sum() + sum(c.sum() for c in x_cat) + loss.backward() + assert r.weight.grad is not None and r.weight.grad.abs().sum() > 0 + for recon in r.cat_recons: + assert recon.weight.grad is not None diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/test_tokenizer.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/test_tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..ea8c55737d473605c2bb1c87f0394fad64baeb18 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/test_tokenizer.py @@ -0,0 +1,85 @@ +import torch +import numpy as np + + +def test_forward_shape_mixed(make_tokenizer, make_dummy_inputs, dims): + tok = make_tokenizer(dims["d_numerical"], dims["categories"], dims["d_token"]) + x_num, x_cat_oh, _, _ = make_dummy_inputs(dims["d_numerical"], dims["categories"], dims["batch_size"]) + out = tok(x_num, x_cat_oh) + expected_seq = 1 + dims["d_numerical"] + len(dims["categories"]) + assert out.shape == (dims["batch_size"], expected_seq, dims["d_token"]) + + +def test_forward_shape_numerical_only(make_tokenizer, make_dummy_inputs, dims_numerical_only): + d = dims_numerical_only + tok = make_tokenizer(d["d_numerical"], d["categories"], d["d_token"]) + x_num, _, _, _ = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"]) + out = tok(x_num, None) + expected_seq = 1 + d["d_numerical"] + assert out.shape == (d["batch_size"], expected_seq, d["d_token"]) + + +def test_forward_shape_single_feature(make_tokenizer, make_dummy_inputs, dims_single): + d = dims_single + tok = make_tokenizer(d["d_numerical"], d["categories"], d["d_token"]) + x_num, x_cat_oh, _, _ = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"]) + out = tok(x_num, x_cat_oh) + expected_seq = 1 + d["d_numerical"] + len(d["categories"]) + assert out.shape == (d["batch_size"], expected_seq, d["d_token"]) + + +def test_n_tokens_property(make_tokenizer, dims): + tok = make_tokenizer(dims["d_numerical"], dims["categories"], dims["d_token"]) + expected = dims["d_numerical"] + 1 + len(dims["categories"]) + assert tok.n_tokens == expected + + +def test_n_tokens_numerical_only(make_tokenizer, dims_numerical_only): + d = dims_numerical_only + tok = make_tokenizer(d["d_numerical"], d["categories"], d["d_token"]) + assert tok.n_tokens == d["d_numerical"] + 1 + + +def test_cls_token_position(make_tokenizer, make_dummy_inputs, dims): + tok = make_tokenizer(dims["d_numerical"], dims["categories"], dims["d_token"], bias=False) + x_num, x_cat_oh, _, _ = make_dummy_inputs(dims["d_numerical"], dims["categories"], dims["batch_size"]) + out = tok(x_num, x_cat_oh) + # CLS token: ones * weight[0], so all batch rows should have the same CLS token + cls_tokens = out[:, 0, :] + assert torch.allclose(cls_tokens[0], cls_tokens[1]) + assert torch.allclose(cls_tokens[0], tok.weight[0]) + + +def test_bias_vs_no_bias(make_tokenizer, make_dummy_inputs, dims): + d = dims + tok_bias = make_tokenizer(d["d_numerical"], d["categories"], d["d_token"], bias=True) + tok_no_bias = make_tokenizer(d["d_numerical"], d["categories"], d["d_token"], bias=False) + assert tok_bias.bias is not None + assert tok_no_bias.bias is None + + +def test_category_offsets_values(make_tokenizer): + cats = np.array([3, 5, 2]) + tok = make_tokenizer(4, cats, 16) + assert torch.equal(tok.category_offsets, torch.tensor([0, 3, 8])) + assert torch.equal(tok.category_ends, torch.tensor([3, 8, 10])) + + +def test_cat_weight_shape(make_tokenizer, dims): + tok = make_tokenizer(dims["d_numerical"], dims["categories"], dims["d_token"]) + assert tok.cat_weight.shape == (sum(dims["categories"]), dims["d_token"]) + + +def test_weight_shape(make_tokenizer, dims): + tok = make_tokenizer(dims["d_numerical"], dims["categories"], dims["d_token"]) + assert tok.weight.shape == (dims["d_numerical"] + 1, dims["d_token"]) + + +def test_gradient_flows(make_tokenizer, make_dummy_inputs, dims): + tok = make_tokenizer(dims["d_numerical"], dims["categories"], dims["d_token"]) + x_num, x_cat_oh, _, _ = make_dummy_inputs(dims["d_numerical"], dims["categories"], dims["batch_size"]) + out = tok(x_num, x_cat_oh) + out.sum().backward() + assert tok.weight.grad is not None and tok.weight.grad.abs().sum() > 0 + assert tok.cat_weight.grad is not None and tok.cat_weight.grad.abs().sum() > 0 + assert tok.bias.grad is not None and tok.bias.grad.abs().sum() > 0 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/test_trainer.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/test_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..592c538d2aa1f8f34098a0d7c6c4fc0b1f0c5ddf --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/test_trainer.py @@ -0,0 +1,98 @@ +import torch +import numpy as np + + +# ---- Gradient clipping tests ---- + +def test_grad_clipping_applied(make_trainer, tmp_path): + trainer = make_trainer(max_grad_norm=0.5, tmp_path=tmp_path) + batch = next(iter(trainer.train_iter)) + trainer._run_step(batch, closs_weight=1.0, dloss_weight=1.0) + # After clipping, total gradient norm should be <= max_grad_norm (with tolerance) + total_norm = torch.nn.utils.clip_grad_norm_(trainer.flow.parameters(), float('inf')) + # Gradients were already clipped in _run_step, then optimizer.step() zeroed them. + # So we re-run to check: do a fresh forward-backward without step + trainer.optimizer.zero_grad() + dloss, closs = trainer.flow.mixed_loss(batch.to(trainer.device)) + (dloss + closs).backward() + torch.nn.utils.clip_grad_norm_(trainer.flow.parameters(), 0.5) + total_norm = 0.0 + for p in trainer.flow.parameters(): + if p.grad is not None: + total_norm += p.grad.data.norm(2).item() ** 2 + total_norm = total_norm ** 0.5 + assert total_norm <= 0.5 + 1e-6 + + +def test_grad_clipping_disabled(make_trainer, tmp_path): + trainer = make_trainer(max_grad_norm=0, tmp_path=tmp_path) + assert trainer.max_grad_norm == 0 + + +def test_run_step_returns_losses(make_trainer, tmp_path): + trainer = make_trainer(tmp_path=tmp_path) + batch = next(iter(trainer.train_iter)) + dloss, closs = trainer._run_step(batch, closs_weight=1.0, dloss_weight=1.0) + assert isinstance(dloss, torch.Tensor) + assert isinstance(closs, torch.Tensor) + assert torch.isfinite(dloss) + assert torch.isfinite(closs) + + +# ---- LR warmup tests ---- + +def test_warmup_lr_linear_ramp(make_trainer, tmp_path): + init_lr = 0.01 + warmup = 5 + trainer = make_trainer(lr=init_lr, warmup_epochs=warmup, tmp_path=tmp_path) + # Simulate warmup epochs + for epoch in range(warmup): + expected_lr = init_lr * (epoch + 1) / warmup + if trainer.warmup_epochs > 0 and (epoch + 1) <= trainer.warmup_epochs: + warmup_lr = trainer.init_lr * (epoch + 1) / trainer.warmup_epochs + for pg in trainer.optimizer.param_groups: + pg["lr"] = warmup_lr + actual_lr = trainer.optimizer.param_groups[0]["lr"] + assert abs(actual_lr - expected_lr) < 1e-8, f"Epoch {epoch}: expected {expected_lr}, got {actual_lr}" + + +def test_warmup_overrides_scheduler(make_trainer, tmp_path): + trainer = make_trainer(warmup_epochs=10, lr_scheduler='reduce_lr_on_plateau', tmp_path=tmp_path) + initial_lr = trainer.optimizer.param_groups[0]["lr"] + # During warmup, scheduler.step should NOT be called (we just set LR directly) + # Simulate epoch 1 warmup + warmup_lr = trainer.init_lr * 1 / trainer.warmup_epochs + for pg in trainer.optimizer.param_groups: + pg["lr"] = warmup_lr + assert trainer.optimizer.param_groups[0]["lr"] == warmup_lr + assert warmup_lr < initial_lr # warmup starts lower + + +def test_no_warmup_when_zero(make_trainer, tmp_path): + trainer = make_trainer(warmup_epochs=0, tmp_path=tmp_path) + assert trainer.warmup_epochs == 0 + # LR should be the init_lr from the start + assert trainer.optimizer.param_groups[0]["lr"] == trainer.init_lr + + +# ---- LR scheduler tests ---- + +def test_anneal_lr(make_trainer, tmp_path): + trainer = make_trainer(lr=0.01, steps=100, lr_scheduler='anneal', tmp_path=tmp_path) + trainer._anneal_lr(50) + expected = 0.01 * (1 - 50 / 100) + assert abs(trainer.optimizer.param_groups[0]["lr"] - expected) < 1e-8 + + +# ---- EMA tests ---- + +def test_ema_model_created(make_trainer, tmp_path): + trainer = make_trainer(tmp_path=tmp_path) + # EMA model should exist and have same structure as flow._vf_fn + assert trainer.ema_model is not None + ema_params = list(trainer.ema_model.parameters()) + model_params = list(trainer.flow._vf_fn.parameters()) + assert len(ema_params) == len(model_params) + # EMA params should be detached (requires_grad=False) + for p in ema_params: + assert not p.requires_grad diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/test_transformer.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/test_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..ff56e884615e818841fbb912f8ef4e9961729197 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/test_transformer.py @@ -0,0 +1,73 @@ +import pytest +import torch +from ef_vfm.modules.transformer import Transformer + + +def test_output_shape_preserved(make_transformer): + t = make_transformer(d_token=16, n_layers=2) + x = torch.randn(4, 5, 16) + out = t(x) + assert out.shape == x.shape + + +def test_activation_gelu(make_transformer): + t = make_transformer(d_token=16, activation='gelu') + x = torch.randn(4, 5, 16) + out = t(x) + assert out.shape == x.shape + + +def test_activation_silu(make_transformer): + t = make_transformer(d_token=16, activation='silu') + x = torch.randn(4, 5, 16) + out = t(x) + assert out.shape == x.shape + + +def test_activation_relu(make_transformer): + t = make_transformer(d_token=16, activation='relu') + x = torch.randn(4, 5, 16) + out = t(x) + assert out.shape == x.shape + + +def test_invalid_activation_raises(): + with pytest.raises(ValueError, match="Unknown activation"): + Transformer(2, 16, 1, 16, 4, activation='bad') + + +def test_prenorm_first_layer_no_norm0(): + t = Transformer(2, 16, 1, 16, 4, prenormalization=True) + assert 'norm0' not in t.layers[0] + # Second layer should have norm0 + assert 'norm0' in t.layers[1] + + +def test_no_prenorm_all_layers_have_norm0(): + t = Transformer(2, 16, 1, 16, 4, prenormalization=False) + for layer in t.layers: + assert 'norm0' in layer + + +def test_single_layer(): + t = Transformer(1, 16, 1, 16, 4) + x = torch.randn(4, 5, 16) + out = t(x) + assert out.shape == x.shape + + +def test_multi_layer(): + t = Transformer(4, 16, 1, 16, 4) + x = torch.randn(4, 5, 16) + out = t(x) + assert out.shape == x.shape + + +def test_gradient_flows(make_transformer): + t = make_transformer(d_token=16, n_layers=2) + x = torch.randn(4, 5, 16, requires_grad=True) + out = t(x) + out.sum().backward() + assert x.grad is not None and x.grad.abs().sum() > 0 + # Check gradients through at least the first layer's linear0 + assert t.layers[0]['linear0'].weight.grad is not None diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/test_unimodmlp.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/test_unimodmlp.py new file mode 100644 index 0000000000000000000000000000000000000000..d935e7c48dba78fd7e4821287628aa861aa6d1b4 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/test_unimodmlp.py @@ -0,0 +1,72 @@ +import torch +import numpy as np + + +def test_forward_shapes_mixed(make_unimodmlp, make_dummy_inputs, dims): + d = dims + model = make_unimodmlp(d["d_numerical"], d["categories"], d_token=d["d_token"]) + x_num, x_cat_oh, _, t = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"]) + x_num_pred, x_cat_pred = model(x_num, x_cat_oh, t) + assert x_num_pred.shape == (d["batch_size"], d["d_numerical"]) + assert x_cat_pred.shape == (d["batch_size"], sum(d["categories"])) + + +def test_forward_shapes_numerical_only(make_unimodmlp, make_dummy_inputs, dims_numerical_only): + d = dims_numerical_only + model = make_unimodmlp(d["d_numerical"], d["categories"], d_token=d["d_token"]) + x_num, _, _, t = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"]) + x_cat = torch.zeros(d["batch_size"], 0) + x_num_pred, x_cat_pred = model(x_num, x_cat, t) + assert x_num_pred.shape == (d["batch_size"], d["d_numerical"]) + # When no categories, cat_pred should be zeros with shape matching x_cat + assert x_cat_pred.shape[0] == d["batch_size"] + assert torch.all(x_cat_pred == 0) + + +def test_forward_shapes_single_feature(make_unimodmlp, make_dummy_inputs, dims_single): + d = dims_single + model = make_unimodmlp(d["d_numerical"], d["categories"], d_token=d["d_token"]) + x_num, x_cat_oh, _, t = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"]) + x_num_pred, x_cat_pred = model(x_num, x_cat_oh, t) + assert x_num_pred.shape == (d["batch_size"], d["d_numerical"]) + assert x_cat_pred.shape == (d["batch_size"], sum(d["categories"])) + + +def test_d_in_computation(make_unimodmlp, dims): + d = dims + model = make_unimodmlp(d["d_numerical"], d["categories"], d_token=d["d_token"]) + expected = d["d_token"] * (d["d_numerical"] + len(d["categories"])) + assert model.mlp.proj.in_features == expected + + +def test_output_dtypes(make_unimodmlp, make_dummy_inputs, dims): + d = dims + model = make_unimodmlp(d["d_numerical"], d["categories"], d_token=d["d_token"]) + x_num, x_cat_oh, _, t = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"]) + x_num_pred, x_cat_pred = model(x_num, x_cat_oh, t) + assert x_num_pred.dtype == torch.float32 + assert x_cat_pred.dtype == torch.float32 + + +def test_gradient_flows_end_to_end(make_unimodmlp, make_dummy_inputs, dims): + d = dims + model = make_unimodmlp(d["d_numerical"], d["categories"], d_token=d["d_token"]) + x_num, x_cat_oh, _, t = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"]) + x_num_pred, x_cat_pred = model(x_num, x_cat_oh, t) + loss = x_num_pred.sum() + x_cat_pred.sum() + loss.backward() + params_with_grad = sum(1 for p in model.parameters() if p.grad is not None and p.grad.abs().sum() > 0) + total_params = sum(1 for _ in model.parameters()) + # Transformer.head is defined but unused in forward(), so not all params get gradients + assert params_with_grad > total_params * 0.8, f"Only {params_with_grad}/{total_params} params got gradients" + + +def test_different_activations(make_unimodmlp, make_dummy_inputs, dims): + d = dims + x_num, x_cat_oh, _, t = make_dummy_inputs(d["d_numerical"], d["categories"], d["batch_size"]) + for act in ['relu', 'gelu', 'silu']: + model = make_unimodmlp(d["d_numerical"], d["categories"], d_token=d["d_token"], activation=act) + x_num_pred, x_cat_pred = model(x_num, x_cat_oh, t) + assert x_num_pred.shape == (d["batch_size"], d["d_numerical"]) + assert torch.isfinite(x_num_pred).all() + assert torch.isfinite(x_cat_pred).all() diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/test_utils.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fbce0db0ac74052a4038dee89fd753b9d97717aa --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/tests/test_utils.py @@ -0,0 +1,49 @@ +import torch +import numpy as np + +from utils_train import update_ema, concat_y_to_X + + +# ---- update_ema tests ---- + +def test_update_ema_basic(): + target = [torch.tensor([1.0, 2.0])] + source = [torch.tensor([3.0, 4.0])] + target[0].requires_grad_(False) + rate = 0.9 + update_ema(target, source, rate=rate) + expected = 0.9 * torch.tensor([1.0, 2.0]) + 0.1 * torch.tensor([3.0, 4.0]) + assert torch.allclose(target[0], expected) + + +def test_update_ema_rate_zero(): + target = [torch.tensor([1.0, 2.0])] + source = [torch.tensor([3.0, 4.0])] + target[0].requires_grad_(False) + update_ema(target, source, rate=0.0) + assert torch.allclose(target[0], torch.tensor([3.0, 4.0])) + + +def test_update_ema_rate_one(): + target = [torch.tensor([1.0, 2.0])] + source = [torch.tensor([3.0, 4.0])] + target[0].requires_grad_(False) + update_ema(target, source, rate=1.0) + assert torch.allclose(target[0], torch.tensor([1.0, 2.0])) + + +# ---- concat_y_to_X tests ---- + +def test_concat_y_to_X_with_X(): + X = np.array([[1, 2], [3, 4]]) + y = np.array([10, 20]) + result = concat_y_to_X(X, y) + expected = np.array([[10, 1, 2], [20, 3, 4]]) + np.testing.assert_array_equal(result, expected) + + +def test_concat_y_to_X_without_X(): + y = np.array([10, 20, 30]) + result = concat_y_to_X(None, y) + expected = np.array([[10], [20], [30]]) + np.testing.assert_array_equal(result, expected) diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/utils_train.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/utils_train.py new file mode 100644 index 0000000000000000000000000000000000000000..f849c412fa3cc62098f14b12684d16ecc30e94ea --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/utils_train.py @@ -0,0 +1,205 @@ +import numpy as np +import os +from pathlib import Path + +import src +from torch.utils.data import Dataset + +import torch + + +class TabularDataset(Dataset): + def __init__(self, X_num, X_cat): + self.X_num = X_num + self.X_cat = X_cat + + def __getitem__(self, index): + this_num = self.X_num[index] + this_cat = self.X_cat[index] + + sample = (this_num, this_cat) + + return sample + + def __len__(self): + return self.X_num.shape[0] + + +class EFVFMDataset(Dataset): + def __init__(self, dataname, data_dir, info, isTrain=True, dequant_dist='none', int_dequant_factor=0.0): + self.dataname = dataname + self.data_dir = data_dir + self.info = info + self.isTrain = isTrain + + X_num, X_cat, categories, d_numerical, num_inverse, int_inverse, cat_inverse = preprocess( + data_dir, dequant_dist, int_dequant_factor, task_type=info['task_type'], inverse=True + ) + categories = np.array(categories) + + X_train_num, X_test_num = X_num + X_train_cat, X_test_cat = X_cat + + X_train_num = torch.tensor(X_train_num).float() + X_test_num = torch.tensor(X_test_num).float() + X_train_cat = torch.tensor(X_train_cat) + X_test_cat = torch.tensor(X_test_cat) + + self.X = ( + torch.cat((X_train_num, X_train_cat), dim=1) + if isTrain + else torch.cat((X_test_num, X_test_cat), dim=1) + ) + self.num_inverse = num_inverse + self.int_inverse = int_inverse + self.cat_inverse = cat_inverse + self.d_numerical = d_numerical + self.categories = categories + + def __getitem__(self, index): + return self.X[index] + + def __len__(self): + return self.X.shape[0] + + +def _empty_num_like(y_split): + return np.zeros((len(y_split), 0), dtype=np.float32) + + +def _empty_cat_like(y_split): + return np.zeros((len(y_split), 0), dtype=np.int64) + + +def preprocess(dataset_path, dequant_dist='none', int_dequant_factor=0.0, task_type='binclass', inverse=False, cat_encoding=None, concat=True): + + T_dict = {} + + T_dict['normalization'] = "quantile" + T_dict['num_nan_policy'] = 'mean' + T_dict['cat_nan_policy'] = None + T_dict['cat_min_frequency'] = None + T_dict['cat_encoding'] = cat_encoding + T_dict['y_policy'] = "default" + T_dict['dequant_dist'] = dequant_dist + T_dict['int_dequant_factor'] = int_dequant_factor + + T = src.Transformations(**T_dict) + + dataset = make_dataset( + data_path=dataset_path, + T=T, + task_type=task_type, + change_val=False, + concat=concat, + ) + + if cat_encoding is None: + X_num = dataset.X_num + X_cat = dataset.X_cat + y = dataset.y + + if X_num is None: + X_train_num = _empty_num_like(y['train']) + X_test_num = _empty_num_like(y['test']) + else: + X_train_num, X_test_num = X_num['train'], X_num['test'] + + if X_cat is None: + # Some datasets have no categorical features after preprocessing. + # For classification tasks, ef-vfm still expects the target to be + # concatenated into the categorical block. + if task_type in ('binclass', 'multiclass') and concat and y is not None: + X_train_cat = y['train'].reshape(-1, 1) + X_test_cat = y['test'].reshape(-1, 1) + else: + X_train_cat = _empty_cat_like(y['train']) + X_test_cat = _empty_cat_like(y['test']) + else: + X_train_cat, X_test_cat = X_cat['train'], X_cat['test'] + + categories = src.get_categories(X_train_cat) if X_train_cat.shape[1] > 0 else [] + d_numerical = X_train_num.shape[1] + + X_num = (X_train_num, X_test_num) + X_cat = (X_train_cat, X_test_cat) + + if inverse: + num_inverse = dataset.num_transform.inverse_transform if dataset.num_transform is not None else lambda x: x + int_inverse = dataset.int_transform.inverse_transform if dataset.int_transform is not None else lambda x: x + cat_inverse = dataset.cat_transform.inverse_transform if dataset.cat_transform is not None else lambda x: x + + return X_num, X_cat, categories, d_numerical, num_inverse, int_inverse, cat_inverse + else: + return X_num, X_cat, categories, d_numerical + else: + return dataset + + +def update_ema(target_params, source_params, rate=0.999): + for target, source in zip(target_params, source_params): + target.detach().mul_(rate).add_(source.detach(), alpha=1 - rate) + + +def concat_y_to_X(X, y): + if X is None: + return y.reshape(-1, 1) + return np.concatenate([y.reshape(-1, 1), X], axis=1) + + +def make_dataset( + data_path: str, + T: src.Transformations, + task_type, + change_val: bool, + concat=True, +): + + if task_type == 'binclass' or task_type == 'multiclass': + X_cat = {} if os.path.exists(os.path.join(data_path, 'X_cat_train.npy')) else None + X_num = {} if os.path.exists(os.path.join(data_path, 'X_num_train.npy')) else None + y = {} if os.path.exists(os.path.join(data_path, 'y_train.npy')) else None + + for split in ['train', 'test']: + X_num_t, X_cat_t, y_t = src.read_pure_data(data_path, split) + if X_num is not None: + X_num[split] = X_num_t + if X_cat is not None: + if concat: + X_cat_t = concat_y_to_X(X_cat_t, y_t) + X_cat[split] = X_cat_t + if y is not None: + y[split] = y_t + else: + X_cat = {} if os.path.exists(os.path.join(data_path, 'X_cat_train.npy')) else None + X_num = {} if os.path.exists(os.path.join(data_path, 'X_num_train.npy')) else None + y = {} if os.path.exists(os.path.join(data_path, 'y_train.npy')) else None + + for split in ['train', 'test']: + X_num_t, X_cat_t, y_t = src.read_pure_data(data_path, split) + if X_num is not None: + if concat: + X_num_t = concat_y_to_X(X_num_t, y_t) + X_num[split] = X_num_t + if X_cat is not None: + X_cat[split] = X_cat_t + if y is not None: + y[split] = y_t + + info = src.load_json(os.path.join(data_path, 'info.json')) + int_col_idx_wrt_num = info['int_col_idx_wrt_num'] + + D = src.Dataset( + X_num, + X_cat, + y, + int_col_idx_wrt_num, + y_info={}, + task_type=src.TaskType(info['task_type']), + n_classes=info.get('n_classes') + ) + + if change_val: + D = src.change_val(D) + D = src.transform_dataset(D, T, cache_dir=Path(data_path)) + return D diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_tabbyflow_gen.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_tabbyflow_gen.py new file mode 100644 index 0000000000000000000000000000000000000000..4ef729ee3f75e25833bbf445c5be0bdc4f6414a3 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_tabbyflow_gen.py @@ -0,0 +1,45 @@ + +import os, shutil, subprocess, sys +root = r"/workspace/ef-vfm" +rt = r"/work/output-Benchmark-trainonly-v1/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime" +name = r"pipeline_n14" +src = r"/work/output-Benchmark-trainonly-v1/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14" + +if not os.path.exists(rt): + def _ignore(_, names): + skip = {"__pycache__", "data", "synthetic", "result", "results", "ckpt"} + return [n for n in names if n in skip or n.endswith(".pyc")] + shutil.copytree(root, rt, ignore=_ignore) + +dst_data = os.path.join(rt, "data", name) +shutil.rmtree(dst_data, ignore_errors=True) +os.makedirs(os.path.dirname(dst_data), exist_ok=True) +shutil.copytree(src, dst_data) +dst_syn = os.path.join(rt, "synthetic", name) +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(rt) +os.environ["PYTHONPATH"] = rt + os.pathsep + os.environ.get("PYTHONPATH", "") +os.environ.setdefault("EFVFM_SAMPLE_BATCH_SIZE", "64") +os.environ.setdefault("EFVFM_ODE_FALLBACK", "1") +os.environ.setdefault("EFVFM_RK4_STEPS", "32") +subprocess.check_call([ + sys.executable, os.path.join(rt, "main.py"), + "--dataname", name, "--mode", "test", "--gpu", "0", + "--no_wandb", "--exp_name", r"adapter_efvfm", + "--ckpt_path", r"/work/output-Benchmark-trainonly-v1/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime/ckpt/pipeline_n14/adapter_efvfm/model_100.pt", + "--num_samples_to_generate", str(int(1600)), +]) +base = os.path.join(rt, "ef_vfm", "result", name, r"adapter_efvfm") +best = None +best_t = -1.0 +for r, _, files in os.walk(base): + if "samples.csv" in files: + p = os.path.join(r, "samples.csv") + t = os.path.getmtime(p) + if t > best_t: + best_t, best = t, p +if not best: + raise SystemExit("tabbyflow: no samples.csv in " + base) +shutil.copy(best, r"/work/output-Benchmark-trainonly-v1/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabbyflow-n14-1600-20260512_000840.csv") diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_tabbyflow_train.py b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_tabbyflow_train.py new file mode 100644 index 0000000000000000000000000000000000000000..5e6c9e04e4da901f81cdd7d834e9c452004afc67 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/_tabbyflow_train.py @@ -0,0 +1,40 @@ + +import os, shutil, subprocess, sys +root = r"/workspace/ef-vfm" +rt = r"/work/output-Benchmark-trainonly-v1/n14/tabbyflow/tabbyflow-n14-20260512_000442/_efvfm_runtime" +name = r"pipeline_n14" +src = r"/work/output-Benchmark-trainonly-v1/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14" + +shutil.rmtree(rt, ignore_errors=True) + +def _ignore(_, names): + skip = {"__pycache__", "data", "synthetic", "result", "results", "ckpt"} + return [n for n in names if n in skip or n.endswith(".pyc")] + +shutil.copytree(root, rt, ignore=_ignore) +pkg_cfg = os.path.join(rt, "ef_vfm", "configs") +root_cfg = os.path.join(rt, "configs") +if not os.path.isdir(root_cfg) and os.path.isdir(pkg_cfg): + shutil.copytree(pkg_cfg, root_cfg) +dst_data = os.path.join(rt, "data", name) +dst_syn = os.path.join(rt, "synthetic", name) +shutil.rmtree(dst_data, ignore_errors=True) +os.makedirs(os.path.dirname(dst_data), exist_ok=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(rt) +os.environ["PYTHONPATH"] = rt + os.pathsep + os.environ.get("PYTHONPATH", "") +os.environ["EFVFM_SMOKE_STEPS"] = "100" +os.environ["EFVFM_ADAPTER_TRAIN"] = "1" +os.environ.setdefault("EFVFM_TRAIN_BATCH_SIZE", "64") +os.environ.setdefault("EFVFM_SAMPLE_BATCH_SIZE", "64") +os.environ.setdefault("EFVFM_EVAL_NUM_SAMPLES", "512") +os.environ.setdefault("EFVFM_ODE_FALLBACK", "1") +os.environ.setdefault("EFVFM_RK4_STEPS", "32") +subprocess.check_call([ + sys.executable, os.path.join(rt, "main.py"), + "--dataname", name, "--mode", "train", "--gpu", "0", + "--no_wandb", "--exp_name", r"adapter_efvfm", +]) diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/gen_20260512_000840.log b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/gen_20260512_000840.log new file mode 100644 index 0000000000000000000000000000000000000000..75989480ea3e905a261369047d46a1f82b2d21eb --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/gen_20260512_000840.log @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d780b9a97a251ac5f5bb2862a8e67dfb7619d263a1c132e0b54d1bed3182a782 +size 4298 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/input_snapshot.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/input_snapshot.json new file mode 100644 index 0000000000000000000000000000000000000000..08865fd252ae77127c65516f5840c6fe4e1385f5 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/input_snapshot.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cb19f1f9abf2b8f00b8196f9ab1c2fd918d4549f286ecafc1a77a6b02f3fddfc +size 1361 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/models_tabbyflow/trained.pt b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/models_tabbyflow/trained.pt new file mode 100644 index 0000000000000000000000000000000000000000..f063a878c470d9d40f79db79881596e1e497dffd --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/models_tabbyflow/trained.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:adb734fec12f2251befd371dca69e481b19464aded2a6823105a01b4be6ddbe5 +size 40 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/public_gate/normalized_schema_snapshot.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/public_gate/normalized_schema_snapshot.json new file mode 100644 index 0000000000000000000000000000000000000000..e95bb9f1507ba3dcc217e156d288a4c218d5ce0e --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/public_gate/normalized_schema_snapshot.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1039de91400208739668ec5dbba162e50476ffb8f7bc2c41c34a9e152d1a1fd7 +size 25212 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/public_gate/public_gate_report.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/public_gate/public_gate_report.json new file mode 100644 index 0000000000000000000000000000000000000000..3042bd53a693121e438e327a754bb37ba7d23620 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/public_gate/public_gate_report.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d0323cb1844f3ed9d898f3dd78211792dbc408cc2661f88cffa593a96fe919f2 +size 920 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/public_gate/staged_input_manifest.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/public_gate/staged_input_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..c9a9805bd6fb1bc05fd2308cb1429115ad743736 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/public_gate/staged_input_manifest.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ded944e1ff5ba344c427b92b79e43ca7f2fb9df4b64fe52c983ff7ac29ec2b8b +size 26048 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/run_config.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/run_config.json new file mode 100644 index 0000000000000000000000000000000000000000..6a2fe7edba201cd5010c525cb1be4d35c439e05c --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/run_config.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7f8fbedfe54903d07c8fb1eb3a86775bdd3497b5ceba142d2f3ed339721bc520 +size 2289 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/runtime_result.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/runtime_result.json new file mode 100644 index 0000000000000000000000000000000000000000..985f734ad7d82684e1b5fd0379ce3ec8aa1c96fe --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/runtime_result.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0a0a2bc779d205e757cca6a0018c61b020cff07f2e11fe00f3c3e21755da4c8a +size 932 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/staged/public/staged_features.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/staged/public/staged_features.json new file mode 100644 index 0000000000000000000000000000000000000000..764ec9270aa6a452ad32f774e4eb007bf24ca4ec --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/staged/public/staged_features.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2ceb242f15c8115703b617ca54db02ff27dff41d99dd4f9af89bb5fcb513e5bb +size 5032 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/staged/public/test.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/staged/public/test.csv new file mode 100644 index 0000000000000000000000000000000000000000..f0047af47ae70bd3483af5c9474d2baa67f629bb --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/staged/public/test.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6c58f97d23ce9ec15dde2caf4ba02105c2839eb4b1e1bb7f5183e0661fec4ecd +size 88640 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/staged/public/train.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/staged/public/train.csv new file mode 100644 index 0000000000000000000000000000000000000000..3eb127a41257f73db9bdc048d746e032df1602e7 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/staged/public/train.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c185607e5260848288c1fe3ee266131707a54e9f5e053f1234c019f315783fac +size 700663 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/staged/public/val.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/staged/public/val.csv new file mode 100644 index 0000000000000000000000000000000000000000..a5a6f693df47fd7a53d30e1da2c9caaa2edf2d23 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/staged/public/val.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:efcb8ee58a24ce4397213b3c4df4826fbcc6662da77b0919ff4e1935d12e2e89 +size 87578 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/staged/tabbyflow/adapter_report.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/staged/tabbyflow/adapter_report.json new file mode 100644 index 0000000000000000000000000000000000000000..6efff2e54e8a5eb8574f409f05f3b0e14ad3a5bc --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/staged/tabbyflow/adapter_report.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:38380ebfc4ab1b6df312bbfc320a769fbd26d82e4cc77ab858aa0a399437ad87 +size 329 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/staged/tabbyflow/adapter_transforms_applied.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/staged/tabbyflow/adapter_transforms_applied.json new file mode 100644 index 0000000000000000000000000000000000000000..6f3aaa01a627a955d2022165805d2786c0da78ba --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/staged/tabbyflow/adapter_transforms_applied.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945 +size 2 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/staged/tabbyflow/model_input_manifest.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/staged/tabbyflow/model_input_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..bb7d06379fc7938a3c1fddf6dc74583e8a1d623f --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/staged/tabbyflow/model_input_manifest.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:904bf7a94c4378fe324387301e47f709a5d23fc3c80ca009900077b638d0b471 +size 26253 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabbyflow-n14-1600-20260512_000442.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabbyflow-n14-1600-20260512_000442.csv new file mode 100644 index 0000000000000000000000000000000000000000..0ee2d9d2004f0a23e18ca9fd285675b59d2897fa --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabbyflow-n14-1600-20260512_000442.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1bd0fb8b36df6a7aa6de043038a7040ee5826c962eb42ffc81540c57bf18bd6c +size 851261 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabbyflow_train_meta.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabbyflow_train_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..2f2814fd078d5991c6f9a1493830689a4789daba --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabbyflow_train_meta.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1e152e005ebeef5c0dcd22b98d9a0ef1f4f8ea554aa8139aec071a47c9e642cf +size 414 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/X_num_test.npy b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/X_num_test.npy new file mode 100644 index 0000000000000000000000000000000000000000..58dcffe35f9c3d2be06bfacd6463afc29f469621 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/X_num_test.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e252b63332f6d0348986fa99b50bd0f50a4842a6535d987c77e35ec94dca2304 +size 41132 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/X_num_train.npy b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/X_num_train.npy new file mode 100644 index 0000000000000000000000000000000000000000..829ebc8714db6fb18f342ce0609de9b685c8a4c8 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/X_num_train.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b976aada0f39493df222408da25c8093fae5ed29c88a963352f6c5924720bfcb +size 326528 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/X_num_val.npy b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/X_num_val.npy new file mode 100644 index 0000000000000000000000000000000000000000..f9b501abfa8648ee74efcaddf531803aee3c5f5c --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/X_num_val.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:43682ea64d3dccdcaf67f0c922556fe78e3cd216b7456a914a5e169e2b52f5a8 +size 40724 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/info.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/info.json new file mode 100644 index 0000000000000000000000000000000000000000..349bd7f0dfb9558da57b1bb6f8027d081b2f8ffe --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/info.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:575631118d21657a7a362ba5a330d6fff150a3d78c4ba038ffb878dd37c75cd5 +size 9435 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/real.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/real.csv new file mode 100644 index 0000000000000000000000000000000000000000..3eb127a41257f73db9bdc048d746e032df1602e7 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/real.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c185607e5260848288c1fe3ee266131707a54e9f5e053f1234c019f315783fac +size 700663 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/staged_features.json b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/staged_features.json new file mode 100644 index 0000000000000000000000000000000000000000..764ec9270aa6a452ad32f774e4eb007bf24ca4ec --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/staged_features.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2ceb242f15c8115703b617ca54db02ff27dff41d99dd4f9af89bb5fcb513e5bb +size 5032 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/test.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/test.csv new file mode 100644 index 0000000000000000000000000000000000000000..f0047af47ae70bd3483af5c9474d2baa67f629bb --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/test.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6c58f97d23ce9ec15dde2caf4ba02105c2839eb4b1e1bb7f5183e0661fec4ecd +size 88640 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/train.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/train.csv new file mode 100644 index 0000000000000000000000000000000000000000..3eb127a41257f73db9bdc048d746e032df1602e7 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/train.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c185607e5260848288c1fe3ee266131707a54e9f5e053f1234c019f315783fac +size 700663 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/val.csv b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/val.csv new file mode 100644 index 0000000000000000000000000000000000000000..a5a6f693df47fd7a53d30e1da2c9caaa2edf2d23 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/val.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:efcb8ee58a24ce4397213b3c4df4826fbcc6662da77b0919ff4e1935d12e2e89 +size 87578 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/y_test.npy b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/y_test.npy new file mode 100644 index 0000000000000000000000000000000000000000..5651fa99fbfba7f7fa1d0ad15aebc466b7a7cc53 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/y_test.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2e6b805a842cf97508b8a3789499fc698c44e659e45b100fb80d666ad2f96a74 +size 1736 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/y_train.npy b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/y_train.npy new file mode 100644 index 0000000000000000000000000000000000000000..0849049b021bfe542c1221ec2b7369cecd5e2165 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/y_train.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ee738812eaaf4a819a6c9f861ee2e99873bd2842f80c68eb380cc38033938b74 +size 12928 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/y_val.npy b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/y_val.npy new file mode 100644 index 0000000000000000000000000000000000000000..87b51e4ebfe724b015106152ef10e69ffd69b53b --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/tabular_bundle/pipeline_n14/y_val.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0df86b75b6fc8fea3f161682beaa867a5bb7dbe36f9331e7d36176459da70720 +size 1720 diff --git a/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/train_20260512_000442.log b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/train_20260512_000442.log new file mode 100644 index 0000000000000000000000000000000000000000..91260cec7b0cb16e8ae0b3da7a1946e913536c49 --- /dev/null +++ b/syntheticFail/n14/tabbyflow/tabbyflow-n14-20260512_000442/train_20260512_000442.log @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:990b3417e500a72639eeb7e976347d8b8142c8b16e4565565eaac2eb7d057c1a +size 562149