Resume SynthData0523 main/c6 batch 17
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +30 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/pipeline.py +112 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/resample_privacy.py +257 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/sample.py +160 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/train.py +158 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/tune_ddpm.py +127 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/tune_evaluation_model.py +145 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/utils_train.py +89 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/smote/pipeline_smote.py +68 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/smote/sample_smote.py +210 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/smote/tune_smote.py +98 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/__init__.py +2 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/__pycache__/__init__.cpython-311.pyc +0 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/__pycache__/gaussian_multinomial_diffsuion.cpython-311.pyc +0 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/__pycache__/modules.cpython-311.pyc +0 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/__pycache__/utils.cpython-311.pyc +0 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/gaussian_multinomial_diffsuion.py +993 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/modules.py +486 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/utils.py +174 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tools/convert_synth_to_csv.py +89 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tools/make_tabddpm_info.py +97 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/abalone_cv.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/adult_cv.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/buddy_cv.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/california_cv.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/cardio_cv.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/churn2_cv.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/default_cv.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/diabetes_cv.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/fb-comments_cv.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/gesture_cv.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/higgs-small_cv.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/house_cv.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/insurance_cv.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/king_cv.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/miniboone_cv.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/wilt_cv.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/abalone_cv.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/adult_cv.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/buddy_cv.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/california_cv.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/cardio_cv.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/churn2_cv.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/default_cv.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/diabetes_cv.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/gesture_cv.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/higgs-small_cv.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/house_cv.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/insurance_cv.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/king_cv.json +3 -0
.gitattributes
CHANGED
|
@@ -5271,3 +5271,33 @@ SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wi
|
|
| 5271 |
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/tvae/eval_catboost.json filter=lfs diff=lfs merge=lfs -text
|
| 5272 |
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/tvae/eval_simple.json filter=lfs diff=lfs merge=lfs -text
|
| 5273 |
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/tvae/info.json filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5271 |
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/tvae/eval_catboost.json filter=lfs diff=lfs merge=lfs -text
|
| 5272 |
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/tvae/eval_simple.json filter=lfs diff=lfs merge=lfs -text
|
| 5273 |
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/tvae/info.json filter=lfs diff=lfs merge=lfs -text
|
| 5274 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/abalone_cv.json filter=lfs diff=lfs merge=lfs -text
|
| 5275 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/adult_cv.json filter=lfs diff=lfs merge=lfs -text
|
| 5276 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/buddy_cv.json filter=lfs diff=lfs merge=lfs -text
|
| 5277 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/california_cv.json filter=lfs diff=lfs merge=lfs -text
|
| 5278 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/cardio_cv.json filter=lfs diff=lfs merge=lfs -text
|
| 5279 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/churn2_cv.json filter=lfs diff=lfs merge=lfs -text
|
| 5280 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/default_cv.json filter=lfs diff=lfs merge=lfs -text
|
| 5281 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/diabetes_cv.json filter=lfs diff=lfs merge=lfs -text
|
| 5282 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/fb-comments_cv.json filter=lfs diff=lfs merge=lfs -text
|
| 5283 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/gesture_cv.json filter=lfs diff=lfs merge=lfs -text
|
| 5284 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/higgs-small_cv.json filter=lfs diff=lfs merge=lfs -text
|
| 5285 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/house_cv.json filter=lfs diff=lfs merge=lfs -text
|
| 5286 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/insurance_cv.json filter=lfs diff=lfs merge=lfs -text
|
| 5287 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/king_cv.json filter=lfs diff=lfs merge=lfs -text
|
| 5288 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/miniboone_cv.json filter=lfs diff=lfs merge=lfs -text
|
| 5289 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/wilt_cv.json filter=lfs diff=lfs merge=lfs -text
|
| 5290 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/abalone_cv.json filter=lfs diff=lfs merge=lfs -text
|
| 5291 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/adult_cv.json filter=lfs diff=lfs merge=lfs -text
|
| 5292 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/buddy_cv.json filter=lfs diff=lfs merge=lfs -text
|
| 5293 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/california_cv.json filter=lfs diff=lfs merge=lfs -text
|
| 5294 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/cardio_cv.json filter=lfs diff=lfs merge=lfs -text
|
| 5295 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/churn2_cv.json filter=lfs diff=lfs merge=lfs -text
|
| 5296 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/default_cv.json filter=lfs diff=lfs merge=lfs -text
|
| 5297 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/diabetes_cv.json filter=lfs diff=lfs merge=lfs -text
|
| 5298 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/gesture_cv.json filter=lfs diff=lfs merge=lfs -text
|
| 5299 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/higgs-small_cv.json filter=lfs diff=lfs merge=lfs -text
|
| 5300 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/house_cv.json filter=lfs diff=lfs merge=lfs -text
|
| 5301 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/insurance_cv.json filter=lfs diff=lfs merge=lfs -text
|
| 5302 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/king_cv.json filter=lfs diff=lfs merge=lfs -text
|
| 5303 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/miniboone_cv.json filter=lfs diff=lfs merge=lfs -text
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/pipeline.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import tomli
|
| 2 |
+
import shutil
|
| 3 |
+
import os
|
| 4 |
+
import argparse
|
| 5 |
+
from scripts.train import train
|
| 6 |
+
from scripts.sample import sample
|
| 7 |
+
from scripts.eval_catboost import train_catboost
|
| 8 |
+
from scripts.eval_mlp import train_mlp
|
| 9 |
+
from scripts.eval_simple import train_simple
|
| 10 |
+
import pandas as pd
|
| 11 |
+
import matplotlib.pyplot as plt
|
| 12 |
+
import zero
|
| 13 |
+
import lib
|
| 14 |
+
import torch
|
| 15 |
+
|
| 16 |
+
def load_config(path) :
|
| 17 |
+
with open(path, 'rb') as f:
|
| 18 |
+
return tomli.load(f)
|
| 19 |
+
|
| 20 |
+
def save_file(parent_dir, config_path):
|
| 21 |
+
try:
|
| 22 |
+
dst = os.path.join(parent_dir)
|
| 23 |
+
os.makedirs(os.path.dirname(dst), exist_ok=True)
|
| 24 |
+
shutil.copyfile(os.path.abspath(config_path), dst)
|
| 25 |
+
except shutil.SameFileError:
|
| 26 |
+
pass
|
| 27 |
+
|
| 28 |
+
def main():
|
| 29 |
+
parser = argparse.ArgumentParser()
|
| 30 |
+
parser.add_argument('--config', metavar='FILE')
|
| 31 |
+
parser.add_argument('--train', action='store_true', default=False)
|
| 32 |
+
parser.add_argument('--sample', action='store_true', default=False)
|
| 33 |
+
parser.add_argument('--eval', action='store_true', default=False)
|
| 34 |
+
parser.add_argument('--change_val', action='store_true', default=False)
|
| 35 |
+
|
| 36 |
+
args = parser.parse_args()
|
| 37 |
+
raw_config = lib.load_config(args.config)
|
| 38 |
+
if 'device' in raw_config:
|
| 39 |
+
device = torch.device(raw_config['device'])
|
| 40 |
+
else:
|
| 41 |
+
device = torch.device('cuda:1')
|
| 42 |
+
|
| 43 |
+
timer = zero.Timer()
|
| 44 |
+
timer.run()
|
| 45 |
+
save_file(os.path.join(raw_config['parent_dir'], 'config.toml'), args.config)
|
| 46 |
+
|
| 47 |
+
if args.train:
|
| 48 |
+
train(
|
| 49 |
+
**raw_config['train']['main'],
|
| 50 |
+
**raw_config['diffusion_params'],
|
| 51 |
+
parent_dir=raw_config['parent_dir'],
|
| 52 |
+
real_data_path=raw_config['real_data_path'],
|
| 53 |
+
model_type=raw_config['model_type'],
|
| 54 |
+
model_params=raw_config['model_params'],
|
| 55 |
+
T_dict=raw_config['train']['T'],
|
| 56 |
+
num_numerical_features=raw_config['num_numerical_features'],
|
| 57 |
+
device=device,
|
| 58 |
+
change_val=args.change_val
|
| 59 |
+
)
|
| 60 |
+
if args.sample:
|
| 61 |
+
sample(
|
| 62 |
+
num_samples=raw_config['sample']['num_samples'],
|
| 63 |
+
batch_size=raw_config['sample']['batch_size'],
|
| 64 |
+
disbalance=raw_config['sample'].get('disbalance', None),
|
| 65 |
+
**raw_config['diffusion_params'],
|
| 66 |
+
parent_dir=raw_config['parent_dir'],
|
| 67 |
+
real_data_path=raw_config['real_data_path'],
|
| 68 |
+
model_path=os.path.join(raw_config['parent_dir'], 'model.pt'),
|
| 69 |
+
model_type=raw_config['model_type'],
|
| 70 |
+
model_params=raw_config['model_params'],
|
| 71 |
+
T_dict=raw_config['train']['T'],
|
| 72 |
+
num_numerical_features=raw_config['num_numerical_features'],
|
| 73 |
+
device=device,
|
| 74 |
+
seed=raw_config['sample'].get('seed', 0),
|
| 75 |
+
change_val=args.change_val
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
save_file(os.path.join(raw_config['parent_dir'], 'info.json'), os.path.join(raw_config['real_data_path'], 'info.json'))
|
| 79 |
+
if args.eval:
|
| 80 |
+
if raw_config['eval']['type']['eval_model'] == 'catboost':
|
| 81 |
+
train_catboost(
|
| 82 |
+
parent_dir=raw_config['parent_dir'],
|
| 83 |
+
real_data_path=raw_config['real_data_path'],
|
| 84 |
+
eval_type=raw_config['eval']['type']['eval_type'],
|
| 85 |
+
T_dict=raw_config['eval']['T'],
|
| 86 |
+
seed=raw_config['seed'],
|
| 87 |
+
change_val=args.change_val
|
| 88 |
+
)
|
| 89 |
+
elif raw_config['eval']['type']['eval_model'] == 'mlp':
|
| 90 |
+
train_mlp(
|
| 91 |
+
parent_dir=raw_config['parent_dir'],
|
| 92 |
+
real_data_path=raw_config['real_data_path'],
|
| 93 |
+
eval_type=raw_config['eval']['type']['eval_type'],
|
| 94 |
+
T_dict=raw_config['eval']['T'],
|
| 95 |
+
seed=raw_config['seed'],
|
| 96 |
+
change_val=args.change_val,
|
| 97 |
+
device=device
|
| 98 |
+
)
|
| 99 |
+
elif raw_config['eval']['type']['eval_model'] == 'simple':
|
| 100 |
+
train_simple(
|
| 101 |
+
parent_dir=raw_config['parent_dir'],
|
| 102 |
+
real_data_path=raw_config['real_data_path'],
|
| 103 |
+
eval_type=raw_config['eval']['type']['eval_type'],
|
| 104 |
+
T_dict=raw_config['eval']['T'],
|
| 105 |
+
seed=raw_config['seed'],
|
| 106 |
+
change_val=args.change_val
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
print(f'Elapsed time: {str(timer)}')
|
| 110 |
+
|
| 111 |
+
if __name__ == '__main__':
|
| 112 |
+
main()
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/resample_privacy.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Adapted from https://github.com/Team-TUD/CTAB-GAN/tree/main/model/eval
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import lib
|
| 7 |
+
import os
|
| 8 |
+
import shutil
|
| 9 |
+
import zero
|
| 10 |
+
from sample import sample
|
| 11 |
+
from smote.sample_smote import sample_smote
|
| 12 |
+
from sklearn.preprocessing import MinMaxScaler, OneHotEncoder
|
| 13 |
+
from sklearn.metrics import pairwise_distances
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
import tempfile
|
| 16 |
+
from eval_seeds import eval_seeds
|
| 17 |
+
import numpy as np
|
| 18 |
+
import subprocess
|
| 19 |
+
import warnings
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
zero.improve_reproducibility(0)
|
| 23 |
+
|
| 24 |
+
warnings.filterwarnings("ignore", category=FutureWarning)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def privacy_metrics(real_path,fake_path, data_percent=15):
|
| 28 |
+
|
| 29 |
+
"""
|
| 30 |
+
Returns privacy metrics
|
| 31 |
+
|
| 32 |
+
Inputs:
|
| 33 |
+
1) real_path -> path to real data
|
| 34 |
+
2) fake_path -> path to corresponding synthetic data
|
| 35 |
+
3) data_percent -> percentage of data to be sampled from real and synthetic datasets for computing privacy metrics
|
| 36 |
+
Outputs:
|
| 37 |
+
1) List containing the 5th percentile distance to closest record (DCR) between real and synthetic as well as within real and synthetic datasets
|
| 38 |
+
along with 5th percentile of nearest neighbour distance ratio (NNDR) between real and synthetic as well as within real and synthetic datasets
|
| 39 |
+
|
| 40 |
+
"""
|
| 41 |
+
task_type = lib.load_json(real_path + "/info.json")["task_type"]
|
| 42 |
+
X_num_real, X_cat_real, y_real = lib.read_pure_data(real_path, 'train')
|
| 43 |
+
X_num_fake, X_cat_fake, y_fake = lib.read_pure_data(fake_path, 'train')
|
| 44 |
+
|
| 45 |
+
if task_type == 'regression':
|
| 46 |
+
X_num_real = np.concatenate([X_num_real, y_real[:, np.newaxis]], axis=1)
|
| 47 |
+
X_num_fake = np.concatenate([X_num_fake, y_fake[:, np.newaxis]], axis=1)
|
| 48 |
+
else:
|
| 49 |
+
if X_cat_fake is None:
|
| 50 |
+
X_cat_real = y_real[:, np.newaxis].astype(int).astype(str)
|
| 51 |
+
X_cat_fake = y_fake[:, np.newaxis].astype(int).astype(str)
|
| 52 |
+
else:
|
| 53 |
+
X_cat_real = np.concatenate([X_cat_real, y_real[:, np.newaxis].astype(int).astype(str)], axis=1)
|
| 54 |
+
X_cat_fake = np.concatenate([X_cat_fake, y_fake[:, np.newaxis].astype(int).astype(str)], axis=1)
|
| 55 |
+
|
| 56 |
+
if len(y_real) > 50000:
|
| 57 |
+
ixs = np.random.choice(len(y_real), 50000, replace=False)
|
| 58 |
+
X_num_real = X_num_real[ixs]
|
| 59 |
+
X_cat_real = X_cat_real[ixs] if X_cat_real is not None else None
|
| 60 |
+
|
| 61 |
+
if len(y_fake) > 50000:
|
| 62 |
+
ixs = np.random.choice(len(y_fake), 50000, replace=False)
|
| 63 |
+
X_num_fake = X_num_fake[ixs]
|
| 64 |
+
X_cat_fake = X_cat_fake[ixs] if X_cat_fake is not None else None
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
mm = MinMaxScaler().fit(X_num_real)
|
| 68 |
+
X_real = mm.transform(X_num_real)
|
| 69 |
+
X_fake = mm.transform(X_num_fake)
|
| 70 |
+
if X_cat_real is not None:
|
| 71 |
+
ohe = OneHotEncoder().fit(X_cat_real)
|
| 72 |
+
X_cat_real = ohe.transform(X_cat_real) / np.sqrt(2)
|
| 73 |
+
X_cat_fake = ohe.transform(X_cat_fake) / np.sqrt(2)
|
| 74 |
+
|
| 75 |
+
X_real = np.concatenate([X_real, X_cat_real.todense()], axis=1)
|
| 76 |
+
X_fake = np.concatenate([X_fake, X_cat_fake.todense()], axis=1)
|
| 77 |
+
|
| 78 |
+
# X_real = np.unique(X_real, axis=0)
|
| 79 |
+
# X_fake = np.unique(X_fake, axis=0)
|
| 80 |
+
|
| 81 |
+
# Computing pair-wise distances between real and synthetic
|
| 82 |
+
dist_rf = pairwise_distances(X_fake, Y=X_real, metric='l2', n_jobs=-1)
|
| 83 |
+
# Computing pair-wise distances within real
|
| 84 |
+
# dist_rr = pairwise_distances(X_real, Y=None, metric='l2', n_jobs=-1)
|
| 85 |
+
# Computing pair-wise distances within synthetic
|
| 86 |
+
# dist_ff = pairwise_distances(X_fake, Y=None, metric='l2', n_jobs=-1)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# Removes distances of data points to themselves to avoid 0s within real and synthetic
|
| 90 |
+
# rd_dist_rr = dist_rr[~np.eye(dist_rr.shape[0],dtype=bool)].reshape(dist_rr.shape[0],-1)
|
| 91 |
+
# rd_dist_ff = dist_ff[~np.eye(dist_ff.shape[0],dtype=bool)].reshape(dist_ff.shape[0],-1)
|
| 92 |
+
|
| 93 |
+
# Computing first and second smallest nearest neighbour distances between real and synthetic
|
| 94 |
+
smallest_two_indexes_rf = [dist_rf[i].argsort()[:2] for i in range(len(dist_rf))]
|
| 95 |
+
smallest_two_rf = [dist_rf[i][smallest_two_indexes_rf[i]] for i in range(len(dist_rf))]
|
| 96 |
+
# Computing first and second smallest nearest neighbour distances within real
|
| 97 |
+
# smallest_two_indexes_rr = [rd_dist_rr[i].argsort()[:2] for i in range(len(rd_dist_rr))]
|
| 98 |
+
# smallest_two_rr = [rd_dist_rr[i][smallest_two_indexes_rr[i]] for i in range(len(rd_dist_rr))]
|
| 99 |
+
# Computing first and second smallest nearest neighbour distances within synthetic
|
| 100 |
+
# smallest_two_indexes_ff = [rd_dist_ff[i].argsort()[:2] for i in range(len(rd_dist_ff))]
|
| 101 |
+
# smallest_two_ff = [rd_dist_ff[i][smallest_two_indexes_ff[i]] for i in range(len(rd_dist_ff))]
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
# Computing 5th percentiles for DCR and NNDR between and within real and synthetic datasets
|
| 105 |
+
min_dist_rf = np.array([i[0] for i in smallest_two_rf])
|
| 106 |
+
fifth_perc_rf = np.percentile(min_dist_rf,5)
|
| 107 |
+
# min_dist_rr = np.array([i[0] for i in smallest_two_rr])
|
| 108 |
+
# fifth_perc_rr = np.percentile(min_dist_rr,5)
|
| 109 |
+
# min_dist_ff = np.array([i[0] for i in smallest_two_ff])
|
| 110 |
+
# fifth_perc_ff = np.percentile(min_dist_ff,5)
|
| 111 |
+
# nn_ratio_rf = np.array([i[0]/i[1] for i in smallest_two_rf])
|
| 112 |
+
# nn_fifth_perc_rf = np.percentile(nn_ratio_rf,5)
|
| 113 |
+
# nn_ratio_rr = np.array([i[0]/i[1] for i in smallest_two_rr])
|
| 114 |
+
# nn_fifth_perc_rr = np.percentile(nn_ratio_rr,5)
|
| 115 |
+
# nn_ratio_ff = np.array([i[0]/i[1] for i in smallest_two_ff])
|
| 116 |
+
# nn_fifth_perc_ff = np.percentile(nn_ratio_ff,5)
|
| 117 |
+
|
| 118 |
+
# return np.array([fifth_perc_rf,fifth_perc_rr,fifth_perc_ff,nn_fifth_perc_rf,nn_fifth_perc_rr,nn_fifth_perc_ff]).reshape(1,6)
|
| 119 |
+
return min_dist_rf # , min_dist_rr
|
| 120 |
+
|
| 121 |
+
def sample_wrapper(method, config, num_samples=None, seed=0):
|
| 122 |
+
if method == "ddpm":
|
| 123 |
+
sample(
|
| 124 |
+
num_samples=num_samples,
|
| 125 |
+
batch_size=config['sample']['batch_size'],
|
| 126 |
+
disbalance=config['sample'].get('disbalance', None),
|
| 127 |
+
**config['diffusion_params'],
|
| 128 |
+
parent_dir=config['parent_dir'],
|
| 129 |
+
real_data_path=config['real_data_path'],
|
| 130 |
+
model_path=os.path.join(config['parent_dir'], 'model.pt'),
|
| 131 |
+
model_type=config['model_type'],
|
| 132 |
+
model_params=config['model_params'],
|
| 133 |
+
T_dict=config['train']['T'],
|
| 134 |
+
num_numerical_features=config['num_numerical_features'],
|
| 135 |
+
seed=seed,
|
| 136 |
+
change_val=False,
|
| 137 |
+
device=torch.device(config["device"])
|
| 138 |
+
)
|
| 139 |
+
elif method == "smote":
|
| 140 |
+
sample_smote(
|
| 141 |
+
parent_dir=config['parent_dir'],
|
| 142 |
+
real_data_path=config['real_data_path'],
|
| 143 |
+
**config['smote_params'],
|
| 144 |
+
seed=seed,
|
| 145 |
+
change_val=False
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
def resample_privacy(config_path, method, q):
|
| 149 |
+
with tempfile.TemporaryDirectory() as dir_:
|
| 150 |
+
config = lib.load_config(config_path)
|
| 151 |
+
if method == "ddpm":
|
| 152 |
+
shutil.copy2(os.path.join(config['parent_dir'], 'model.pt'), os.path.join(dir_, 'model.pt'))
|
| 153 |
+
config["parent_dir"] = str(dir_)
|
| 154 |
+
parent_dir = config["parent_dir"]
|
| 155 |
+
|
| 156 |
+
sample_wrapper(method, config, num_samples=config["sample"].get("num_samples", 0))
|
| 157 |
+
|
| 158 |
+
dists = privacy_metrics(config["real_data_path"], parent_dir)
|
| 159 |
+
old_privacy = np.median(dists)
|
| 160 |
+
|
| 161 |
+
q10 = np.quantile(dists, q=q)
|
| 162 |
+
print(f"Q: {q10}")
|
| 163 |
+
to_drop = np.where(dists < q10)
|
| 164 |
+
|
| 165 |
+
X_num, X_cat, y = lib.read_pure_data(parent_dir)
|
| 166 |
+
num_samples = len(y)
|
| 167 |
+
X_num = np.delete(X_num, to_drop, axis=0)
|
| 168 |
+
X_cat = np.delete(X_cat, to_drop, axis=0) if X_cat is not None else None
|
| 169 |
+
y = np.delete(y, to_drop, axis=0)
|
| 170 |
+
i = 1
|
| 171 |
+
|
| 172 |
+
while len(y) < num_samples and i <= 10:
|
| 173 |
+
print(f"{len(y)}/{num_samples}")
|
| 174 |
+
|
| 175 |
+
sample_wrapper(method, config, num_samples=config["sample"].get("batch_size", 0), seed=i)
|
| 176 |
+
|
| 177 |
+
i += 1
|
| 178 |
+
|
| 179 |
+
X_num_t, X_cat_t, y_t = lib.read_pure_data(parent_dir)
|
| 180 |
+
dists = privacy_metrics(config["real_data_path"], parent_dir)
|
| 181 |
+
to_drop = np.where(dists < q10)
|
| 182 |
+
X_num_t = np.delete(X_num_t, to_drop, axis=0)
|
| 183 |
+
X_cat_t = np.delete(X_cat_t, to_drop, axis=0) if X_cat is not None else None
|
| 184 |
+
y_t = np.delete(y_t, to_drop, axis=0)
|
| 185 |
+
|
| 186 |
+
X_num = np.concatenate([X_num, X_num_t], axis=0)[:num_samples]
|
| 187 |
+
X_cat = np.concatenate([X_cat, X_cat_t], axis=0)[:num_samples] if X_cat is not None else None
|
| 188 |
+
y = np.concatenate([y, y_t], axis=0)[:num_samples]
|
| 189 |
+
|
| 190 |
+
# np.save(os.path.join(parent_dir, 'X_num_train'), X_num)
|
| 191 |
+
# if X_cat is not None:
|
| 192 |
+
# np.save(os.path.join(parent_dir, 'X_cat_train'), X_cat)
|
| 193 |
+
# np.save(os.path.join(parent_dir, 'y_train'), y)
|
| 194 |
+
|
| 195 |
+
np.save(os.path.join(parent_dir, 'X_num_train'), X_num)
|
| 196 |
+
if X_cat is not None:
|
| 197 |
+
np.save(os.path.join(parent_dir, 'X_cat_train'), X_cat)
|
| 198 |
+
np.save(os.path.join(parent_dir, 'y_train'), y)
|
| 199 |
+
|
| 200 |
+
new_dists = privacy_metrics(config["real_data_path"], parent_dir)
|
| 201 |
+
|
| 202 |
+
res = eval_seeds(
|
| 203 |
+
config,
|
| 204 |
+
n_seeds=10,
|
| 205 |
+
eval_type="synthetic",
|
| 206 |
+
model_type="catboost",
|
| 207 |
+
n_datasets=1,
|
| 208 |
+
dump=False
|
| 209 |
+
)
|
| 210 |
+
print(f"Old: {old_privacy:.4f}, New: {np.median(new_dists):.4f}")
|
| 211 |
+
|
| 212 |
+
metric = "r2-mean" if "r2-mean" in res["test"] else "f1-mean"
|
| 213 |
+
return res["test"][metric], np.around(np.median(new_dists), 4)
|
| 214 |
+
|
| 215 |
+
def resample_privacy_qs(config_path, method):
|
| 216 |
+
config = lib.load_config(config_path)
|
| 217 |
+
scores = []
|
| 218 |
+
privacies = []
|
| 219 |
+
|
| 220 |
+
eval_res = lib.load_json(Path(config["parent_dir"]) / "eval_catboost.json")["synthetic"]["test"]
|
| 221 |
+
metric = "r2-mean" if "r2-mean" in eval_res else "f1-mean"
|
| 222 |
+
scores.append(eval_res[metric])
|
| 223 |
+
privacies.append(np.median(privacy_metrics(config["real_data_path"], config["parent_dir"])))
|
| 224 |
+
|
| 225 |
+
for q in [0.1, 0.2, 0.3, 0.4]:
|
| 226 |
+
score, privacy = resample_privacy(config_path, method, q)
|
| 227 |
+
scores.append(score)
|
| 228 |
+
privacies.append(privacy)
|
| 229 |
+
|
| 230 |
+
lib.dump_json(
|
| 231 |
+
{"scores": scores, "privacies": privacies},
|
| 232 |
+
Path(config["parent_dir"]) / "privacies.json"
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
def calc_privacy(config_path, method, seed=0):
|
| 236 |
+
config = lib.load_config(config_path)
|
| 237 |
+
sample_wrapper(method, config, num_samples=config["sample"]["num_samples"], seed=seed)
|
| 238 |
+
timer = zero.Timer()
|
| 239 |
+
timer.run()
|
| 240 |
+
dists = privacy_metrics(config["real_data_path"], config["parent_dir"])
|
| 241 |
+
privacy_val = np.median(dists)
|
| 242 |
+
lib.dump_json({"privacy": privacy_val}, os.path.join(config["parent_dir"], "privacy.json"))
|
| 243 |
+
print(f"Elapsed tine:{str(timer)}")
|
| 244 |
+
|
| 245 |
+
def main():
|
| 246 |
+
parser = argparse.ArgumentParser()
|
| 247 |
+
parser.add_argument('--config', metavar='FILE')
|
| 248 |
+
parser.add_argument('method', type=str)
|
| 249 |
+
args = parser.parse_args()
|
| 250 |
+
|
| 251 |
+
calc_privacy(
|
| 252 |
+
args.config,
|
| 253 |
+
args.method
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
if __name__ == "__main__":
|
| 257 |
+
main()
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/sample.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import numpy as np
|
| 3 |
+
import zero
|
| 4 |
+
import os
|
| 5 |
+
from tab_ddpm.gaussian_multinomial_diffsuion import GaussianMultinomialDiffusion
|
| 6 |
+
from tab_ddpm.utils import FoundNANsError
|
| 7 |
+
from scripts.utils_train import get_model, make_dataset
|
| 8 |
+
from lib import round_columns
|
| 9 |
+
import lib
|
| 10 |
+
|
| 11 |
+
def to_good_ohe(ohe, X):
|
| 12 |
+
indices = np.cumsum([0] + ohe._n_features_outs)
|
| 13 |
+
Xres = []
|
| 14 |
+
for i in range(1, len(indices)):
|
| 15 |
+
x_ = np.max(X[:, indices[i - 1]:indices[i]], axis=1)
|
| 16 |
+
t = X[:, indices[i - 1]:indices[i]] - x_.reshape(-1, 1)
|
| 17 |
+
Xres.append(np.where(t >= 0, 1, 0))
|
| 18 |
+
return np.hstack(Xres)
|
| 19 |
+
|
| 20 |
+
def sample(
|
| 21 |
+
parent_dir,
|
| 22 |
+
real_data_path = 'data/higgs-small',
|
| 23 |
+
batch_size = 2000,
|
| 24 |
+
num_samples = 0,
|
| 25 |
+
model_type = 'mlp',
|
| 26 |
+
model_params = None,
|
| 27 |
+
model_path = None,
|
| 28 |
+
num_timesteps = 1000,
|
| 29 |
+
gaussian_loss_type = 'mse',
|
| 30 |
+
scheduler = 'cosine',
|
| 31 |
+
T_dict = None,
|
| 32 |
+
num_numerical_features = 0,
|
| 33 |
+
disbalance = None,
|
| 34 |
+
device = torch.device('cuda:1'),
|
| 35 |
+
seed = 0,
|
| 36 |
+
change_val = False
|
| 37 |
+
):
|
| 38 |
+
zero.improve_reproducibility(seed)
|
| 39 |
+
|
| 40 |
+
T = lib.Transformations(**T_dict)
|
| 41 |
+
D = make_dataset(
|
| 42 |
+
real_data_path,
|
| 43 |
+
T,
|
| 44 |
+
num_classes=model_params['num_classes'],
|
| 45 |
+
is_y_cond=model_params['is_y_cond'],
|
| 46 |
+
change_val=change_val
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
K = np.array(D.get_category_sizes('train'))
|
| 50 |
+
if len(K) == 0 or T_dict['cat_encoding'] == 'one-hot':
|
| 51 |
+
K = np.array([0])
|
| 52 |
+
|
| 53 |
+
num_numerical_features_ = D.X_num['train'].shape[1] if D.X_num is not None else 0
|
| 54 |
+
d_in = np.sum(K) + num_numerical_features_
|
| 55 |
+
model_params['d_in'] = int(d_in)
|
| 56 |
+
model = get_model(
|
| 57 |
+
model_type,
|
| 58 |
+
model_params,
|
| 59 |
+
num_numerical_features_,
|
| 60 |
+
category_sizes=D.get_category_sizes('train')
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
model.load_state_dict(
|
| 64 |
+
torch.load(model_path, map_location="cpu")
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
diffusion = GaussianMultinomialDiffusion(
|
| 68 |
+
K,
|
| 69 |
+
num_numerical_features=num_numerical_features_,
|
| 70 |
+
denoise_fn=model, num_timesteps=num_timesteps,
|
| 71 |
+
gaussian_loss_type=gaussian_loss_type, scheduler=scheduler, device=device
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
diffusion.to(device)
|
| 75 |
+
diffusion.eval()
|
| 76 |
+
|
| 77 |
+
_, empirical_class_dist = torch.unique(torch.from_numpy(D.y['train']), return_counts=True)
|
| 78 |
+
# empirical_class_dist = empirical_class_dist.float() + torch.tensor([-5000., 10000.]).float()
|
| 79 |
+
if disbalance == 'fix':
|
| 80 |
+
empirical_class_dist[0], empirical_class_dist[1] = empirical_class_dist[1], empirical_class_dist[0]
|
| 81 |
+
x_gen, y_gen = diffusion.sample_all(num_samples, batch_size, empirical_class_dist.float(), ddim=False)
|
| 82 |
+
|
| 83 |
+
elif disbalance == 'fill':
|
| 84 |
+
ix_major = empirical_class_dist.argmax().item()
|
| 85 |
+
val_major = empirical_class_dist[ix_major].item()
|
| 86 |
+
x_gen, y_gen = [], []
|
| 87 |
+
for i in range(empirical_class_dist.shape[0]):
|
| 88 |
+
if i == ix_major:
|
| 89 |
+
continue
|
| 90 |
+
distrib = torch.zeros_like(empirical_class_dist)
|
| 91 |
+
distrib[i] = 1
|
| 92 |
+
num_samples = val_major - empirical_class_dist[i].item()
|
| 93 |
+
x_temp, y_temp = diffusion.sample_all(num_samples, batch_size, distrib.float(), ddim=False)
|
| 94 |
+
x_gen.append(x_temp)
|
| 95 |
+
y_gen.append(y_temp)
|
| 96 |
+
|
| 97 |
+
x_gen = torch.cat(x_gen, dim=0)
|
| 98 |
+
y_gen = torch.cat(y_gen, dim=0)
|
| 99 |
+
|
| 100 |
+
else:
|
| 101 |
+
x_gen, y_gen = diffusion.sample_all(num_samples, batch_size, empirical_class_dist.float(), ddim=False)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
# try:
|
| 105 |
+
# except FoundNANsError as ex:
|
| 106 |
+
# print("Found NaNs during sampling!")
|
| 107 |
+
# loader = lib.prepare_fast_dataloader(D, 'train', 8)
|
| 108 |
+
# x_gen = next(loader)[0]
|
| 109 |
+
# y_gen = torch.multinomial(
|
| 110 |
+
# empirical_class_dist.float(),
|
| 111 |
+
# num_samples=8,
|
| 112 |
+
# replacement=True
|
| 113 |
+
# )
|
| 114 |
+
X_gen, y_gen = x_gen.numpy(), y_gen.numpy()
|
| 115 |
+
|
| 116 |
+
###
|
| 117 |
+
# X_num_unnorm = X_gen[:, :num_numerical_features]
|
| 118 |
+
# lo = np.percentile(X_num_unnorm, 2.5, axis=0)
|
| 119 |
+
# hi = np.percentile(X_num_unnorm, 97.5, axis=0)
|
| 120 |
+
# idx = (lo < X_num_unnorm) & (hi > X_num_unnorm)
|
| 121 |
+
# X_gen = X_gen[np.all(idx, axis=1)]
|
| 122 |
+
# y_gen = y_gen[np.all(idx, axis=1)]
|
| 123 |
+
###
|
| 124 |
+
|
| 125 |
+
num_numerical_features = num_numerical_features + int(D.is_regression and not model_params["is_y_cond"])
|
| 126 |
+
|
| 127 |
+
X_num_ = X_gen
|
| 128 |
+
if num_numerical_features < X_gen.shape[1]:
|
| 129 |
+
np.save(os.path.join(parent_dir, 'X_cat_unnorm'), X_gen[:, num_numerical_features:])
|
| 130 |
+
# _, _, cat_encoder = lib.cat_encode({'train': X_cat_real}, T_dict['cat_encoding'], y_real, T_dict['seed'], True)
|
| 131 |
+
if T_dict['cat_encoding'] == 'one-hot':
|
| 132 |
+
X_gen[:, num_numerical_features:] = to_good_ohe(D.cat_transform.steps[0][1], X_num_[:, num_numerical_features:])
|
| 133 |
+
X_cat = D.cat_transform.inverse_transform(X_gen[:, num_numerical_features:])
|
| 134 |
+
|
| 135 |
+
if num_numerical_features_ != 0:
|
| 136 |
+
# _, normalize = lib.normalize({'train' : X_num_real}, T_dict['normalization'], T_dict['seed'], True)
|
| 137 |
+
np.save(os.path.join(parent_dir, 'X_num_unnorm'), X_gen[:, :num_numerical_features])
|
| 138 |
+
X_num_ = D.num_transform.inverse_transform(X_gen[:, :num_numerical_features])
|
| 139 |
+
X_num = X_num_[:, :num_numerical_features]
|
| 140 |
+
|
| 141 |
+
X_num_real = np.load(os.path.join(real_data_path, "X_num_train.npy"), allow_pickle=True)
|
| 142 |
+
disc_cols = []
|
| 143 |
+
for col in range(X_num_real.shape[1]):
|
| 144 |
+
uniq_vals = np.unique(X_num_real[:, col])
|
| 145 |
+
if len(uniq_vals) <= 32 and ((uniq_vals - np.round(uniq_vals)) == 0).all():
|
| 146 |
+
disc_cols.append(col)
|
| 147 |
+
print("Discrete cols:", disc_cols)
|
| 148 |
+
# 仅当 regression 且 y 在 X_num 中(非 is_y_cond)时才提取 y;否则 y_gen 已由 sample_all 返回
|
| 149 |
+
if model_params['num_classes'] == 0 and not model_params.get('is_y_cond', True):
|
| 150 |
+
y_gen = X_num[:, 0]
|
| 151 |
+
X_num = X_num[:, 1:]
|
| 152 |
+
if len(disc_cols):
|
| 153 |
+
X_num = round_columns(X_num_real, X_num, disc_cols)
|
| 154 |
+
|
| 155 |
+
if num_numerical_features != 0:
|
| 156 |
+
print("Num shape: ", X_num.shape)
|
| 157 |
+
np.save(os.path.join(parent_dir, 'X_num_train'), X_num)
|
| 158 |
+
if num_numerical_features < X_gen.shape[1]:
|
| 159 |
+
np.save(os.path.join(parent_dir, 'X_cat_train'), X_cat)
|
| 160 |
+
np.save(os.path.join(parent_dir, 'y_train'), y_gen)
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/train.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from copy import deepcopy
|
| 2 |
+
import torch
|
| 3 |
+
import os
|
| 4 |
+
import numpy as np
|
| 5 |
+
import zero
|
| 6 |
+
from tab_ddpm import GaussianMultinomialDiffusion
|
| 7 |
+
from scripts.utils_train import get_model, make_dataset, update_ema
|
| 8 |
+
import lib
|
| 9 |
+
import pandas as pd
|
| 10 |
+
|
| 11 |
+
class Trainer:
|
| 12 |
+
def __init__(self, diffusion, train_iter, lr, weight_decay, steps, device=torch.device('cuda:1')):
|
| 13 |
+
self.diffusion = diffusion
|
| 14 |
+
self.ema_model = deepcopy(self.diffusion._denoise_fn)
|
| 15 |
+
for param in self.ema_model.parameters():
|
| 16 |
+
param.detach_()
|
| 17 |
+
|
| 18 |
+
self.train_iter = train_iter
|
| 19 |
+
self.steps = steps
|
| 20 |
+
self.init_lr = lr
|
| 21 |
+
self.optimizer = torch.optim.AdamW(self.diffusion.parameters(), lr=lr, weight_decay=weight_decay)
|
| 22 |
+
self.device = device
|
| 23 |
+
self.loss_history = pd.DataFrame(columns=['step', 'mloss', 'gloss', 'loss'])
|
| 24 |
+
self.log_every = 100
|
| 25 |
+
self.print_every = 500
|
| 26 |
+
self.ema_every = 1000
|
| 27 |
+
|
| 28 |
+
def _anneal_lr(self, step):
|
| 29 |
+
frac_done = step / self.steps
|
| 30 |
+
lr = self.init_lr * (1 - frac_done)
|
| 31 |
+
for param_group in self.optimizer.param_groups:
|
| 32 |
+
param_group["lr"] = lr
|
| 33 |
+
|
| 34 |
+
def _run_step(self, x, out_dict):
|
| 35 |
+
x = x.to(self.device)
|
| 36 |
+
for k in out_dict:
|
| 37 |
+
out_dict[k] = out_dict[k].long().to(self.device)
|
| 38 |
+
self.optimizer.zero_grad()
|
| 39 |
+
loss_multi, loss_gauss = self.diffusion.mixed_loss(x, out_dict)
|
| 40 |
+
loss = loss_multi + loss_gauss
|
| 41 |
+
loss.backward()
|
| 42 |
+
self.optimizer.step()
|
| 43 |
+
|
| 44 |
+
return loss_multi, loss_gauss
|
| 45 |
+
|
| 46 |
+
def run_loop(self):
|
| 47 |
+
step = 0
|
| 48 |
+
curr_loss_multi = 0.0
|
| 49 |
+
curr_loss_gauss = 0.0
|
| 50 |
+
|
| 51 |
+
curr_count = 0
|
| 52 |
+
while step < self.steps:
|
| 53 |
+
x, out_dict = next(self.train_iter)
|
| 54 |
+
out_dict = {'y': out_dict}
|
| 55 |
+
batch_loss_multi, batch_loss_gauss = self._run_step(x, out_dict)
|
| 56 |
+
|
| 57 |
+
self._anneal_lr(step)
|
| 58 |
+
|
| 59 |
+
curr_count += len(x)
|
| 60 |
+
curr_loss_multi += batch_loss_multi.item() * len(x)
|
| 61 |
+
curr_loss_gauss += batch_loss_gauss.item() * len(x)
|
| 62 |
+
|
| 63 |
+
if (step + 1) % self.log_every == 0:
|
| 64 |
+
mloss = np.around(curr_loss_multi / curr_count, 4)
|
| 65 |
+
gloss = np.around(curr_loss_gauss / curr_count, 4)
|
| 66 |
+
if (step + 1) % self.print_every == 0:
|
| 67 |
+
print(f'Step {(step + 1)}/{self.steps} MLoss: {mloss} GLoss: {gloss} Sum: {mloss + gloss}')
|
| 68 |
+
self.loss_history.loc[len(self.loss_history)] =[step + 1, mloss, gloss, mloss + gloss]
|
| 69 |
+
curr_count = 0
|
| 70 |
+
curr_loss_gauss = 0.0
|
| 71 |
+
curr_loss_multi = 0.0
|
| 72 |
+
|
| 73 |
+
update_ema(self.ema_model.parameters(), self.diffusion._denoise_fn.parameters())
|
| 74 |
+
|
| 75 |
+
step += 1
|
| 76 |
+
|
| 77 |
+
def train(
|
| 78 |
+
parent_dir,
|
| 79 |
+
real_data_path = 'data/higgs-small',
|
| 80 |
+
steps = 1000,
|
| 81 |
+
lr = 0.002,
|
| 82 |
+
weight_decay = 1e-4,
|
| 83 |
+
batch_size = 1024,
|
| 84 |
+
model_type = 'mlp',
|
| 85 |
+
model_params = None,
|
| 86 |
+
num_timesteps = 1000,
|
| 87 |
+
gaussian_loss_type = 'mse',
|
| 88 |
+
scheduler = 'cosine',
|
| 89 |
+
T_dict = None,
|
| 90 |
+
num_numerical_features = 0,
|
| 91 |
+
device = torch.device('cuda:1'),
|
| 92 |
+
seed = 0,
|
| 93 |
+
change_val = False
|
| 94 |
+
):
|
| 95 |
+
real_data_path = os.path.normpath(real_data_path)
|
| 96 |
+
parent_dir = os.path.normpath(parent_dir)
|
| 97 |
+
|
| 98 |
+
zero.improve_reproducibility(seed)
|
| 99 |
+
|
| 100 |
+
T = lib.Transformations(**T_dict)
|
| 101 |
+
|
| 102 |
+
dataset = make_dataset(
|
| 103 |
+
real_data_path,
|
| 104 |
+
T,
|
| 105 |
+
num_classes=model_params['num_classes'],
|
| 106 |
+
is_y_cond=model_params['is_y_cond'],
|
| 107 |
+
change_val=change_val
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
K = np.array(dataset.get_category_sizes('train'))
|
| 111 |
+
if len(K) == 0 or T_dict['cat_encoding'] == 'one-hot':
|
| 112 |
+
K = np.array([0])
|
| 113 |
+
print(K)
|
| 114 |
+
|
| 115 |
+
num_numerical_features = dataset.X_num['train'].shape[1] if dataset.X_num is not None else 0
|
| 116 |
+
d_in = np.sum(K) + num_numerical_features
|
| 117 |
+
model_params['d_in'] = d_in
|
| 118 |
+
print(d_in)
|
| 119 |
+
|
| 120 |
+
print(model_params)
|
| 121 |
+
model = get_model(
|
| 122 |
+
model_type,
|
| 123 |
+
model_params,
|
| 124 |
+
num_numerical_features,
|
| 125 |
+
category_sizes=dataset.get_category_sizes('train')
|
| 126 |
+
)
|
| 127 |
+
model.to(device)
|
| 128 |
+
|
| 129 |
+
# train_loader = lib.prepare_beton_loader(dataset, split='train', batch_size=batch_size)
|
| 130 |
+
train_loader = lib.prepare_fast_dataloader(dataset, split='train', batch_size=batch_size)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
diffusion = GaussianMultinomialDiffusion(
|
| 135 |
+
num_classes=K,
|
| 136 |
+
num_numerical_features=num_numerical_features,
|
| 137 |
+
denoise_fn=model,
|
| 138 |
+
gaussian_loss_type=gaussian_loss_type,
|
| 139 |
+
num_timesteps=num_timesteps,
|
| 140 |
+
scheduler=scheduler,
|
| 141 |
+
device=device
|
| 142 |
+
)
|
| 143 |
+
diffusion.to(device)
|
| 144 |
+
diffusion.train()
|
| 145 |
+
|
| 146 |
+
trainer = Trainer(
|
| 147 |
+
diffusion,
|
| 148 |
+
train_loader,
|
| 149 |
+
lr=lr,
|
| 150 |
+
weight_decay=weight_decay,
|
| 151 |
+
steps=steps,
|
| 152 |
+
device=device
|
| 153 |
+
)
|
| 154 |
+
trainer.run_loop()
|
| 155 |
+
|
| 156 |
+
trainer.loss_history.to_csv(os.path.join(parent_dir, 'loss.csv'), index=False)
|
| 157 |
+
torch.save(diffusion._denoise_fn.state_dict(), os.path.join(parent_dir, 'model.pt'))
|
| 158 |
+
torch.save(trainer.ema_model.state_dict(), os.path.join(parent_dir, 'model_ema.pt'))
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/tune_ddpm.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import subprocess
|
| 2 |
+
import lib
|
| 3 |
+
import os
|
| 4 |
+
import optuna
|
| 5 |
+
from copy import deepcopy
|
| 6 |
+
import shutil
|
| 7 |
+
import argparse
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
parser = argparse.ArgumentParser()
|
| 11 |
+
parser.add_argument('ds_name', type=str)
|
| 12 |
+
parser.add_argument('train_size', type=int)
|
| 13 |
+
parser.add_argument('eval_type', type=str)
|
| 14 |
+
parser.add_argument('eval_model', type=str)
|
| 15 |
+
parser.add_argument('prefix', type=str)
|
| 16 |
+
parser.add_argument('--eval_seeds', action='store_true', default=False)
|
| 17 |
+
|
| 18 |
+
args = parser.parse_args()
|
| 19 |
+
train_size = args.train_size
|
| 20 |
+
ds_name = args.ds_name
|
| 21 |
+
eval_type = args.eval_type
|
| 22 |
+
assert eval_type in ('merged', 'synthetic')
|
| 23 |
+
prefix = str(args.prefix)
|
| 24 |
+
|
| 25 |
+
pipeline = f'scripts/pipeline.py'
|
| 26 |
+
base_config_path = f'exp/{ds_name}/config.toml'
|
| 27 |
+
parent_path = Path(f'exp/{ds_name}/')
|
| 28 |
+
exps_path = Path(f'exp/{ds_name}/many-exps/') # temporary dir. maybe will be replaced with tempdiвdr
|
| 29 |
+
eval_seeds = f'scripts/eval_seeds.py'
|
| 30 |
+
|
| 31 |
+
os.makedirs(exps_path, exist_ok=True)
|
| 32 |
+
|
| 33 |
+
def _suggest_mlp_layers(trial):
|
| 34 |
+
def suggest_dim(name):
|
| 35 |
+
t = trial.suggest_int(name, d_min, d_max)
|
| 36 |
+
return 2 ** t
|
| 37 |
+
min_n_layers, max_n_layers, d_min, d_max = 1, 4, 7, 10
|
| 38 |
+
n_layers = 2 * trial.suggest_int('n_layers', min_n_layers, max_n_layers)
|
| 39 |
+
d_first = [suggest_dim('d_first')] if n_layers else []
|
| 40 |
+
d_middle = (
|
| 41 |
+
[suggest_dim('d_middle')] * (n_layers - 2)
|
| 42 |
+
if n_layers > 2
|
| 43 |
+
else []
|
| 44 |
+
)
|
| 45 |
+
d_last = [suggest_dim('d_last')] if n_layers > 1 else []
|
| 46 |
+
d_layers = d_first + d_middle + d_last
|
| 47 |
+
return d_layers
|
| 48 |
+
|
| 49 |
+
def objective(trial):
|
| 50 |
+
|
| 51 |
+
lr = trial.suggest_loguniform('lr', 0.00001, 0.003)
|
| 52 |
+
d_layers = _suggest_mlp_layers(trial)
|
| 53 |
+
weight_decay = 0.0
|
| 54 |
+
batch_size = trial.suggest_categorical('batch_size', [256, 4096])
|
| 55 |
+
steps = trial.suggest_categorical('steps', [5000, 20000, 30000])
|
| 56 |
+
# steps = trial.suggest_categorical('steps', [500]) # for debug
|
| 57 |
+
gaussian_loss_type = 'mse'
|
| 58 |
+
# scheduler = trial.suggest_categorical('scheduler', ['cosine', 'linear'])
|
| 59 |
+
num_timesteps = trial.suggest_categorical('num_timesteps', [100, 1000])
|
| 60 |
+
num_samples = int(train_size * (2 ** trial.suggest_int('num_samples', -2, 1)))
|
| 61 |
+
|
| 62 |
+
base_config = lib.load_config(base_config_path)
|
| 63 |
+
|
| 64 |
+
base_config['train']['main']['lr'] = lr
|
| 65 |
+
base_config['train']['main']['steps'] = steps
|
| 66 |
+
base_config['train']['main']['batch_size'] = batch_size
|
| 67 |
+
base_config['train']['main']['weight_decay'] = weight_decay
|
| 68 |
+
base_config['model_params']['rtdl_params']['d_layers'] = d_layers
|
| 69 |
+
base_config['eval']['type']['eval_type'] = eval_type
|
| 70 |
+
base_config['sample']['num_samples'] = num_samples
|
| 71 |
+
base_config['diffusion_params']['gaussian_loss_type'] = gaussian_loss_type
|
| 72 |
+
base_config['diffusion_params']['num_timesteps'] = num_timesteps
|
| 73 |
+
# base_config['diffusion_params']['scheduler'] = scheduler
|
| 74 |
+
|
| 75 |
+
base_config['parent_dir'] = str(exps_path / f"{trial.number}")
|
| 76 |
+
base_config['eval']['type']['eval_model'] = args.eval_model
|
| 77 |
+
if args.eval_model == "mlp":
|
| 78 |
+
base_config['eval']['T']['normalization'] = "quantile"
|
| 79 |
+
base_config['eval']['T']['cat_encoding'] = "one-hot"
|
| 80 |
+
|
| 81 |
+
trial.set_user_attr("config", base_config)
|
| 82 |
+
|
| 83 |
+
lib.dump_config(base_config, exps_path / 'config.toml')
|
| 84 |
+
|
| 85 |
+
subprocess.run(['python3.9', f'{pipeline}', '--config', f'{exps_path / "config.toml"}', '--train', '--change_val'], check=True)
|
| 86 |
+
|
| 87 |
+
n_datasets = 5
|
| 88 |
+
score = 0.0
|
| 89 |
+
|
| 90 |
+
for sample_seed in range(n_datasets):
|
| 91 |
+
base_config['sample']['seed'] = sample_seed
|
| 92 |
+
lib.dump_config(base_config, exps_path / 'config.toml')
|
| 93 |
+
|
| 94 |
+
subprocess.run(['python3.9', f'{pipeline}', '--config', f'{exps_path / "config.toml"}', '--sample', '--eval', '--change_val'], check=True)
|
| 95 |
+
|
| 96 |
+
report_path = str(Path(base_config['parent_dir']) / f'results_{args.eval_model}.json')
|
| 97 |
+
report = lib.load_json(report_path)
|
| 98 |
+
|
| 99 |
+
if 'r2' in report['metrics']['val']:
|
| 100 |
+
score += report['metrics']['val']['r2']
|
| 101 |
+
else:
|
| 102 |
+
score += report['metrics']['val']['macro avg']['f1-score']
|
| 103 |
+
|
| 104 |
+
shutil.rmtree(exps_path / f"{trial.number}")
|
| 105 |
+
|
| 106 |
+
return score / n_datasets
|
| 107 |
+
|
| 108 |
+
study = optuna.create_study(
|
| 109 |
+
direction='maximize',
|
| 110 |
+
sampler=optuna.samplers.TPESampler(seed=0),
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
study.optimize(objective, n_trials=50, show_progress_bar=True)
|
| 114 |
+
|
| 115 |
+
best_config_path = parent_path / f'{prefix}_best/config.toml'
|
| 116 |
+
best_config = study.best_trial.user_attrs['config']
|
| 117 |
+
best_config["parent_dir"] = str(parent_path / f'{prefix}_best/')
|
| 118 |
+
|
| 119 |
+
os.makedirs(parent_path / f'{prefix}_best', exist_ok=True)
|
| 120 |
+
lib.dump_config(best_config, best_config_path)
|
| 121 |
+
lib.dump_json(optuna.importance.get_param_importances(study), parent_path / f'{prefix}_best/importance.json')
|
| 122 |
+
|
| 123 |
+
subprocess.run(['python3.9', f'{pipeline}', '--config', f'{best_config_path}', '--train', '--sample'], check=True)
|
| 124 |
+
|
| 125 |
+
if args.eval_seeds:
|
| 126 |
+
best_exp = str(parent_path / f'{prefix}_best/config.toml')
|
| 127 |
+
subprocess.run(['python3.9', f'{eval_seeds}', '--config', f'{best_exp}', '10', "ddpm", eval_type, args.eval_model, '5'], check=True)
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/tune_evaluation_model.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import optuna
|
| 2 |
+
import lib
|
| 3 |
+
import argparse
|
| 4 |
+
from eval_catboost import train_catboost
|
| 5 |
+
from eval_mlp import train_mlp
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
parser = argparse.ArgumentParser()
|
| 9 |
+
parser.add_argument('ds_name', type=str)
|
| 10 |
+
parser.add_argument('model', type=str)
|
| 11 |
+
parser.add_argument('tune_type', type=str)
|
| 12 |
+
parser.add_argument('device', type=str)
|
| 13 |
+
|
| 14 |
+
args = parser.parse_args()
|
| 15 |
+
data_path = Path(f"data/{args.ds_name}")
|
| 16 |
+
best_params = None
|
| 17 |
+
|
| 18 |
+
assert args.tune_type in ("cv", "val")
|
| 19 |
+
|
| 20 |
+
def _suggest(trial: optuna.trial.Trial, distribution: str, label: str, *args):
|
| 21 |
+
return getattr(trial, f'suggest_{distribution}')(label, *args)
|
| 22 |
+
|
| 23 |
+
def _suggest_optional(trial: optuna.trial.Trial, distribution: str, label: str, *args):
|
| 24 |
+
if trial.suggest_categorical(f"optional_{label}", [True, False]):
|
| 25 |
+
return _suggest(trial, distribution, label, *args)
|
| 26 |
+
else:
|
| 27 |
+
return 0.0
|
| 28 |
+
|
| 29 |
+
def _suggest_mlp_layers(trial: optuna.trial.Trial, mlp_d_layers: list[int]):
|
| 30 |
+
|
| 31 |
+
min_n_layers, max_n_layers = mlp_d_layers[0], mlp_d_layers[1]
|
| 32 |
+
d_min, d_max = mlp_d_layers[2], mlp_d_layers[3]
|
| 33 |
+
|
| 34 |
+
def suggest_dim(name):
|
| 35 |
+
t = trial.suggest_int(name, d_min, d_max)
|
| 36 |
+
return 2 ** t
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
n_layers = trial.suggest_int('n_layers', min_n_layers, max_n_layers)
|
| 40 |
+
d_first = [suggest_dim('d_first')] if n_layers else []
|
| 41 |
+
d_middle = (
|
| 42 |
+
[suggest_dim('d_middle')] * (n_layers - 2)
|
| 43 |
+
if n_layers > 2
|
| 44 |
+
else []
|
| 45 |
+
)
|
| 46 |
+
d_last = [suggest_dim('d_last')] if n_layers > 1 else []
|
| 47 |
+
d_layers = d_first + d_middle + d_last
|
| 48 |
+
|
| 49 |
+
return d_layers
|
| 50 |
+
|
| 51 |
+
def suggest_mlp_params(trial):
|
| 52 |
+
params = {}
|
| 53 |
+
params["lr"] = trial.suggest_loguniform("lr", 5e-5, 0.005)
|
| 54 |
+
params["dropout"] = _suggest_optional(trial, "uniform", "dropout", 0.0, 0.5)
|
| 55 |
+
params["weight_decay"] = _suggest_optional(trial, "loguniform", "weight_decay", 1e-6, 1e-2)
|
| 56 |
+
params["d_layers"] = _suggest_mlp_layers(trial, [1, 8, 6, 10])
|
| 57 |
+
|
| 58 |
+
return params
|
| 59 |
+
|
| 60 |
+
def suggest_catboost_params(trial):
|
| 61 |
+
params = {}
|
| 62 |
+
params["learning_rate"] = trial.suggest_loguniform("learning_rate", 0.001, 1.0)
|
| 63 |
+
params["depth"] = trial.suggest_int("depth", 3, 10)
|
| 64 |
+
params["l2_leaf_reg"] = trial.suggest_uniform("l2_leaf_reg", 0.1, 10.0)
|
| 65 |
+
params["bagging_temperature"] = trial.suggest_uniform("bagging_temperature", 0.0, 1.0)
|
| 66 |
+
params["leaf_estimation_iterations"] = trial.suggest_int("leaf_estimation_iterations", 1, 10)
|
| 67 |
+
|
| 68 |
+
params = params | {
|
| 69 |
+
"iterations": 2000,
|
| 70 |
+
"early_stopping_rounds": 50,
|
| 71 |
+
"od_pval": 0.001,
|
| 72 |
+
"task_type": "CPU", # "GPU", may affect performance
|
| 73 |
+
"thread_count": 4,
|
| 74 |
+
# "devices": "0", # for GPU
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
return params
|
| 78 |
+
|
| 79 |
+
def objective(trial):
|
| 80 |
+
if args.model == "mlp":
|
| 81 |
+
params = suggest_mlp_params(trial)
|
| 82 |
+
train_func = train_mlp
|
| 83 |
+
T_dict = {
|
| 84 |
+
"seed": 0,
|
| 85 |
+
"normalization": "quantile",
|
| 86 |
+
"num_nan_policy": None,
|
| 87 |
+
"cat_nan_policy": None,
|
| 88 |
+
"cat_min_frequency": None,
|
| 89 |
+
"cat_encoding": "one-hot",
|
| 90 |
+
"y_policy": "default"
|
| 91 |
+
}
|
| 92 |
+
else:
|
| 93 |
+
params = suggest_catboost_params(trial)
|
| 94 |
+
train_func = train_catboost
|
| 95 |
+
T_dict = {
|
| 96 |
+
"seed": 0,
|
| 97 |
+
"normalization": None,
|
| 98 |
+
"num_nan_policy": None,
|
| 99 |
+
"cat_nan_policy": None,
|
| 100 |
+
"cat_min_frequency": None,
|
| 101 |
+
"cat_encoding": None,
|
| 102 |
+
"y_policy": "default"
|
| 103 |
+
}
|
| 104 |
+
trial.set_user_attr("params", params)
|
| 105 |
+
if args.tune_type == "cv":
|
| 106 |
+
score = 0.0
|
| 107 |
+
for fold in range(5):
|
| 108 |
+
metrics_report = train_func(
|
| 109 |
+
parent_dir=None,
|
| 110 |
+
real_data_path=data_path / f"kfolds/{fold}",
|
| 111 |
+
eval_type="real",
|
| 112 |
+
T_dict=T_dict,
|
| 113 |
+
params=params,
|
| 114 |
+
change_val=False,
|
| 115 |
+
device=args.device
|
| 116 |
+
)
|
| 117 |
+
score += metrics_report.get_val_score()
|
| 118 |
+
score /= 5
|
| 119 |
+
|
| 120 |
+
elif args.tune_type == "val":
|
| 121 |
+
metrics_report = train_func(
|
| 122 |
+
parent_dir=None,
|
| 123 |
+
real_data_path=data_path,
|
| 124 |
+
eval_type="real",
|
| 125 |
+
T_dict=T_dict,
|
| 126 |
+
params=params,
|
| 127 |
+
change_val=False,
|
| 128 |
+
device=args.device
|
| 129 |
+
)
|
| 130 |
+
score = metrics_report.get_val_score()
|
| 131 |
+
|
| 132 |
+
return score
|
| 133 |
+
|
| 134 |
+
study = optuna.create_study(
|
| 135 |
+
direction='maximize',
|
| 136 |
+
sampler=optuna.samplers.TPESampler(seed=0),
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
study.optimize(objective, n_trials=100, show_progress_bar=True)
|
| 140 |
+
|
| 141 |
+
bets_params = study.best_trial.user_attrs['params']
|
| 142 |
+
|
| 143 |
+
best_params_path = f"tuned_models/{args.model}/{args.ds_name}_{args.tune_type}.json"
|
| 144 |
+
|
| 145 |
+
lib.dump_json(bets_params, best_params_path)
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/utils_train.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import os
|
| 3 |
+
import lib
|
| 4 |
+
from tab_ddpm.modules import MLPDiffusion, ResNetDiffusion
|
| 5 |
+
|
| 6 |
+
def get_model(
|
| 7 |
+
model_name,
|
| 8 |
+
model_params,
|
| 9 |
+
n_num_features,
|
| 10 |
+
category_sizes
|
| 11 |
+
):
|
| 12 |
+
print(model_name)
|
| 13 |
+
if model_name == 'mlp':
|
| 14 |
+
model = MLPDiffusion(**model_params)
|
| 15 |
+
elif model_name == 'resnet':
|
| 16 |
+
model = ResNetDiffusion(**model_params)
|
| 17 |
+
else:
|
| 18 |
+
raise "Unknown model!"
|
| 19 |
+
return model
|
| 20 |
+
|
| 21 |
+
def update_ema(target_params, source_params, rate=0.999):
|
| 22 |
+
"""
|
| 23 |
+
Update target parameters to be closer to those of source parameters using
|
| 24 |
+
an exponential moving average.
|
| 25 |
+
:param target_params: the target parameter sequence.
|
| 26 |
+
:param source_params: the source parameter sequence.
|
| 27 |
+
:param rate: the EMA rate (closer to 1 means slower).
|
| 28 |
+
"""
|
| 29 |
+
for targ, src in zip(target_params, source_params):
|
| 30 |
+
targ.detach().mul_(rate).add_(src.detach(), alpha=1 - rate)
|
| 31 |
+
|
| 32 |
+
def concat_y_to_X(X, y):
|
| 33 |
+
if X is None:
|
| 34 |
+
return y.reshape(-1, 1)
|
| 35 |
+
return np.concatenate([y.reshape(-1, 1), X], axis=1)
|
| 36 |
+
|
| 37 |
+
def make_dataset(
|
| 38 |
+
data_path: str,
|
| 39 |
+
T: lib.Transformations,
|
| 40 |
+
num_classes: int,
|
| 41 |
+
is_y_cond: bool,
|
| 42 |
+
change_val: bool
|
| 43 |
+
):
|
| 44 |
+
# classification
|
| 45 |
+
if num_classes > 0:
|
| 46 |
+
X_cat = {} if os.path.exists(os.path.join(data_path, 'X_cat_train.npy')) or not is_y_cond else None
|
| 47 |
+
X_num = {} if os.path.exists(os.path.join(data_path, 'X_num_train.npy')) else None
|
| 48 |
+
y = {}
|
| 49 |
+
|
| 50 |
+
for split in ['train']:
|
| 51 |
+
X_num_t, X_cat_t, y_t = lib.read_pure_data(data_path, split)
|
| 52 |
+
if X_num is not None:
|
| 53 |
+
X_num[split] = X_num_t
|
| 54 |
+
if not is_y_cond:
|
| 55 |
+
X_cat_t = concat_y_to_X(X_cat_t, y_t)
|
| 56 |
+
if X_cat is not None:
|
| 57 |
+
X_cat[split] = X_cat_t
|
| 58 |
+
y[split] = y_t
|
| 59 |
+
else:
|
| 60 |
+
# regression
|
| 61 |
+
X_cat = {} if os.path.exists(os.path.join(data_path, 'X_cat_train.npy')) else None
|
| 62 |
+
X_num = {} if os.path.exists(os.path.join(data_path, 'X_num_train.npy')) or not is_y_cond else None
|
| 63 |
+
y = {}
|
| 64 |
+
|
| 65 |
+
for split in ['train']:
|
| 66 |
+
X_num_t, X_cat_t, y_t = lib.read_pure_data(data_path, split)
|
| 67 |
+
if not is_y_cond:
|
| 68 |
+
X_num_t = concat_y_to_X(X_num_t, y_t)
|
| 69 |
+
if X_num is not None:
|
| 70 |
+
X_num[split] = X_num_t
|
| 71 |
+
if X_cat is not None:
|
| 72 |
+
X_cat[split] = X_cat_t
|
| 73 |
+
y[split] = y_t
|
| 74 |
+
|
| 75 |
+
info = lib.load_json(os.path.join(data_path, 'info.json'))
|
| 76 |
+
|
| 77 |
+
D = lib.Dataset(
|
| 78 |
+
X_num,
|
| 79 |
+
X_cat,
|
| 80 |
+
y,
|
| 81 |
+
y_info={},
|
| 82 |
+
task_type=lib.TaskType(info['task_type']),
|
| 83 |
+
n_classes=info.get('n_classes')
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
if change_val:
|
| 87 |
+
D = lib.change_val(D)
|
| 88 |
+
|
| 89 |
+
return lib.transform_dataset(D, T, None)
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/smote/pipeline_smote.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import tomli
|
| 2 |
+
import shutil
|
| 3 |
+
import os
|
| 4 |
+
import argparse
|
| 5 |
+
from sample_smote import sample_smote
|
| 6 |
+
from scripts.eval_catboost import train_catboost
|
| 7 |
+
# from scripts.eval_mlp import train_mlp
|
| 8 |
+
import zero
|
| 9 |
+
import lib
|
| 10 |
+
|
| 11 |
+
def load_config(path) :
|
| 12 |
+
with open(path, 'rb') as f:
|
| 13 |
+
return tomli.load(f)
|
| 14 |
+
|
| 15 |
+
def save_file(parent_dir, config_path):
|
| 16 |
+
try:
|
| 17 |
+
dst = os.path.join(parent_dir)
|
| 18 |
+
os.makedirs(os.path.dirname(dst), exist_ok=True)
|
| 19 |
+
shutil.copyfile(os.path.abspath(config_path), dst)
|
| 20 |
+
except shutil.SameFileError:
|
| 21 |
+
pass
|
| 22 |
+
|
| 23 |
+
def main():
|
| 24 |
+
parser = argparse.ArgumentParser()
|
| 25 |
+
parser.add_argument('--config', metavar='FILE')
|
| 26 |
+
parser.add_argument('--sample', action='store_true', default=False)
|
| 27 |
+
parser.add_argument('--eval', action='store_true', default=False)
|
| 28 |
+
parser.add_argument('--change_val', action='store_true', default=False)
|
| 29 |
+
|
| 30 |
+
args = parser.parse_args()
|
| 31 |
+
raw_config = lib.load_config(args.config)
|
| 32 |
+
timer = zero.Timer()
|
| 33 |
+
timer.run()
|
| 34 |
+
save_file(os.path.join(raw_config['parent_dir'], 'config.toml'), args.config)
|
| 35 |
+
if args.sample:
|
| 36 |
+
sample_smote(
|
| 37 |
+
parent_dir=raw_config['parent_dir'],
|
| 38 |
+
real_data_path=raw_config['real_data_path'],
|
| 39 |
+
**raw_config['smote_params'],
|
| 40 |
+
seed=raw_config['seed'],
|
| 41 |
+
change_val=args.change_val
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
save_file(os.path.join(raw_config['parent_dir'], 'info.json'), os.path.join(raw_config['real_data_path'], 'info.json'))
|
| 45 |
+
if args.eval:
|
| 46 |
+
if raw_config['eval']['type']['eval_model'] == 'catboost':
|
| 47 |
+
train_catboost(
|
| 48 |
+
parent_dir=raw_config['parent_dir'],
|
| 49 |
+
real_data_path=raw_config['real_data_path'],
|
| 50 |
+
eval_type=raw_config['eval']['type']['eval_type'],
|
| 51 |
+
T_dict=raw_config['eval']['T'],
|
| 52 |
+
seed=raw_config['seed'],
|
| 53 |
+
change_val=args.change_val
|
| 54 |
+
)
|
| 55 |
+
# elif raw_config['eval']['type']['eval_model'] == 'mlp':
|
| 56 |
+
# train_mlp(
|
| 57 |
+
# parent_dir=raw_config['parent_dir'],
|
| 58 |
+
# real_data_path=raw_config['real_data_path'],
|
| 59 |
+
# eval_type=raw_config['eval']['type']['eval_type'],
|
| 60 |
+
# T_dict=raw_config['eval']['T'],
|
| 61 |
+
# seed=raw_config['seed'],
|
| 62 |
+
# change_val=args.change_val
|
| 63 |
+
# )
|
| 64 |
+
|
| 65 |
+
print(f'Elapsed time: {str(timer)}')
|
| 66 |
+
|
| 67 |
+
if __name__ == '__main__':
|
| 68 |
+
main()
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/smote/sample_smote.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import lib
|
| 3 |
+
import argparse
|
| 4 |
+
import numpy as np
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Union, Any
|
| 7 |
+
from imblearn.over_sampling import SMOTE, SMOTENC
|
| 8 |
+
from sklearn.model_selection import train_test_split
|
| 9 |
+
from sklearn.preprocessing import MinMaxScaler
|
| 10 |
+
from sklearn.utils import check_random_state
|
| 11 |
+
|
| 12 |
+
class MySMOTE(SMOTE):
|
| 13 |
+
def __init__(
|
| 14 |
+
self,
|
| 15 |
+
lam1=0.0,
|
| 16 |
+
lam2=1.0,
|
| 17 |
+
*,
|
| 18 |
+
sampling_strategy="auto",
|
| 19 |
+
random_state=None,
|
| 20 |
+
k_neighbors=5,
|
| 21 |
+
n_jobs=None,
|
| 22 |
+
):
|
| 23 |
+
super().__init__(
|
| 24 |
+
sampling_strategy=sampling_strategy,
|
| 25 |
+
random_state=random_state,
|
| 26 |
+
k_neighbors=k_neighbors,
|
| 27 |
+
n_jobs=n_jobs,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
self.lam1=lam1
|
| 31 |
+
self.lam2=lam2
|
| 32 |
+
|
| 33 |
+
def _make_samples(
|
| 34 |
+
self, X, y_dtype, y_type, nn_data, nn_num, n_samples, step_size=1.0
|
| 35 |
+
):
|
| 36 |
+
random_state = check_random_state(self.random_state)
|
| 37 |
+
samples_indices = random_state.randint(low=0, high=nn_num.size, size=n_samples)
|
| 38 |
+
|
| 39 |
+
# np.newaxis for backwards compatability with random_state
|
| 40 |
+
steps = step_size * random_state.uniform(low=self.lam1, high=self.lam2, size=n_samples)[:, np.newaxis]
|
| 41 |
+
rows = np.floor_divide(samples_indices, nn_num.shape[1])
|
| 42 |
+
cols = np.mod(samples_indices, nn_num.shape[1])
|
| 43 |
+
|
| 44 |
+
X_new = self._generate_samples(X, nn_data, nn_num, rows, cols, steps)
|
| 45 |
+
y_new = np.full(n_samples, fill_value=y_type, dtype=y_dtype)
|
| 46 |
+
return X_new, y_new
|
| 47 |
+
|
| 48 |
+
class MySMOTENC(SMOTENC):
|
| 49 |
+
def __init__(
|
| 50 |
+
self,
|
| 51 |
+
lam1=0.0,
|
| 52 |
+
lam2=1.0,
|
| 53 |
+
*,
|
| 54 |
+
categorical_features,
|
| 55 |
+
sampling_strategy="auto",
|
| 56 |
+
random_state=None,
|
| 57 |
+
k_neighbors=5,
|
| 58 |
+
n_jobs=None
|
| 59 |
+
):
|
| 60 |
+
super().__init__(
|
| 61 |
+
categorical_features=categorical_features,
|
| 62 |
+
sampling_strategy=sampling_strategy,
|
| 63 |
+
random_state=random_state,
|
| 64 |
+
k_neighbors=k_neighbors,
|
| 65 |
+
n_jobs=n_jobs,
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
self.lam1=0.0
|
| 69 |
+
self.lam2=1.0
|
| 70 |
+
|
| 71 |
+
def _make_samples(
|
| 72 |
+
self, X, y_dtype, y_type, nn_data, nn_num, n_samples, step_size=1.0, lam1=0.0, lam2=1.0
|
| 73 |
+
):
|
| 74 |
+
random_state = check_random_state(self.random_state)
|
| 75 |
+
samples_indices = random_state.randint(low=0, high=nn_num.size, size=n_samples)
|
| 76 |
+
|
| 77 |
+
# np.newaxis for backwards compatability with random_state
|
| 78 |
+
steps = step_size * random_state.uniform(low=self.lam1, high=self.lam2, size=n_samples)[:, np.newaxis]
|
| 79 |
+
rows = np.floor_divide(samples_indices, nn_num.shape[1])
|
| 80 |
+
cols = np.mod(samples_indices, nn_num.shape[1])
|
| 81 |
+
|
| 82 |
+
X_new = self._generate_samples(X, nn_data, nn_num, rows, cols, steps)
|
| 83 |
+
y_new = np.full(n_samples, fill_value=y_type, dtype=y_dtype)
|
| 84 |
+
return X_new, y_new
|
| 85 |
+
|
| 86 |
+
def save_data(X, y, path, n_cat_features=0):
|
| 87 |
+
if n_cat_features > 0:
|
| 88 |
+
X_num = X[:, :-n_cat_features]
|
| 89 |
+
X_cat = X[:, -n_cat_features:]
|
| 90 |
+
else:
|
| 91 |
+
X_num = X
|
| 92 |
+
X_cat = None
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
np.save(path / "X_num_train", X_num.astype(float), allow_pickle=True)
|
| 96 |
+
np.save(path / "y_train", y, allow_pickle=True)
|
| 97 |
+
if X_cat is not None:
|
| 98 |
+
np.save(path / "X_cat_train", X_cat, allow_pickle=True)
|
| 99 |
+
|
| 100 |
+
def sample_smote(
|
| 101 |
+
parent_dir,
|
| 102 |
+
real_data_path,
|
| 103 |
+
eval_type = "synthetic",
|
| 104 |
+
k_neighbours = 5,
|
| 105 |
+
frac_samples = 1.0,
|
| 106 |
+
frac_lam_del = 0.0,
|
| 107 |
+
change_val = False,
|
| 108 |
+
save = True,
|
| 109 |
+
seed = 0
|
| 110 |
+
):
|
| 111 |
+
lam1 = 0.0 + frac_lam_del / 2
|
| 112 |
+
lam2 = 1.0 - frac_lam_del / 2
|
| 113 |
+
|
| 114 |
+
real_data_path = Path(real_data_path)
|
| 115 |
+
info = lib.load_json(real_data_path / 'info.json')
|
| 116 |
+
is_regression = info['task_type'] == 'regression'
|
| 117 |
+
|
| 118 |
+
X_num = {}
|
| 119 |
+
X_cat = {}
|
| 120 |
+
y = {}
|
| 121 |
+
|
| 122 |
+
if change_val:
|
| 123 |
+
X_num['train'], X_cat['train'], y['train'], X_num['val'], X_cat['val'], y['val'] = lib.read_changed_val(real_data_path)
|
| 124 |
+
else:
|
| 125 |
+
X_num['train'], X_cat['train'], y['train'] = lib.read_pure_data(real_data_path, 'train')
|
| 126 |
+
X_num['val'], X_cat['val'], y['val'] = lib.read_pure_data(real_data_path, 'val')
|
| 127 |
+
X_num['test'], X_cat['test'], y['test'] = lib.read_pure_data(real_data_path, 'test')
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
X = {k: X_num[k] for k in X_num.keys()}
|
| 131 |
+
|
| 132 |
+
if is_regression:
|
| 133 |
+
X['train'] = np.concatenate([X["train"], y["train"].reshape(-1, 1)], axis=1, dtype=object)
|
| 134 |
+
y['train'] = np.where(y["train"] > np.median(y["train"]), 1, 0)
|
| 135 |
+
|
| 136 |
+
n_num_features = X['train'].shape[1]
|
| 137 |
+
n_cat_features = X_cat['train'].shape[1] if X_cat['train'] is not None else 0
|
| 138 |
+
cat_features = list(range(n_num_features, n_num_features+n_cat_features))
|
| 139 |
+
print(cat_features)
|
| 140 |
+
|
| 141 |
+
scaler = MinMaxScaler().fit(X["train"])
|
| 142 |
+
X["train"] = scaler.transform(X["train"]).astype(object)
|
| 143 |
+
|
| 144 |
+
if X_cat['train'] is not None:
|
| 145 |
+
for k in X_num.keys():
|
| 146 |
+
X[k] = np.concatenate([X[k], X_cat[k]], axis=1, dtype=object)
|
| 147 |
+
|
| 148 |
+
print("Before:", X['train'].shape)
|
| 149 |
+
|
| 150 |
+
if eval_type != 'real':
|
| 151 |
+
strat = {k: int((1 + frac_samples) * np.sum(y['train'] == k)) for k in np.unique(y['train'])}
|
| 152 |
+
print(strat)
|
| 153 |
+
if n_cat_features > 0:
|
| 154 |
+
sm = MySMOTENC(
|
| 155 |
+
lam1=lam1,
|
| 156 |
+
lam2=lam2,
|
| 157 |
+
random_state=seed,
|
| 158 |
+
k_neighbors=k_neighbours,
|
| 159 |
+
categorical_features=cat_features,
|
| 160 |
+
sampling_strategy=strat
|
| 161 |
+
)
|
| 162 |
+
else:
|
| 163 |
+
sm = MySMOTE(
|
| 164 |
+
lam1=lam1,
|
| 165 |
+
lam2=lam2,
|
| 166 |
+
random_state=seed,
|
| 167 |
+
k_neighbors=k_neighbours,
|
| 168 |
+
sampling_strategy=strat
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
X_res, y_res = sm.fit_resample(X['train'], y['train'])
|
| 172 |
+
if is_regression:
|
| 173 |
+
X_res[:, :X_num["train"].shape[1]+1] = scaler.inverse_transform(X_res[:, :X_num["train"].shape[1]+1])
|
| 174 |
+
y_res = X_res[:, X_num["train"].shape[1]]
|
| 175 |
+
X_res = np.delete(X_res, [X_num["train"].shape[1]], axis=1)
|
| 176 |
+
else:
|
| 177 |
+
X_res[:, :X_num["train"].shape[1]] = scaler.inverse_transform(X_res[:, :X_num["train"].shape[1]])
|
| 178 |
+
y_res = y_res.astype(int)
|
| 179 |
+
|
| 180 |
+
if eval_type == "synthetic":
|
| 181 |
+
X_res = X_res[X['train'].shape[0]:]
|
| 182 |
+
y_res = y_res[X['train'].shape[0]:]
|
| 183 |
+
|
| 184 |
+
disc_cols = []
|
| 185 |
+
for col in range(X_num["train"].shape[1]):
|
| 186 |
+
uniq_vals = np.unique(X_num["train"][:, col])
|
| 187 |
+
if len(uniq_vals) <= 32 and ((uniq_vals - np.round(uniq_vals)) == 0).all():
|
| 188 |
+
disc_cols.append(col)
|
| 189 |
+
if len(disc_cols):
|
| 190 |
+
X_res[:, :X_num["train"].shape[1]] = lib.round_columns(X_num["train"], X_res[:, :X_num["train"].shape[1]], disc_cols)
|
| 191 |
+
|
| 192 |
+
if save:
|
| 193 |
+
save_data(X_res, y_res, Path(parent_dir), n_cat_features)
|
| 194 |
+
|
| 195 |
+
X['train'] = X_res
|
| 196 |
+
y['train'] = y_res
|
| 197 |
+
|
| 198 |
+
return X, y
|
| 199 |
+
|
| 200 |
+
def main():
|
| 201 |
+
parser = argparse.ArgumentParser()
|
| 202 |
+
parser.add_argument('data_path', type=str)
|
| 203 |
+
parser.add_argument('method', type=str)
|
| 204 |
+
|
| 205 |
+
args = parser.parse_args()
|
| 206 |
+
|
| 207 |
+
sample_smote(args.data_path, args.method, save=False)
|
| 208 |
+
|
| 209 |
+
if __name__ == '__main__':
|
| 210 |
+
main()
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/smote/tune_smote.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import optuna
|
| 2 |
+
import lib
|
| 3 |
+
from copy import deepcopy
|
| 4 |
+
import argparse
|
| 5 |
+
import tempfile
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import os
|
| 8 |
+
from scripts.eval_catboost import train_catboost
|
| 9 |
+
from sample_smote import sample_smote
|
| 10 |
+
import subprocess
|
| 11 |
+
|
| 12 |
+
parser = argparse.ArgumentParser()
|
| 13 |
+
parser.add_argument('data_path', type=str)
|
| 14 |
+
parser.add_argument('eval_type', type=str)
|
| 15 |
+
|
| 16 |
+
args = parser.parse_args()
|
| 17 |
+
real_data_path = args.data_path
|
| 18 |
+
eval_type = args.eval_type
|
| 19 |
+
|
| 20 |
+
def objective(trial):
|
| 21 |
+
|
| 22 |
+
k_neighbours = trial.suggest_int("k_neighbours", 5, 20)
|
| 23 |
+
frac_samples = 2 ** trial.suggest_int('frac_samples', -2, 3)
|
| 24 |
+
|
| 25 |
+
# z = \lam*x + (1 - \lam)*y, \lam ~ U[frac_lam_del/2, 1-frac_lam_del/2]
|
| 26 |
+
frac_lam_del = trial.suggest_float("frac_lam_del", 0.0, 0.95, step=0.05)
|
| 27 |
+
|
| 28 |
+
score = 0.0
|
| 29 |
+
with tempfile.TemporaryDirectory() as dir_:
|
| 30 |
+
dir_ = Path(dir_)
|
| 31 |
+
for seed in range(5):
|
| 32 |
+
sample_smote(
|
| 33 |
+
parent_dir=dir_,
|
| 34 |
+
real_data_path=real_data_path,
|
| 35 |
+
eval_type=eval_type,
|
| 36 |
+
frac_samples=frac_samples,
|
| 37 |
+
frac_lam_del=frac_lam_del,
|
| 38 |
+
k_neighbours=k_neighbours,
|
| 39 |
+
change_val=True,
|
| 40 |
+
seed=seed
|
| 41 |
+
)
|
| 42 |
+
T_dict = {
|
| 43 |
+
"seed": 0,
|
| 44 |
+
"normalization": None,
|
| 45 |
+
"num_nan_policy": None,
|
| 46 |
+
"cat_nan_policy": None,
|
| 47 |
+
"cat_min_frequency": None,
|
| 48 |
+
"cat_encoding": None,
|
| 49 |
+
"y_policy": "default"
|
| 50 |
+
}
|
| 51 |
+
metrics = train_catboost(
|
| 52 |
+
parent_dir=dir_,
|
| 53 |
+
real_data_path=real_data_path,
|
| 54 |
+
eval_type=eval_type,
|
| 55 |
+
T_dict=T_dict,
|
| 56 |
+
change_val=True,
|
| 57 |
+
seed = 0
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
score += metrics.get_val_score()
|
| 61 |
+
|
| 62 |
+
return score / 5
|
| 63 |
+
|
| 64 |
+
study = optuna.create_study(
|
| 65 |
+
direction='maximize',
|
| 66 |
+
sampler=optuna.samplers.TPESampler(seed=0),
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
study.optimize(objective, n_trials=5, show_progress_bar=True)
|
| 70 |
+
|
| 71 |
+
os.makedirs(f"exp/{Path(real_data_path).name}/smote/", exist_ok=True)
|
| 72 |
+
config = {
|
| 73 |
+
"parent_dir": f"exp/{Path(real_data_path).name}/smote/",
|
| 74 |
+
"real_data_path": real_data_path,
|
| 75 |
+
"seed": 0,
|
| 76 |
+
"smote_params": {},
|
| 77 |
+
"sample": {"seed": 0},
|
| 78 |
+
"eval": {
|
| 79 |
+
"type": {"eval_model": "catboost", "eval_type": eval_type},
|
| 80 |
+
"T": {
|
| 81 |
+
"seed": 0,
|
| 82 |
+
"normalization": None,
|
| 83 |
+
"num_nan_policy": None,
|
| 84 |
+
"cat_nan_policy": None,
|
| 85 |
+
"cat_min_frequency": None,
|
| 86 |
+
"cat_encoding": None,
|
| 87 |
+
"y_policy": "default"
|
| 88 |
+
},
|
| 89 |
+
}
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
config["smote_params"] = study.best_params
|
| 93 |
+
config["smote_params"]["frac_samples"] = 2 ** config["smote_params"]["frac_samples"]
|
| 94 |
+
|
| 95 |
+
lib.dump_config(config, config["parent_dir"]+"config.toml")
|
| 96 |
+
|
| 97 |
+
subprocess.run(['python3.9', "scripts/eval_seeds.py", '--config', f'{config["parent_dir"]+"config.toml"}',
|
| 98 |
+
'10', "smote", eval_type, "catboost", "5"], check=True)
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .gaussian_multinomial_diffsuion import * # noqa
|
| 2 |
+
from .modules import * # noqa
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (304 Bytes). View file
|
|
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/__pycache__/gaussian_multinomial_diffsuion.cpython-311.pyc
ADDED
|
Binary file (51 kB). View file
|
|
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/__pycache__/modules.cpython-311.pyc
ADDED
|
Binary file (24.8 kB). View file
|
|
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/__pycache__/utils.cpython-311.pyc
ADDED
|
Binary file (11.4 kB). View file
|
|
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/gaussian_multinomial_diffsuion.py
ADDED
|
@@ -0,0 +1,993 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Based on https://github.com/openai/guided-diffusion/blob/main/guided_diffusion
|
| 3 |
+
and https://github.com/ehoogeboom/multinomial_diffusion
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
import torch
|
| 8 |
+
import math
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
from .utils import *
|
| 12 |
+
|
| 13 |
+
"""
|
| 14 |
+
Based in part on: https://github.com/lucidrains/denoising-diffusion-pytorch/blob/5989f4c77eafcdc6be0fb4739f0f277a6dd7f7d8/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py#L281
|
| 15 |
+
"""
|
| 16 |
+
eps = 1e-8
|
| 17 |
+
|
| 18 |
+
def get_named_beta_schedule(schedule_name, num_diffusion_timesteps):
|
| 19 |
+
"""
|
| 20 |
+
Get a pre-defined beta schedule for the given name.
|
| 21 |
+
The beta schedule library consists of beta schedules which remain similar
|
| 22 |
+
in the limit of num_diffusion_timesteps.
|
| 23 |
+
Beta schedules may be added, but should not be removed or changed once
|
| 24 |
+
they are committed to maintain backwards compatibility.
|
| 25 |
+
"""
|
| 26 |
+
if schedule_name == "linear":
|
| 27 |
+
# Linear schedule from Ho et al, extended to work for any number of
|
| 28 |
+
# diffusion steps.
|
| 29 |
+
scale = 1000 / num_diffusion_timesteps
|
| 30 |
+
beta_start = scale * 0.0001
|
| 31 |
+
beta_end = scale * 0.02
|
| 32 |
+
return np.linspace(
|
| 33 |
+
beta_start, beta_end, num_diffusion_timesteps, dtype=np.float64
|
| 34 |
+
)
|
| 35 |
+
elif schedule_name == "cosine":
|
| 36 |
+
return betas_for_alpha_bar(
|
| 37 |
+
num_diffusion_timesteps,
|
| 38 |
+
lambda t: math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2,
|
| 39 |
+
)
|
| 40 |
+
else:
|
| 41 |
+
raise NotImplementedError(f"unknown beta schedule: {schedule_name}")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999):
|
| 45 |
+
"""
|
| 46 |
+
Create a beta schedule that discretizes the given alpha_t_bar function,
|
| 47 |
+
which defines the cumulative product of (1-beta) over time from t = [0,1].
|
| 48 |
+
:param num_diffusion_timesteps: the number of betas to produce.
|
| 49 |
+
:param alpha_bar: a lambda that takes an argument t from 0 to 1 and
|
| 50 |
+
produces the cumulative product of (1-beta) up to that
|
| 51 |
+
part of the diffusion process.
|
| 52 |
+
:param max_beta: the maximum beta to use; use values lower than 1 to
|
| 53 |
+
prevent singularities.
|
| 54 |
+
"""
|
| 55 |
+
betas = []
|
| 56 |
+
for i in range(num_diffusion_timesteps):
|
| 57 |
+
t1 = i / num_diffusion_timesteps
|
| 58 |
+
t2 = (i + 1) / num_diffusion_timesteps
|
| 59 |
+
betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta))
|
| 60 |
+
return np.array(betas)
|
| 61 |
+
|
| 62 |
+
class GaussianMultinomialDiffusion(torch.nn.Module):
|
| 63 |
+
def __init__(
|
| 64 |
+
self,
|
| 65 |
+
num_classes: np.array,
|
| 66 |
+
num_numerical_features: int,
|
| 67 |
+
denoise_fn,
|
| 68 |
+
num_timesteps=1000,
|
| 69 |
+
gaussian_loss_type='mse',
|
| 70 |
+
gaussian_parametrization='eps',
|
| 71 |
+
multinomial_loss_type='vb_stochastic',
|
| 72 |
+
parametrization='x0',
|
| 73 |
+
scheduler='cosine',
|
| 74 |
+
device=torch.device('cpu')
|
| 75 |
+
):
|
| 76 |
+
|
| 77 |
+
super(GaussianMultinomialDiffusion, self).__init__()
|
| 78 |
+
assert multinomial_loss_type in ('vb_stochastic', 'vb_all')
|
| 79 |
+
assert parametrization in ('x0', 'direct')
|
| 80 |
+
|
| 81 |
+
if multinomial_loss_type == 'vb_all':
|
| 82 |
+
print('Computing the loss using the bound on _all_ timesteps.'
|
| 83 |
+
' This is expensive both in terms of memory and computation.')
|
| 84 |
+
|
| 85 |
+
self.num_numerical_features = num_numerical_features
|
| 86 |
+
self.num_classes = num_classes # it as a vector [K1, K2, ..., Km]
|
| 87 |
+
self.num_classes_expanded = torch.from_numpy(
|
| 88 |
+
np.concatenate([num_classes[i].repeat(num_classes[i]) for i in range(len(num_classes))])
|
| 89 |
+
).to(device)
|
| 90 |
+
|
| 91 |
+
self.slices_for_classes = [np.arange(self.num_classes[0])]
|
| 92 |
+
offsets = np.cumsum(self.num_classes)
|
| 93 |
+
for i in range(1, len(offsets)):
|
| 94 |
+
self.slices_for_classes.append(np.arange(offsets[i - 1], offsets[i]))
|
| 95 |
+
self.offsets = torch.from_numpy(np.append([0], offsets)).to(device)
|
| 96 |
+
|
| 97 |
+
self._denoise_fn = denoise_fn
|
| 98 |
+
self.gaussian_loss_type = gaussian_loss_type
|
| 99 |
+
self.gaussian_parametrization = gaussian_parametrization
|
| 100 |
+
self.multinomial_loss_type = multinomial_loss_type
|
| 101 |
+
self.num_timesteps = num_timesteps
|
| 102 |
+
self.parametrization = parametrization
|
| 103 |
+
self.scheduler = scheduler
|
| 104 |
+
|
| 105 |
+
alphas = 1. - get_named_beta_schedule(scheduler, num_timesteps)
|
| 106 |
+
alphas = torch.tensor(alphas.astype('float64'))
|
| 107 |
+
betas = 1. - alphas
|
| 108 |
+
|
| 109 |
+
log_alpha = np.log(alphas)
|
| 110 |
+
log_cumprod_alpha = np.cumsum(log_alpha)
|
| 111 |
+
|
| 112 |
+
log_1_min_alpha = log_1_min_a(log_alpha)
|
| 113 |
+
log_1_min_cumprod_alpha = log_1_min_a(log_cumprod_alpha)
|
| 114 |
+
|
| 115 |
+
alphas_cumprod = np.cumprod(alphas, axis=0)
|
| 116 |
+
alphas_cumprod_prev = torch.tensor(np.append(1.0, alphas_cumprod[:-1]))
|
| 117 |
+
alphas_cumprod_next = torch.tensor(np.append(alphas_cumprod[1:], 0.0))
|
| 118 |
+
sqrt_alphas_cumprod = np.sqrt(alphas_cumprod)
|
| 119 |
+
sqrt_one_minus_alphas_cumprod = np.sqrt(1.0 - alphas_cumprod)
|
| 120 |
+
sqrt_recip_alphas_cumprod = np.sqrt(1.0 / alphas_cumprod)
|
| 121 |
+
sqrt_recipm1_alphas_cumprod = np.sqrt(1.0 / alphas_cumprod - 1)
|
| 122 |
+
|
| 123 |
+
# Gaussian diffusion
|
| 124 |
+
|
| 125 |
+
self.posterior_variance = (
|
| 126 |
+
betas * (1.0 - alphas_cumprod_prev) / (1.0 - alphas_cumprod)
|
| 127 |
+
)
|
| 128 |
+
self.posterior_log_variance_clipped = torch.from_numpy(
|
| 129 |
+
np.log(np.append(self.posterior_variance[1], self.posterior_variance[1:]))
|
| 130 |
+
).float().to(device)
|
| 131 |
+
self.posterior_mean_coef1 = (
|
| 132 |
+
betas * np.sqrt(alphas_cumprod_prev) / (1.0 - alphas_cumprod)
|
| 133 |
+
).float().to(device)
|
| 134 |
+
self.posterior_mean_coef2 = (
|
| 135 |
+
(1.0 - alphas_cumprod_prev)
|
| 136 |
+
* np.sqrt(alphas.numpy())
|
| 137 |
+
/ (1.0 - alphas_cumprod)
|
| 138 |
+
).float().to(device)
|
| 139 |
+
|
| 140 |
+
assert log_add_exp(log_alpha, log_1_min_alpha).abs().sum().item() < 1.e-5
|
| 141 |
+
assert log_add_exp(log_cumprod_alpha, log_1_min_cumprod_alpha).abs().sum().item() < 1e-5
|
| 142 |
+
assert (np.cumsum(log_alpha) - log_cumprod_alpha).abs().sum().item() < 1.e-5
|
| 143 |
+
|
| 144 |
+
# Convert to float32 and register buffers.
|
| 145 |
+
self.register_buffer('alphas', alphas.float().to(device))
|
| 146 |
+
self.register_buffer('log_alpha', log_alpha.float().to(device))
|
| 147 |
+
self.register_buffer('log_1_min_alpha', log_1_min_alpha.float().to(device))
|
| 148 |
+
self.register_buffer('log_1_min_cumprod_alpha', log_1_min_cumprod_alpha.float().to(device))
|
| 149 |
+
self.register_buffer('log_cumprod_alpha', log_cumprod_alpha.float().to(device))
|
| 150 |
+
self.register_buffer('alphas_cumprod', alphas_cumprod.float().to(device))
|
| 151 |
+
self.register_buffer('alphas_cumprod_prev', alphas_cumprod_prev.float().to(device))
|
| 152 |
+
self.register_buffer('alphas_cumprod_next', alphas_cumprod_next.float().to(device))
|
| 153 |
+
self.register_buffer('sqrt_alphas_cumprod', sqrt_alphas_cumprod.float().to(device))
|
| 154 |
+
self.register_buffer('sqrt_one_minus_alphas_cumprod', sqrt_one_minus_alphas_cumprod.float().to(device))
|
| 155 |
+
self.register_buffer('sqrt_recip_alphas_cumprod', sqrt_recip_alphas_cumprod.float().to(device))
|
| 156 |
+
self.register_buffer('sqrt_recipm1_alphas_cumprod', sqrt_recipm1_alphas_cumprod.float().to(device))
|
| 157 |
+
|
| 158 |
+
self.register_buffer('Lt_history', torch.zeros(num_timesteps))
|
| 159 |
+
self.register_buffer('Lt_count', torch.zeros(num_timesteps))
|
| 160 |
+
|
| 161 |
+
# Gaussian part
|
| 162 |
+
def gaussian_q_mean_variance(self, x_start, t):
|
| 163 |
+
mean = (
|
| 164 |
+
extract(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start
|
| 165 |
+
)
|
| 166 |
+
variance = extract(1.0 - self.alphas_cumprod, t, x_start.shape)
|
| 167 |
+
log_variance = extract(
|
| 168 |
+
self.log_1_min_cumprod_alpha, t, x_start.shape
|
| 169 |
+
)
|
| 170 |
+
return mean, variance, log_variance
|
| 171 |
+
|
| 172 |
+
def gaussian_q_sample(self, x_start, t, noise=None):
|
| 173 |
+
if noise is None:
|
| 174 |
+
noise = torch.randn_like(x_start)
|
| 175 |
+
assert noise.shape == x_start.shape
|
| 176 |
+
return (
|
| 177 |
+
extract(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start
|
| 178 |
+
+ extract(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape)
|
| 179 |
+
* noise
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
def gaussian_q_posterior_mean_variance(self, x_start, x_t, t):
|
| 183 |
+
assert x_start.shape == x_t.shape
|
| 184 |
+
posterior_mean = (
|
| 185 |
+
extract(self.posterior_mean_coef1, t, x_t.shape) * x_start
|
| 186 |
+
+ extract(self.posterior_mean_coef2, t, x_t.shape) * x_t
|
| 187 |
+
)
|
| 188 |
+
posterior_variance = extract(self.posterior_variance, t, x_t.shape)
|
| 189 |
+
posterior_log_variance_clipped = extract(
|
| 190 |
+
self.posterior_log_variance_clipped, t, x_t.shape
|
| 191 |
+
)
|
| 192 |
+
assert (
|
| 193 |
+
posterior_mean.shape[0]
|
| 194 |
+
== posterior_variance.shape[0]
|
| 195 |
+
== posterior_log_variance_clipped.shape[0]
|
| 196 |
+
== x_start.shape[0]
|
| 197 |
+
)
|
| 198 |
+
return posterior_mean, posterior_variance, posterior_log_variance_clipped
|
| 199 |
+
|
| 200 |
+
def gaussian_p_mean_variance(
|
| 201 |
+
self, model_output, x, t, clip_denoised=False, denoised_fn=None, model_kwargs=None
|
| 202 |
+
):
|
| 203 |
+
if model_kwargs is None:
|
| 204 |
+
model_kwargs = {}
|
| 205 |
+
|
| 206 |
+
B, C = x.shape[:2]
|
| 207 |
+
assert t.shape == (B,)
|
| 208 |
+
|
| 209 |
+
model_variance = torch.cat([self.posterior_variance[1].unsqueeze(0).to(x.device), (1. - self.alphas)[1:]], dim=0)
|
| 210 |
+
# model_variance = self.posterior_variance.to(x.device)
|
| 211 |
+
model_log_variance = torch.log(model_variance)
|
| 212 |
+
|
| 213 |
+
model_variance = extract(model_variance, t, x.shape)
|
| 214 |
+
model_log_variance = extract(model_log_variance, t, x.shape)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
if self.gaussian_parametrization == 'eps':
|
| 218 |
+
pred_xstart = self._predict_xstart_from_eps(x_t=x, t=t, eps=model_output)
|
| 219 |
+
elif self.gaussian_parametrization == 'x0':
|
| 220 |
+
pred_xstart = model_output
|
| 221 |
+
else:
|
| 222 |
+
raise NotImplementedError
|
| 223 |
+
|
| 224 |
+
model_mean, _, _ = self.gaussian_q_posterior_mean_variance(
|
| 225 |
+
x_start=pred_xstart, x_t=x, t=t
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
assert (
|
| 229 |
+
model_mean.shape == model_log_variance.shape == pred_xstart.shape == x.shape
|
| 230 |
+
), f'{model_mean.shape}, {model_log_variance.shape}, {pred_xstart.shape}, {x.shape}'
|
| 231 |
+
|
| 232 |
+
return {
|
| 233 |
+
"mean": model_mean,
|
| 234 |
+
"variance": model_variance,
|
| 235 |
+
"log_variance": model_log_variance,
|
| 236 |
+
"pred_xstart": pred_xstart,
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
def _vb_terms_bpd(
|
| 240 |
+
self, model_output, x_start, x_t, t, clip_denoised=False, model_kwargs=None
|
| 241 |
+
):
|
| 242 |
+
true_mean, _, true_log_variance_clipped = self.gaussian_q_posterior_mean_variance(
|
| 243 |
+
x_start=x_start, x_t=x_t, t=t
|
| 244 |
+
)
|
| 245 |
+
out = self.gaussian_p_mean_variance(
|
| 246 |
+
model_output, x_t, t, clip_denoised=clip_denoised, model_kwargs=model_kwargs
|
| 247 |
+
)
|
| 248 |
+
kl = normal_kl(
|
| 249 |
+
true_mean, true_log_variance_clipped, out["mean"], out["log_variance"]
|
| 250 |
+
)
|
| 251 |
+
kl = mean_flat(kl) / np.log(2.0)
|
| 252 |
+
|
| 253 |
+
decoder_nll = -discretized_gaussian_log_likelihood(
|
| 254 |
+
x_start, means=out["mean"], log_scales=0.5 * out["log_variance"]
|
| 255 |
+
)
|
| 256 |
+
assert decoder_nll.shape == x_start.shape
|
| 257 |
+
decoder_nll = mean_flat(decoder_nll) / np.log(2.0)
|
| 258 |
+
|
| 259 |
+
# At the first timestep return the decoder NLL,
|
| 260 |
+
# otherwise return KL(q(x_{t-1}|x_t,x_0) || p(x_{t-1}|x_t))
|
| 261 |
+
output = torch.where((t == 0), decoder_nll, kl)
|
| 262 |
+
return {"output": output, "pred_xstart": out["pred_xstart"], "out_mean": out["mean"], "true_mean": true_mean}
|
| 263 |
+
|
| 264 |
+
def _prior_gaussian(self, x_start):
|
| 265 |
+
"""
|
| 266 |
+
Get the prior KL term for the variational lower-bound, measured in
|
| 267 |
+
bits-per-dim.
|
| 268 |
+
|
| 269 |
+
This term can't be optimized, as it only depends on the encoder.
|
| 270 |
+
|
| 271 |
+
:param x_start: the [N x C x ...] tensor of inputs.
|
| 272 |
+
:return: a batch of [N] KL values (in bits), one per batch element.
|
| 273 |
+
"""
|
| 274 |
+
batch_size = x_start.shape[0]
|
| 275 |
+
t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device)
|
| 276 |
+
qt_mean, _, qt_log_variance = self.gaussian_q_mean_variance(x_start, t)
|
| 277 |
+
kl_prior = normal_kl(
|
| 278 |
+
mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0
|
| 279 |
+
)
|
| 280 |
+
return mean_flat(kl_prior) / np.log(2.0)
|
| 281 |
+
|
| 282 |
+
def _gaussian_loss(self, model_out, x_start, x_t, t, noise, model_kwargs=None):
|
| 283 |
+
if model_kwargs is None:
|
| 284 |
+
model_kwargs = {}
|
| 285 |
+
|
| 286 |
+
terms = {}
|
| 287 |
+
if self.gaussian_loss_type == 'mse':
|
| 288 |
+
terms["loss"] = mean_flat((noise - model_out) ** 2)
|
| 289 |
+
elif self.gaussian_loss_type == 'kl':
|
| 290 |
+
terms["loss"] = self._vb_terms_bpd(
|
| 291 |
+
model_output=model_out,
|
| 292 |
+
x_start=x_start,
|
| 293 |
+
x_t=x_t,
|
| 294 |
+
t=t,
|
| 295 |
+
clip_denoised=False,
|
| 296 |
+
model_kwargs=model_kwargs,
|
| 297 |
+
)["output"]
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
return terms['loss']
|
| 301 |
+
|
| 302 |
+
def _predict_xstart_from_eps(self, x_t, t, eps):
|
| 303 |
+
assert x_t.shape == eps.shape
|
| 304 |
+
return (
|
| 305 |
+
extract(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t
|
| 306 |
+
- extract(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * eps
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
def _predict_eps_from_xstart(self, x_t, t, pred_xstart):
|
| 310 |
+
return (
|
| 311 |
+
extract(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t
|
| 312 |
+
- pred_xstart
|
| 313 |
+
) / extract(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
|
| 314 |
+
|
| 315 |
+
def gaussian_p_sample(
|
| 316 |
+
self,
|
| 317 |
+
model_out,
|
| 318 |
+
x,
|
| 319 |
+
t,
|
| 320 |
+
clip_denoised=False,
|
| 321 |
+
denoised_fn=None,
|
| 322 |
+
model_kwargs=None,
|
| 323 |
+
):
|
| 324 |
+
out = self.gaussian_p_mean_variance(
|
| 325 |
+
model_out,
|
| 326 |
+
x,
|
| 327 |
+
t,
|
| 328 |
+
clip_denoised=clip_denoised,
|
| 329 |
+
denoised_fn=denoised_fn,
|
| 330 |
+
model_kwargs=model_kwargs,
|
| 331 |
+
)
|
| 332 |
+
noise = torch.randn_like(x)
|
| 333 |
+
nonzero_mask = (
|
| 334 |
+
(t != 0).float().view(-1, *([1] * (len(x.shape) - 1)))
|
| 335 |
+
) # no noise when t == 0
|
| 336 |
+
|
| 337 |
+
sample = out["mean"] + nonzero_mask * torch.exp(0.5 * out["log_variance"]) * noise
|
| 338 |
+
return {"sample": sample, "pred_xstart": out["pred_xstart"]}
|
| 339 |
+
|
| 340 |
+
# Multinomial part
|
| 341 |
+
|
| 342 |
+
def multinomial_kl(self, log_prob1, log_prob2):
|
| 343 |
+
kl = (log_prob1.exp() * (log_prob1 - log_prob2)).sum(dim=1)
|
| 344 |
+
return kl
|
| 345 |
+
|
| 346 |
+
def q_pred_one_timestep(self, log_x_t, t):
|
| 347 |
+
log_alpha_t = extract(self.log_alpha, t, log_x_t.shape)
|
| 348 |
+
log_1_min_alpha_t = extract(self.log_1_min_alpha, t, log_x_t.shape)
|
| 349 |
+
|
| 350 |
+
# alpha_t * E[xt] + (1 - alpha_t) 1 / K
|
| 351 |
+
log_probs = log_add_exp(
|
| 352 |
+
log_x_t + log_alpha_t,
|
| 353 |
+
log_1_min_alpha_t - torch.log(self.num_classes_expanded)
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
return log_probs
|
| 357 |
+
|
| 358 |
+
def q_pred(self, log_x_start, t):
|
| 359 |
+
log_cumprod_alpha_t = extract(self.log_cumprod_alpha, t, log_x_start.shape)
|
| 360 |
+
log_1_min_cumprod_alpha = extract(self.log_1_min_cumprod_alpha, t, log_x_start.shape)
|
| 361 |
+
|
| 362 |
+
log_probs = log_add_exp(
|
| 363 |
+
log_x_start + log_cumprod_alpha_t,
|
| 364 |
+
log_1_min_cumprod_alpha - torch.log(self.num_classes_expanded)
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
return log_probs
|
| 368 |
+
|
| 369 |
+
def predict_start(self, model_out, log_x_t, t, out_dict):
|
| 370 |
+
|
| 371 |
+
# model_out = self._denoise_fn(x_t, t.to(x_t.device), **out_dict)
|
| 372 |
+
|
| 373 |
+
assert model_out.size(0) == log_x_t.size(0)
|
| 374 |
+
assert model_out.size(1) == self.num_classes.sum(), f'{model_out.size()}'
|
| 375 |
+
|
| 376 |
+
log_pred = torch.empty_like(model_out)
|
| 377 |
+
for ix in self.slices_for_classes:
|
| 378 |
+
log_pred[:, ix] = F.log_softmax(model_out[:, ix], dim=1)
|
| 379 |
+
return log_pred
|
| 380 |
+
|
| 381 |
+
def q_posterior(self, log_x_start, log_x_t, t):
|
| 382 |
+
# q(xt-1 | xt, x0) = q(xt | xt-1, x0) * q(xt-1 | x0) / q(xt | x0)
|
| 383 |
+
# where q(xt | xt-1, x0) = q(xt | xt-1).
|
| 384 |
+
|
| 385 |
+
# EV_log_qxt_x0 = self.q_pred(log_x_start, t)
|
| 386 |
+
|
| 387 |
+
# print('sum exp', EV_log_qxt_x0.exp().sum(1).mean())
|
| 388 |
+
# assert False
|
| 389 |
+
|
| 390 |
+
# log_qxt_x0 = (log_x_t.exp() * EV_log_qxt_x0).sum(dim=1)
|
| 391 |
+
t_minus_1 = t - 1
|
| 392 |
+
# Remove negative values, will not be used anyway for final decoder
|
| 393 |
+
t_minus_1 = torch.where(t_minus_1 < 0, torch.zeros_like(t_minus_1), t_minus_1)
|
| 394 |
+
log_EV_qxtmin_x0 = self.q_pred(log_x_start, t_minus_1)
|
| 395 |
+
|
| 396 |
+
num_axes = (1,) * (len(log_x_start.size()) - 1)
|
| 397 |
+
t_broadcast = t.to(log_x_start.device).view(-1, *num_axes) * torch.ones_like(log_x_start)
|
| 398 |
+
log_EV_qxtmin_x0 = torch.where(t_broadcast == 0, log_x_start, log_EV_qxtmin_x0.to(torch.float32))
|
| 399 |
+
|
| 400 |
+
# unnormed_logprobs = log_EV_qxtmin_x0 +
|
| 401 |
+
# log q_pred_one_timestep(x_t, t)
|
| 402 |
+
# Note: _NOT_ x_tmin1, which is how the formula is typically used!!!
|
| 403 |
+
# Not very easy to see why this is true. But it is :)
|
| 404 |
+
unnormed_logprobs = log_EV_qxtmin_x0 + self.q_pred_one_timestep(log_x_t, t)
|
| 405 |
+
|
| 406 |
+
log_EV_xtmin_given_xt_given_xstart = \
|
| 407 |
+
unnormed_logprobs \
|
| 408 |
+
- sliced_logsumexp(unnormed_logprobs, self.offsets)
|
| 409 |
+
|
| 410 |
+
return log_EV_xtmin_given_xt_given_xstart
|
| 411 |
+
|
| 412 |
+
def p_pred(self, model_out, log_x, t, out_dict):
|
| 413 |
+
if self.parametrization == 'x0':
|
| 414 |
+
log_x_recon = self.predict_start(model_out, log_x, t=t, out_dict=out_dict)
|
| 415 |
+
log_model_pred = self.q_posterior(
|
| 416 |
+
log_x_start=log_x_recon, log_x_t=log_x, t=t)
|
| 417 |
+
elif self.parametrization == 'direct':
|
| 418 |
+
log_model_pred = self.predict_start(model_out, log_x, t=t, out_dict=out_dict)
|
| 419 |
+
else:
|
| 420 |
+
raise ValueError
|
| 421 |
+
return log_model_pred
|
| 422 |
+
|
| 423 |
+
@torch.no_grad()
|
| 424 |
+
def p_sample(self, model_out, log_x, t, out_dict):
|
| 425 |
+
model_log_prob = self.p_pred(model_out, log_x=log_x, t=t, out_dict=out_dict)
|
| 426 |
+
out = self.log_sample_categorical(model_log_prob)
|
| 427 |
+
return out
|
| 428 |
+
|
| 429 |
+
@torch.no_grad()
|
| 430 |
+
def p_sample_loop(self, shape, out_dict):
|
| 431 |
+
device = self.log_alpha.device
|
| 432 |
+
|
| 433 |
+
b = shape[0]
|
| 434 |
+
# start with random normal image.
|
| 435 |
+
img = torch.randn(shape, device=device)
|
| 436 |
+
|
| 437 |
+
for i in reversed(range(1, self.num_timesteps)):
|
| 438 |
+
img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long), out_dict)
|
| 439 |
+
return img
|
| 440 |
+
|
| 441 |
+
@torch.no_grad()
|
| 442 |
+
def _sample(self, image_size, out_dict, batch_size = 16):
|
| 443 |
+
return self.p_sample_loop((batch_size, 3, image_size, image_size), out_dict)
|
| 444 |
+
|
| 445 |
+
@torch.no_grad()
|
| 446 |
+
def interpolate(self, x1, x2, t = None, lam = 0.5):
|
| 447 |
+
b, *_, device = *x1.shape, x1.device
|
| 448 |
+
t = default(t, self.num_timesteps - 1)
|
| 449 |
+
|
| 450 |
+
assert x1.shape == x2.shape
|
| 451 |
+
|
| 452 |
+
t_batched = torch.stack([torch.tensor(t, device=device)] * b)
|
| 453 |
+
xt1, xt2 = map(lambda x: self.q_sample(x, t=t_batched), (x1, x2))
|
| 454 |
+
|
| 455 |
+
img = (1 - lam) * xt1 + lam * xt2
|
| 456 |
+
for i in reversed(range(0, t)):
|
| 457 |
+
img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long))
|
| 458 |
+
|
| 459 |
+
return img
|
| 460 |
+
|
| 461 |
+
def log_sample_categorical(self, logits):
|
| 462 |
+
full_sample = []
|
| 463 |
+
for i in range(len(self.num_classes)):
|
| 464 |
+
one_class_logits = logits[:, self.slices_for_classes[i]]
|
| 465 |
+
uniform = torch.rand_like(one_class_logits)
|
| 466 |
+
gumbel_noise = -torch.log(-torch.log(uniform + 1e-30) + 1e-30)
|
| 467 |
+
sample = (gumbel_noise + one_class_logits).argmax(dim=1)
|
| 468 |
+
full_sample.append(sample.unsqueeze(1))
|
| 469 |
+
full_sample = torch.cat(full_sample, dim=1)
|
| 470 |
+
log_sample = index_to_log_onehot(full_sample, self.num_classes)
|
| 471 |
+
return log_sample
|
| 472 |
+
|
| 473 |
+
def q_sample(self, log_x_start, t):
|
| 474 |
+
log_EV_qxt_x0 = self.q_pred(log_x_start, t)
|
| 475 |
+
|
| 476 |
+
log_sample = self.log_sample_categorical(log_EV_qxt_x0)
|
| 477 |
+
|
| 478 |
+
return log_sample
|
| 479 |
+
|
| 480 |
+
def nll(self, log_x_start, out_dict):
|
| 481 |
+
b = log_x_start.size(0)
|
| 482 |
+
device = log_x_start.device
|
| 483 |
+
loss = 0
|
| 484 |
+
for t in range(0, self.num_timesteps):
|
| 485 |
+
t_array = (torch.ones(b, device=device) * t).long()
|
| 486 |
+
|
| 487 |
+
kl = self.compute_Lt(
|
| 488 |
+
log_x_start=log_x_start,
|
| 489 |
+
log_x_t=self.q_sample(log_x_start=log_x_start, t=t_array),
|
| 490 |
+
t=t_array,
|
| 491 |
+
out_dict=out_dict)
|
| 492 |
+
|
| 493 |
+
loss += kl
|
| 494 |
+
|
| 495 |
+
loss += self.kl_prior(log_x_start)
|
| 496 |
+
|
| 497 |
+
return loss
|
| 498 |
+
|
| 499 |
+
def kl_prior(self, log_x_start):
|
| 500 |
+
b = log_x_start.size(0)
|
| 501 |
+
device = log_x_start.device
|
| 502 |
+
ones = torch.ones(b, device=device).long()
|
| 503 |
+
|
| 504 |
+
log_qxT_prob = self.q_pred(log_x_start, t=(self.num_timesteps - 1) * ones)
|
| 505 |
+
log_half_prob = -torch.log(self.num_classes_expanded * torch.ones_like(log_qxT_prob))
|
| 506 |
+
|
| 507 |
+
kl_prior = self.multinomial_kl(log_qxT_prob, log_half_prob)
|
| 508 |
+
return sum_except_batch(kl_prior)
|
| 509 |
+
|
| 510 |
+
def compute_Lt(self, model_out, log_x_start, log_x_t, t, out_dict, detach_mean=False):
|
| 511 |
+
log_true_prob = self.q_posterior(
|
| 512 |
+
log_x_start=log_x_start, log_x_t=log_x_t, t=t)
|
| 513 |
+
log_model_prob = self.p_pred(model_out, log_x=log_x_t, t=t, out_dict=out_dict)
|
| 514 |
+
|
| 515 |
+
if detach_mean:
|
| 516 |
+
log_model_prob = log_model_prob.detach()
|
| 517 |
+
|
| 518 |
+
kl = self.multinomial_kl(log_true_prob, log_model_prob)
|
| 519 |
+
kl = sum_except_batch(kl)
|
| 520 |
+
|
| 521 |
+
decoder_nll = -log_categorical(log_x_start, log_model_prob)
|
| 522 |
+
decoder_nll = sum_except_batch(decoder_nll)
|
| 523 |
+
|
| 524 |
+
mask = (t == torch.zeros_like(t)).float()
|
| 525 |
+
loss = mask * decoder_nll + (1. - mask) * kl
|
| 526 |
+
|
| 527 |
+
return loss
|
| 528 |
+
|
| 529 |
+
def sample_time(self, b, device, method='uniform'):
|
| 530 |
+
if method == 'importance':
|
| 531 |
+
if not (self.Lt_count > 10).all():
|
| 532 |
+
return self.sample_time(b, device, method='uniform')
|
| 533 |
+
|
| 534 |
+
Lt_sqrt = torch.sqrt(self.Lt_history + 1e-10) + 0.0001
|
| 535 |
+
Lt_sqrt[0] = Lt_sqrt[1] # Overwrite decoder term with L1.
|
| 536 |
+
pt_all = (Lt_sqrt / Lt_sqrt.sum()).to(device)
|
| 537 |
+
|
| 538 |
+
t = torch.multinomial(pt_all, num_samples=b, replacement=True).to(device)
|
| 539 |
+
|
| 540 |
+
pt = pt_all.gather(dim=0, index=t)
|
| 541 |
+
|
| 542 |
+
return t, pt
|
| 543 |
+
|
| 544 |
+
elif method == 'uniform':
|
| 545 |
+
t = torch.randint(0, self.num_timesteps, (b,), device=device).long()
|
| 546 |
+
|
| 547 |
+
pt = torch.ones_like(t).float() / self.num_timesteps
|
| 548 |
+
return t, pt
|
| 549 |
+
else:
|
| 550 |
+
raise ValueError
|
| 551 |
+
|
| 552 |
+
def _multinomial_loss(self, model_out, log_x_start, log_x_t, t, pt, out_dict):
|
| 553 |
+
|
| 554 |
+
if self.multinomial_loss_type == 'vb_stochastic':
|
| 555 |
+
kl = self.compute_Lt(
|
| 556 |
+
model_out, log_x_start, log_x_t, t, out_dict
|
| 557 |
+
)
|
| 558 |
+
kl_prior = self.kl_prior(log_x_start)
|
| 559 |
+
# Upweigh loss term of the kl
|
| 560 |
+
vb_loss = kl / pt + kl_prior
|
| 561 |
+
|
| 562 |
+
return vb_loss
|
| 563 |
+
|
| 564 |
+
elif self.multinomial_loss_type == 'vb_all':
|
| 565 |
+
# Expensive, dont do it ;).
|
| 566 |
+
# DEPRECATED
|
| 567 |
+
return -self.nll(log_x_start)
|
| 568 |
+
else:
|
| 569 |
+
raise ValueError()
|
| 570 |
+
|
| 571 |
+
def log_prob(self, x, out_dict):
|
| 572 |
+
b, device = x.size(0), x.device
|
| 573 |
+
if self.training:
|
| 574 |
+
return self._multinomial_loss(x, out_dict)
|
| 575 |
+
|
| 576 |
+
else:
|
| 577 |
+
log_x_start = index_to_log_onehot(x, self.num_classes)
|
| 578 |
+
|
| 579 |
+
t, pt = self.sample_time(b, device, 'importance')
|
| 580 |
+
|
| 581 |
+
kl = self.compute_Lt(
|
| 582 |
+
log_x_start, self.q_sample(log_x_start=log_x_start, t=t), t, out_dict)
|
| 583 |
+
|
| 584 |
+
kl_prior = self.kl_prior(log_x_start)
|
| 585 |
+
|
| 586 |
+
# Upweigh loss term of the kl
|
| 587 |
+
loss = kl / pt + kl_prior
|
| 588 |
+
|
| 589 |
+
return -loss
|
| 590 |
+
|
| 591 |
+
def mixed_loss(self, x, out_dict):
|
| 592 |
+
b = x.shape[0]
|
| 593 |
+
device = x.device
|
| 594 |
+
t, pt = self.sample_time(b, device, 'uniform')
|
| 595 |
+
|
| 596 |
+
x_num = x[:, :self.num_numerical_features]
|
| 597 |
+
x_cat = x[:, self.num_numerical_features:]
|
| 598 |
+
|
| 599 |
+
x_num_t = x_num
|
| 600 |
+
log_x_cat_t = x_cat
|
| 601 |
+
if x_num.shape[1] > 0:
|
| 602 |
+
noise = torch.randn_like(x_num)
|
| 603 |
+
x_num_t = self.gaussian_q_sample(x_num, t, noise=noise)
|
| 604 |
+
if x_cat.shape[1] > 0:
|
| 605 |
+
log_x_cat = index_to_log_onehot(x_cat.long(), self.num_classes)
|
| 606 |
+
log_x_cat_t = self.q_sample(log_x_start=log_x_cat, t=t)
|
| 607 |
+
|
| 608 |
+
x_in = torch.cat([x_num_t, log_x_cat_t], dim=1)
|
| 609 |
+
|
| 610 |
+
model_out = self._denoise_fn(
|
| 611 |
+
x_in,
|
| 612 |
+
t,
|
| 613 |
+
**out_dict
|
| 614 |
+
)
|
| 615 |
+
|
| 616 |
+
model_out_num = model_out[:, :self.num_numerical_features]
|
| 617 |
+
model_out_cat = model_out[:, self.num_numerical_features:]
|
| 618 |
+
|
| 619 |
+
loss_multi = torch.zeros((1,)).float()
|
| 620 |
+
loss_gauss = torch.zeros((1,)).float()
|
| 621 |
+
if x_cat.shape[1] > 0:
|
| 622 |
+
loss_multi = self._multinomial_loss(model_out_cat, log_x_cat, log_x_cat_t, t, pt, out_dict) / len(self.num_classes)
|
| 623 |
+
|
| 624 |
+
if x_num.shape[1] > 0:
|
| 625 |
+
loss_gauss = self._gaussian_loss(model_out_num, x_num, x_num_t, t, noise)
|
| 626 |
+
|
| 627 |
+
# loss_multi = torch.where(out_dict['y'] == 1, loss_multi, 2 * loss_multi)
|
| 628 |
+
# loss_gauss = torch.where(out_dict['y'] == 1, loss_gauss, 2 * loss_gauss)
|
| 629 |
+
|
| 630 |
+
return loss_multi.mean(), loss_gauss.mean()
|
| 631 |
+
|
| 632 |
+
@torch.no_grad()
|
| 633 |
+
def mixed_elbo(self, x0, out_dict):
|
| 634 |
+
b = x0.size(0)
|
| 635 |
+
device = x0.device
|
| 636 |
+
|
| 637 |
+
x_num = x0[:, :self.num_numerical_features]
|
| 638 |
+
x_cat = x0[:, self.num_numerical_features:]
|
| 639 |
+
has_cat = x_cat.shape[1] > 0
|
| 640 |
+
if has_cat:
|
| 641 |
+
log_x_cat = index_to_log_onehot(x_cat.long(), self.num_classes).to(device)
|
| 642 |
+
|
| 643 |
+
gaussian_loss = []
|
| 644 |
+
xstart_mse = []
|
| 645 |
+
mse = []
|
| 646 |
+
mu_mse = []
|
| 647 |
+
out_mean = []
|
| 648 |
+
true_mean = []
|
| 649 |
+
multinomial_loss = []
|
| 650 |
+
for t in range(self.num_timesteps):
|
| 651 |
+
t_array = (torch.ones(b, device=device) * t).long()
|
| 652 |
+
noise = torch.randn_like(x_num)
|
| 653 |
+
|
| 654 |
+
x_num_t = self.gaussian_q_sample(x_start=x_num, t=t_array, noise=noise)
|
| 655 |
+
if has_cat:
|
| 656 |
+
log_x_cat_t = self.q_sample(log_x_start=log_x_cat, t=t_array)
|
| 657 |
+
else:
|
| 658 |
+
log_x_cat_t = x_cat
|
| 659 |
+
|
| 660 |
+
model_out = self._denoise_fn(
|
| 661 |
+
torch.cat([x_num_t, log_x_cat_t], dim=1),
|
| 662 |
+
t_array,
|
| 663 |
+
**out_dict
|
| 664 |
+
)
|
| 665 |
+
|
| 666 |
+
model_out_num = model_out[:, :self.num_numerical_features]
|
| 667 |
+
model_out_cat = model_out[:, self.num_numerical_features:]
|
| 668 |
+
|
| 669 |
+
kl = torch.tensor([0.0])
|
| 670 |
+
if has_cat:
|
| 671 |
+
kl = self.compute_Lt(
|
| 672 |
+
model_out=model_out_cat,
|
| 673 |
+
log_x_start=log_x_cat,
|
| 674 |
+
log_x_t=log_x_cat_t,
|
| 675 |
+
t=t_array,
|
| 676 |
+
out_dict=out_dict
|
| 677 |
+
)
|
| 678 |
+
|
| 679 |
+
out = self._vb_terms_bpd(
|
| 680 |
+
model_out_num,
|
| 681 |
+
x_start=x_num,
|
| 682 |
+
x_t=x_num_t,
|
| 683 |
+
t=t_array,
|
| 684 |
+
clip_denoised=False
|
| 685 |
+
)
|
| 686 |
+
|
| 687 |
+
multinomial_loss.append(kl)
|
| 688 |
+
gaussian_loss.append(out["output"])
|
| 689 |
+
xstart_mse.append(mean_flat((out["pred_xstart"] - x_num) ** 2))
|
| 690 |
+
# mu_mse.append(mean_flat(out["mean_mse"]))
|
| 691 |
+
out_mean.append(mean_flat(out["out_mean"]))
|
| 692 |
+
true_mean.append(mean_flat(out["true_mean"]))
|
| 693 |
+
|
| 694 |
+
eps = self._predict_eps_from_xstart(x_num_t, t_array, out["pred_xstart"])
|
| 695 |
+
mse.append(mean_flat((eps - noise) ** 2))
|
| 696 |
+
|
| 697 |
+
gaussian_loss = torch.stack(gaussian_loss, dim=1)
|
| 698 |
+
multinomial_loss = torch.stack(multinomial_loss, dim=1)
|
| 699 |
+
xstart_mse = torch.stack(xstart_mse, dim=1)
|
| 700 |
+
mse = torch.stack(mse, dim=1)
|
| 701 |
+
# mu_mse = torch.stack(mu_mse, dim=1)
|
| 702 |
+
out_mean = torch.stack(out_mean, dim=1)
|
| 703 |
+
true_mean = torch.stack(true_mean, dim=1)
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
|
| 707 |
+
prior_gauss = self._prior_gaussian(x_num)
|
| 708 |
+
|
| 709 |
+
prior_multin = torch.tensor([0.0])
|
| 710 |
+
if has_cat:
|
| 711 |
+
prior_multin = self.kl_prior(log_x_cat)
|
| 712 |
+
|
| 713 |
+
total_gauss = gaussian_loss.sum(dim=1) + prior_gauss
|
| 714 |
+
total_multin = multinomial_loss.sum(dim=1) + prior_multin
|
| 715 |
+
return {
|
| 716 |
+
"total_gaussian": total_gauss,
|
| 717 |
+
"total_multinomial": total_multin,
|
| 718 |
+
"losses_gaussian": gaussian_loss,
|
| 719 |
+
"losses_multinimial": multinomial_loss,
|
| 720 |
+
"xstart_mse": xstart_mse,
|
| 721 |
+
"mse": mse,
|
| 722 |
+
# "mu_mse": mu_mse
|
| 723 |
+
"out_mean": out_mean,
|
| 724 |
+
"true_mean": true_mean
|
| 725 |
+
}
|
| 726 |
+
|
| 727 |
+
@torch.no_grad()
|
| 728 |
+
def gaussian_ddim_step(
|
| 729 |
+
self,
|
| 730 |
+
model_out_num,
|
| 731 |
+
x,
|
| 732 |
+
t,
|
| 733 |
+
clip_denoised=False,
|
| 734 |
+
denoised_fn=None,
|
| 735 |
+
eta=0.0
|
| 736 |
+
):
|
| 737 |
+
out = self.gaussian_p_mean_variance(
|
| 738 |
+
model_out_num,
|
| 739 |
+
x,
|
| 740 |
+
t,
|
| 741 |
+
clip_denoised=clip_denoised,
|
| 742 |
+
denoised_fn=denoised_fn,
|
| 743 |
+
model_kwargs=None,
|
| 744 |
+
)
|
| 745 |
+
|
| 746 |
+
eps = self._predict_eps_from_xstart(x, t, out["pred_xstart"])
|
| 747 |
+
|
| 748 |
+
alpha_bar = extract(self.alphas_cumprod, t, x.shape)
|
| 749 |
+
alpha_bar_prev = extract(self.alphas_cumprod_prev, t, x.shape)
|
| 750 |
+
sigma = (
|
| 751 |
+
eta
|
| 752 |
+
* torch.sqrt((1 - alpha_bar_prev) / (1 - alpha_bar))
|
| 753 |
+
* torch.sqrt(1 - alpha_bar / alpha_bar_prev)
|
| 754 |
+
)
|
| 755 |
+
|
| 756 |
+
noise = torch.randn_like(x)
|
| 757 |
+
mean_pred = (
|
| 758 |
+
out["pred_xstart"] * torch.sqrt(alpha_bar_prev)
|
| 759 |
+
+ torch.sqrt(1 - alpha_bar_prev - sigma ** 2) * eps
|
| 760 |
+
)
|
| 761 |
+
nonzero_mask = (
|
| 762 |
+
(t != 0).float().view(-1, *([1] * (len(x.shape) - 1)))
|
| 763 |
+
) # no noise when t == 0
|
| 764 |
+
sample = mean_pred + nonzero_mask * sigma * noise
|
| 765 |
+
|
| 766 |
+
return sample
|
| 767 |
+
|
| 768 |
+
@torch.no_grad()
|
| 769 |
+
def gaussian_ddim_sample(
|
| 770 |
+
self,
|
| 771 |
+
noise,
|
| 772 |
+
T,
|
| 773 |
+
out_dict,
|
| 774 |
+
eta=0.0
|
| 775 |
+
):
|
| 776 |
+
x = noise
|
| 777 |
+
b = x.shape[0]
|
| 778 |
+
device = x.device
|
| 779 |
+
for t in reversed(range(T)):
|
| 780 |
+
print(f'Sample timestep {t:4d}', end='\r')
|
| 781 |
+
t_array = (torch.ones(b, device=device) * t).long()
|
| 782 |
+
out_num = self._denoise_fn(x, t_array, **out_dict)
|
| 783 |
+
x = self.gaussian_ddim_step(
|
| 784 |
+
out_num,
|
| 785 |
+
x,
|
| 786 |
+
t_array
|
| 787 |
+
)
|
| 788 |
+
print()
|
| 789 |
+
return x
|
| 790 |
+
|
| 791 |
+
|
| 792 |
+
@torch.no_grad()
|
| 793 |
+
def gaussian_ddim_reverse_step(
|
| 794 |
+
self,
|
| 795 |
+
model_out_num,
|
| 796 |
+
x,
|
| 797 |
+
t,
|
| 798 |
+
clip_denoised=False,
|
| 799 |
+
eta=0.0
|
| 800 |
+
):
|
| 801 |
+
assert eta == 0.0, "Eta must be zero."
|
| 802 |
+
out = self.gaussian_p_mean_variance(
|
| 803 |
+
model_out_num,
|
| 804 |
+
x,
|
| 805 |
+
t,
|
| 806 |
+
clip_denoised=clip_denoised,
|
| 807 |
+
denoised_fn=None,
|
| 808 |
+
model_kwargs=None,
|
| 809 |
+
)
|
| 810 |
+
|
| 811 |
+
eps = (
|
| 812 |
+
extract(self.sqrt_recip_alphas_cumprod, t, x.shape) * x
|
| 813 |
+
- out["pred_xstart"]
|
| 814 |
+
) / extract(self.sqrt_recipm1_alphas_cumprod, t, x.shape)
|
| 815 |
+
alpha_bar_next = extract(self.alphas_cumprod_next, t, x.shape)
|
| 816 |
+
|
| 817 |
+
mean_pred = (
|
| 818 |
+
out["pred_xstart"] * torch.sqrt(alpha_bar_next)
|
| 819 |
+
+ torch.sqrt(1 - alpha_bar_next) * eps
|
| 820 |
+
)
|
| 821 |
+
|
| 822 |
+
return mean_pred
|
| 823 |
+
|
| 824 |
+
@torch.no_grad()
|
| 825 |
+
def gaussian_ddim_reverse_sample(
|
| 826 |
+
self,
|
| 827 |
+
x,
|
| 828 |
+
T,
|
| 829 |
+
out_dict,
|
| 830 |
+
):
|
| 831 |
+
b = x.shape[0]
|
| 832 |
+
device = x.device
|
| 833 |
+
for t in range(T):
|
| 834 |
+
print(f'Reverse timestep {t:4d}', end='\r')
|
| 835 |
+
t_array = (torch.ones(b, device=device) * t).long()
|
| 836 |
+
out_num = self._denoise_fn(x, t_array, **out_dict)
|
| 837 |
+
x = self.gaussian_ddim_reverse_step(
|
| 838 |
+
out_num,
|
| 839 |
+
x,
|
| 840 |
+
t_array,
|
| 841 |
+
eta=0.0
|
| 842 |
+
)
|
| 843 |
+
print()
|
| 844 |
+
|
| 845 |
+
return x
|
| 846 |
+
|
| 847 |
+
|
| 848 |
+
@torch.no_grad()
|
| 849 |
+
def multinomial_ddim_step(
|
| 850 |
+
self,
|
| 851 |
+
model_out_cat,
|
| 852 |
+
log_x_t,
|
| 853 |
+
t,
|
| 854 |
+
out_dict,
|
| 855 |
+
eta=0.0
|
| 856 |
+
):
|
| 857 |
+
# not ddim, essentially
|
| 858 |
+
log_x0 = self.predict_start(model_out_cat, log_x_t=log_x_t, t=t, out_dict=out_dict)
|
| 859 |
+
|
| 860 |
+
alpha_bar = extract(self.alphas_cumprod, t, log_x_t.shape)
|
| 861 |
+
alpha_bar_prev = extract(self.alphas_cumprod_prev, t, log_x_t.shape)
|
| 862 |
+
sigma = (
|
| 863 |
+
eta
|
| 864 |
+
* torch.sqrt((1 - alpha_bar_prev) / (1 - alpha_bar))
|
| 865 |
+
* torch.sqrt(1 - alpha_bar / alpha_bar_prev)
|
| 866 |
+
)
|
| 867 |
+
|
| 868 |
+
coef1 = sigma
|
| 869 |
+
coef2 = alpha_bar_prev - sigma * alpha_bar
|
| 870 |
+
coef3 = 1 - coef1 - coef2
|
| 871 |
+
|
| 872 |
+
|
| 873 |
+
log_ps = torch.stack([
|
| 874 |
+
torch.log(coef1) + log_x_t,
|
| 875 |
+
torch.log(coef2) + log_x0,
|
| 876 |
+
torch.log(coef3) - torch.log(self.num_classes_expanded)
|
| 877 |
+
], dim=2)
|
| 878 |
+
|
| 879 |
+
log_prob = torch.logsumexp(log_ps, dim=2)
|
| 880 |
+
|
| 881 |
+
out = self.log_sample_categorical(log_prob)
|
| 882 |
+
|
| 883 |
+
return out
|
| 884 |
+
|
| 885 |
+
@torch.no_grad()
|
| 886 |
+
def sample_ddim(self, num_samples, y_dist):
|
| 887 |
+
b = num_samples
|
| 888 |
+
device = self.log_alpha.device
|
| 889 |
+
z_norm = torch.randn((b, self.num_numerical_features), device=device)
|
| 890 |
+
|
| 891 |
+
has_cat = self.num_classes[0] != 0
|
| 892 |
+
log_z = torch.zeros((b, 0), device=device).float()
|
| 893 |
+
if has_cat:
|
| 894 |
+
uniform_logits = torch.zeros((b, len(self.num_classes_expanded)), device=device)
|
| 895 |
+
log_z = self.log_sample_categorical(uniform_logits)
|
| 896 |
+
|
| 897 |
+
y = torch.multinomial(
|
| 898 |
+
y_dist,
|
| 899 |
+
num_samples=b,
|
| 900 |
+
replacement=True
|
| 901 |
+
)
|
| 902 |
+
out_dict = {'y': y.long().to(device)}
|
| 903 |
+
for i in reversed(range(0, self.num_timesteps)):
|
| 904 |
+
print(f'Sample timestep {i:4d}', end='\r')
|
| 905 |
+
t = torch.full((b,), i, device=device, dtype=torch.long)
|
| 906 |
+
model_out = self._denoise_fn(
|
| 907 |
+
torch.cat([z_norm, log_z], dim=1).float(),
|
| 908 |
+
t,
|
| 909 |
+
**out_dict
|
| 910 |
+
)
|
| 911 |
+
model_out_num = model_out[:, :self.num_numerical_features]
|
| 912 |
+
model_out_cat = model_out[:, self.num_numerical_features:]
|
| 913 |
+
z_norm = self.gaussian_ddim_step(model_out_num, z_norm, t, clip_denoised=False)
|
| 914 |
+
if has_cat:
|
| 915 |
+
log_z = self.multinomial_ddim_step(model_out_cat, log_z, t, out_dict)
|
| 916 |
+
|
| 917 |
+
print()
|
| 918 |
+
z_ohe = torch.exp(log_z).round()
|
| 919 |
+
z_cat = log_z
|
| 920 |
+
if has_cat:
|
| 921 |
+
z_cat = ohe_to_categories(z_ohe, self.num_classes)
|
| 922 |
+
sample = torch.cat([z_norm, z_cat], dim=1).cpu()
|
| 923 |
+
return sample, out_dict
|
| 924 |
+
|
| 925 |
+
|
| 926 |
+
@torch.no_grad()
|
| 927 |
+
def sample(self, num_samples, y_dist):
|
| 928 |
+
b = num_samples
|
| 929 |
+
device = self.log_alpha.device
|
| 930 |
+
z_norm = torch.randn((b, self.num_numerical_features), device=device)
|
| 931 |
+
|
| 932 |
+
has_cat = self.num_classes[0] != 0
|
| 933 |
+
log_z = torch.zeros((b, 0), device=device).float()
|
| 934 |
+
if has_cat:
|
| 935 |
+
uniform_logits = torch.zeros((b, len(self.num_classes_expanded)), device=device)
|
| 936 |
+
log_z = self.log_sample_categorical(uniform_logits)
|
| 937 |
+
|
| 938 |
+
y = torch.multinomial(
|
| 939 |
+
y_dist,
|
| 940 |
+
num_samples=b,
|
| 941 |
+
replacement=True
|
| 942 |
+
)
|
| 943 |
+
out_dict = {'y': y.long().to(device)}
|
| 944 |
+
for i in reversed(range(0, self.num_timesteps)):
|
| 945 |
+
print(f'Sample timestep {i:4d}', end='\r')
|
| 946 |
+
t = torch.full((b,), i, device=device, dtype=torch.long)
|
| 947 |
+
model_out = self._denoise_fn(
|
| 948 |
+
torch.cat([z_norm, log_z], dim=1).float(),
|
| 949 |
+
t,
|
| 950 |
+
**out_dict
|
| 951 |
+
)
|
| 952 |
+
model_out_num = model_out[:, :self.num_numerical_features]
|
| 953 |
+
model_out_cat = model_out[:, self.num_numerical_features:]
|
| 954 |
+
z_norm = self.gaussian_p_sample(model_out_num, z_norm, t, clip_denoised=False)['sample']
|
| 955 |
+
if has_cat:
|
| 956 |
+
log_z = self.p_sample(model_out_cat, log_z, t, out_dict)
|
| 957 |
+
|
| 958 |
+
print()
|
| 959 |
+
z_ohe = torch.exp(log_z).round()
|
| 960 |
+
z_cat = log_z
|
| 961 |
+
if has_cat:
|
| 962 |
+
z_cat = ohe_to_categories(z_ohe, self.num_classes)
|
| 963 |
+
sample = torch.cat([z_norm, z_cat], dim=1).cpu()
|
| 964 |
+
return sample, out_dict
|
| 965 |
+
|
| 966 |
+
def sample_all(self, num_samples, batch_size, y_dist, ddim=False):
|
| 967 |
+
if ddim:
|
| 968 |
+
print('Sample using DDIM.')
|
| 969 |
+
sample_fn = self.sample_ddim
|
| 970 |
+
else:
|
| 971 |
+
sample_fn = self.sample
|
| 972 |
+
|
| 973 |
+
b = batch_size
|
| 974 |
+
|
| 975 |
+
all_y = []
|
| 976 |
+
all_samples = []
|
| 977 |
+
num_generated = 0
|
| 978 |
+
while num_generated < num_samples:
|
| 979 |
+
sample, out_dict = sample_fn(b, y_dist)
|
| 980 |
+
mask_nan = torch.any(sample.isnan(), dim=1)
|
| 981 |
+
sample = sample[~mask_nan]
|
| 982 |
+
out_dict['y'] = out_dict['y'][~mask_nan]
|
| 983 |
+
|
| 984 |
+
all_samples.append(sample)
|
| 985 |
+
all_y.append(out_dict['y'].cpu())
|
| 986 |
+
if sample.shape[0] != b:
|
| 987 |
+
raise FoundNANsError
|
| 988 |
+
num_generated += sample.shape[0]
|
| 989 |
+
|
| 990 |
+
x_gen = torch.cat(all_samples, dim=0)[:num_samples]
|
| 991 |
+
y_gen = torch.cat(all_y, dim=0)[:num_samples]
|
| 992 |
+
|
| 993 |
+
return x_gen, y_gen
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/modules.py
ADDED
|
@@ -0,0 +1,486 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Code was adapted from https://github.com/Yura52/rtdl
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union, cast
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
import torch.optim
|
| 12 |
+
from torch import Tensor
|
| 13 |
+
|
| 14 |
+
ModuleType = Union[str, Callable[..., nn.Module]]
|
| 15 |
+
|
| 16 |
+
class SiLU(nn.Module):
|
| 17 |
+
def forward(self, x):
|
| 18 |
+
return x * torch.sigmoid(x)
|
| 19 |
+
|
| 20 |
+
def timestep_embedding(timesteps, dim, max_period=10000):
|
| 21 |
+
"""
|
| 22 |
+
Create sinusoidal timestep embeddings.
|
| 23 |
+
|
| 24 |
+
:param timesteps: a 1-D Tensor of N indices, one per batch element.
|
| 25 |
+
These may be fractional.
|
| 26 |
+
:param dim: the dimension of the output.
|
| 27 |
+
:param max_period: controls the minimum frequency of the embeddings.
|
| 28 |
+
:return: an [N x dim] Tensor of positional embeddings.
|
| 29 |
+
"""
|
| 30 |
+
half = dim // 2
|
| 31 |
+
freqs = torch.exp(
|
| 32 |
+
-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
|
| 33 |
+
).to(device=timesteps.device)
|
| 34 |
+
args = timesteps[:, None].float() * freqs[None]
|
| 35 |
+
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
| 36 |
+
if dim % 2:
|
| 37 |
+
embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
|
| 38 |
+
return embedding
|
| 39 |
+
|
| 40 |
+
def _is_glu_activation(activation: ModuleType):
|
| 41 |
+
return (
|
| 42 |
+
isinstance(activation, str)
|
| 43 |
+
and activation.endswith('GLU')
|
| 44 |
+
or activation in [ReGLU, GEGLU]
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _all_or_none(values):
|
| 49 |
+
assert all(x is None for x in values) or all(x is not None for x in values)
|
| 50 |
+
|
| 51 |
+
def reglu(x: Tensor) -> Tensor:
|
| 52 |
+
"""The ReGLU activation function from [1].
|
| 53 |
+
References:
|
| 54 |
+
[1] Noam Shazeer, "GLU Variants Improve Transformer", 2020
|
| 55 |
+
"""
|
| 56 |
+
assert x.shape[-1] % 2 == 0
|
| 57 |
+
a, b = x.chunk(2, dim=-1)
|
| 58 |
+
return a * F.relu(b)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def geglu(x: Tensor) -> Tensor:
|
| 62 |
+
"""The GEGLU activation function from [1].
|
| 63 |
+
References:
|
| 64 |
+
[1] Noam Shazeer, "GLU Variants Improve Transformer", 2020
|
| 65 |
+
"""
|
| 66 |
+
assert x.shape[-1] % 2 == 0
|
| 67 |
+
a, b = x.chunk(2, dim=-1)
|
| 68 |
+
return a * F.gelu(b)
|
| 69 |
+
|
| 70 |
+
class ReGLU(nn.Module):
|
| 71 |
+
"""The ReGLU activation function from [shazeer2020glu].
|
| 72 |
+
|
| 73 |
+
Examples:
|
| 74 |
+
.. testcode::
|
| 75 |
+
|
| 76 |
+
module = ReGLU()
|
| 77 |
+
x = torch.randn(3, 4)
|
| 78 |
+
assert module(x).shape == (3, 2)
|
| 79 |
+
|
| 80 |
+
References:
|
| 81 |
+
* [shazeer2020glu] Noam Shazeer, "GLU Variants Improve Transformer", 2020
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 85 |
+
return reglu(x)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class GEGLU(nn.Module):
|
| 89 |
+
"""The GEGLU activation function from [shazeer2020glu].
|
| 90 |
+
|
| 91 |
+
Examples:
|
| 92 |
+
.. testcode::
|
| 93 |
+
|
| 94 |
+
module = GEGLU()
|
| 95 |
+
x = torch.randn(3, 4)
|
| 96 |
+
assert module(x).shape == (3, 2)
|
| 97 |
+
|
| 98 |
+
References:
|
| 99 |
+
* [shazeer2020glu] Noam Shazeer, "GLU Variants Improve Transformer", 2020
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 103 |
+
return geglu(x)
|
| 104 |
+
|
| 105 |
+
def _make_nn_module(module_type: ModuleType, *args) -> nn.Module:
|
| 106 |
+
return (
|
| 107 |
+
(
|
| 108 |
+
ReGLU()
|
| 109 |
+
if module_type == 'ReGLU'
|
| 110 |
+
else GEGLU()
|
| 111 |
+
if module_type == 'GEGLU'
|
| 112 |
+
else getattr(nn, module_type)(*args)
|
| 113 |
+
)
|
| 114 |
+
if isinstance(module_type, str)
|
| 115 |
+
else module_type(*args)
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class MLP(nn.Module):
|
| 120 |
+
"""The MLP model used in [gorishniy2021revisiting].
|
| 121 |
+
|
| 122 |
+
The following scheme describes the architecture:
|
| 123 |
+
|
| 124 |
+
.. code-block:: text
|
| 125 |
+
|
| 126 |
+
MLP: (in) -> Block -> ... -> Block -> Linear -> (out)
|
| 127 |
+
Block: (in) -> Linear -> Activation -> Dropout -> (out)
|
| 128 |
+
|
| 129 |
+
Examples:
|
| 130 |
+
.. testcode::
|
| 131 |
+
|
| 132 |
+
x = torch.randn(4, 2)
|
| 133 |
+
module = MLP.make_baseline(x.shape[1], [3, 5], 0.1, 1)
|
| 134 |
+
assert module(x).shape == (len(x), 1)
|
| 135 |
+
|
| 136 |
+
References:
|
| 137 |
+
* [gorishniy2021revisiting] Yury Gorishniy, Ivan Rubachev, Valentin Khrulkov, Artem Babenko, "Revisiting Deep Learning Models for Tabular Data", 2021
|
| 138 |
+
"""
|
| 139 |
+
|
| 140 |
+
class Block(nn.Module):
|
| 141 |
+
"""The main building block of `MLP`."""
|
| 142 |
+
|
| 143 |
+
def __init__(
|
| 144 |
+
self,
|
| 145 |
+
*,
|
| 146 |
+
d_in: int,
|
| 147 |
+
d_out: int,
|
| 148 |
+
bias: bool,
|
| 149 |
+
activation: ModuleType,
|
| 150 |
+
dropout: float,
|
| 151 |
+
) -> None:
|
| 152 |
+
super().__init__()
|
| 153 |
+
self.linear = nn.Linear(d_in, d_out, bias)
|
| 154 |
+
self.activation = _make_nn_module(activation)
|
| 155 |
+
self.dropout = nn.Dropout(dropout)
|
| 156 |
+
|
| 157 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 158 |
+
return self.dropout(self.activation(self.linear(x)))
|
| 159 |
+
|
| 160 |
+
def __init__(
|
| 161 |
+
self,
|
| 162 |
+
*,
|
| 163 |
+
d_in: int,
|
| 164 |
+
d_layers: List[int],
|
| 165 |
+
dropouts: Union[float, List[float]],
|
| 166 |
+
activation: Union[str, Callable[[], nn.Module]],
|
| 167 |
+
d_out: int,
|
| 168 |
+
) -> None:
|
| 169 |
+
"""
|
| 170 |
+
Note:
|
| 171 |
+
`make_baseline` is the recommended constructor.
|
| 172 |
+
"""
|
| 173 |
+
super().__init__()
|
| 174 |
+
if isinstance(dropouts, float):
|
| 175 |
+
dropouts = [dropouts] * len(d_layers)
|
| 176 |
+
assert len(d_layers) == len(dropouts)
|
| 177 |
+
assert activation not in ['ReGLU', 'GEGLU']
|
| 178 |
+
|
| 179 |
+
self.blocks = nn.ModuleList(
|
| 180 |
+
[
|
| 181 |
+
MLP.Block(
|
| 182 |
+
d_in=d_layers[i - 1] if i else d_in,
|
| 183 |
+
d_out=d,
|
| 184 |
+
bias=True,
|
| 185 |
+
activation=activation,
|
| 186 |
+
dropout=dropout,
|
| 187 |
+
)
|
| 188 |
+
for i, (d, dropout) in enumerate(zip(d_layers, dropouts))
|
| 189 |
+
]
|
| 190 |
+
)
|
| 191 |
+
self.head = nn.Linear(d_layers[-1] if d_layers else d_in, d_out)
|
| 192 |
+
|
| 193 |
+
@classmethod
|
| 194 |
+
def make_baseline(
|
| 195 |
+
cls: Type['MLP'],
|
| 196 |
+
d_in: int,
|
| 197 |
+
d_layers: List[int],
|
| 198 |
+
dropout: float,
|
| 199 |
+
d_out: int,
|
| 200 |
+
) -> 'MLP':
|
| 201 |
+
"""Create a "baseline" `MLP`.
|
| 202 |
+
|
| 203 |
+
This variation of MLP was used in [gorishniy2021revisiting]. Features:
|
| 204 |
+
|
| 205 |
+
* :code:`Activation` = :code:`ReLU`
|
| 206 |
+
* all linear layers except for the first one and the last one are of the same dimension
|
| 207 |
+
* the dropout rate is the same for all dropout layers
|
| 208 |
+
|
| 209 |
+
Args:
|
| 210 |
+
d_in: the input size
|
| 211 |
+
d_layers: the dimensions of the linear layers. If there are more than two
|
| 212 |
+
layers, then all of them except for the first and the last ones must
|
| 213 |
+
have the same dimension. Valid examples: :code:`[]`, :code:`[8]`,
|
| 214 |
+
:code:`[8, 16]`, :code:`[2, 2, 2, 2]`, :code:`[1, 2, 2, 4]`. Invalid
|
| 215 |
+
example: :code:`[1, 2, 3, 4]`.
|
| 216 |
+
dropout: the dropout rate for all hidden layers
|
| 217 |
+
d_out: the output size
|
| 218 |
+
Returns:
|
| 219 |
+
MLP
|
| 220 |
+
|
| 221 |
+
References:
|
| 222 |
+
* [gorishniy2021revisiting] Yury Gorishniy, Ivan Rubachev, Valentin Khrulkov, Artem Babenko, "Revisiting Deep Learning Models for Tabular Data", 2021
|
| 223 |
+
"""
|
| 224 |
+
assert isinstance(dropout, float)
|
| 225 |
+
if len(d_layers) > 2:
|
| 226 |
+
assert len(set(d_layers[1:-1])) == 1, (
|
| 227 |
+
'if d_layers contains more than two elements, then'
|
| 228 |
+
' all elements except for the first and the last ones must be equal.'
|
| 229 |
+
)
|
| 230 |
+
return MLP(
|
| 231 |
+
d_in=d_in,
|
| 232 |
+
d_layers=d_layers, # type: ignore
|
| 233 |
+
dropouts=dropout,
|
| 234 |
+
activation='ReLU',
|
| 235 |
+
d_out=d_out,
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 239 |
+
x = x.float()
|
| 240 |
+
for block in self.blocks:
|
| 241 |
+
x = block(x)
|
| 242 |
+
x = self.head(x)
|
| 243 |
+
return x
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
class ResNet(nn.Module):
|
| 247 |
+
"""The ResNet model used in [gorishniy2021revisiting].
|
| 248 |
+
The following scheme describes the architecture:
|
| 249 |
+
.. code-block:: text
|
| 250 |
+
ResNet: (in) -> Linear -> Block -> ... -> Block -> Head -> (out)
|
| 251 |
+
|-> Norm -> Linear -> Activation -> Dropout -> Linear -> Dropout ->|
|
| 252 |
+
| |
|
| 253 |
+
Block: (in) ------------------------------------------------------------> Add -> (out)
|
| 254 |
+
Head: (in) -> Norm -> Activation -> Linear -> (out)
|
| 255 |
+
Examples:
|
| 256 |
+
.. testcode::
|
| 257 |
+
x = torch.randn(4, 2)
|
| 258 |
+
module = ResNet.make_baseline(
|
| 259 |
+
d_in=x.shape[1],
|
| 260 |
+
n_blocks=2,
|
| 261 |
+
d_main=3,
|
| 262 |
+
d_hidden=4,
|
| 263 |
+
dropout_first=0.25,
|
| 264 |
+
dropout_second=0.0,
|
| 265 |
+
d_out=1
|
| 266 |
+
)
|
| 267 |
+
assert module(x).shape == (len(x), 1)
|
| 268 |
+
References:
|
| 269 |
+
* [gorishniy2021revisiting] Yury Gorishniy, Ivan Rubachev, Valentin Khrulkov, Artem Babenko, "Revisiting Deep Learning Models for Tabular Data", 2021
|
| 270 |
+
"""
|
| 271 |
+
|
| 272 |
+
class Block(nn.Module):
|
| 273 |
+
"""The main building block of `ResNet`."""
|
| 274 |
+
|
| 275 |
+
def __init__(
|
| 276 |
+
self,
|
| 277 |
+
*,
|
| 278 |
+
d_main: int,
|
| 279 |
+
d_hidden: int,
|
| 280 |
+
bias_first: bool,
|
| 281 |
+
bias_second: bool,
|
| 282 |
+
dropout_first: float,
|
| 283 |
+
dropout_second: float,
|
| 284 |
+
normalization: ModuleType,
|
| 285 |
+
activation: ModuleType,
|
| 286 |
+
skip_connection: bool,
|
| 287 |
+
) -> None:
|
| 288 |
+
super().__init__()
|
| 289 |
+
self.normalization = _make_nn_module(normalization, d_main)
|
| 290 |
+
self.linear_first = nn.Linear(d_main, d_hidden, bias_first)
|
| 291 |
+
self.activation = _make_nn_module(activation)
|
| 292 |
+
self.dropout_first = nn.Dropout(dropout_first)
|
| 293 |
+
self.linear_second = nn.Linear(d_hidden, d_main, bias_second)
|
| 294 |
+
self.dropout_second = nn.Dropout(dropout_second)
|
| 295 |
+
self.skip_connection = skip_connection
|
| 296 |
+
|
| 297 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 298 |
+
x_input = x
|
| 299 |
+
x = self.normalization(x)
|
| 300 |
+
x = self.linear_first(x)
|
| 301 |
+
x = self.activation(x)
|
| 302 |
+
x = self.dropout_first(x)
|
| 303 |
+
x = self.linear_second(x)
|
| 304 |
+
x = self.dropout_second(x)
|
| 305 |
+
if self.skip_connection:
|
| 306 |
+
x = x_input + x
|
| 307 |
+
return x
|
| 308 |
+
|
| 309 |
+
class Head(nn.Module):
|
| 310 |
+
"""The final module of `ResNet`."""
|
| 311 |
+
|
| 312 |
+
def __init__(
|
| 313 |
+
self,
|
| 314 |
+
*,
|
| 315 |
+
d_in: int,
|
| 316 |
+
d_out: int,
|
| 317 |
+
bias: bool,
|
| 318 |
+
normalization: ModuleType,
|
| 319 |
+
activation: ModuleType,
|
| 320 |
+
) -> None:
|
| 321 |
+
super().__init__()
|
| 322 |
+
self.normalization = _make_nn_module(normalization, d_in)
|
| 323 |
+
self.activation = _make_nn_module(activation)
|
| 324 |
+
self.linear = nn.Linear(d_in, d_out, bias)
|
| 325 |
+
|
| 326 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 327 |
+
if self.normalization is not None:
|
| 328 |
+
x = self.normalization(x)
|
| 329 |
+
x = self.activation(x)
|
| 330 |
+
x = self.linear(x)
|
| 331 |
+
return x
|
| 332 |
+
|
| 333 |
+
def __init__(
|
| 334 |
+
self,
|
| 335 |
+
*,
|
| 336 |
+
d_in: int,
|
| 337 |
+
n_blocks: int,
|
| 338 |
+
d_main: int,
|
| 339 |
+
d_hidden: int,
|
| 340 |
+
dropout_first: float,
|
| 341 |
+
dropout_second: float,
|
| 342 |
+
normalization: ModuleType,
|
| 343 |
+
activation: ModuleType,
|
| 344 |
+
d_out: int,
|
| 345 |
+
) -> None:
|
| 346 |
+
"""
|
| 347 |
+
Note:
|
| 348 |
+
`make_baseline` is the recommended constructor.
|
| 349 |
+
"""
|
| 350 |
+
super().__init__()
|
| 351 |
+
|
| 352 |
+
self.first_layer = nn.Linear(d_in, d_main)
|
| 353 |
+
if d_main is None:
|
| 354 |
+
d_main = d_in
|
| 355 |
+
self.blocks = nn.Sequential(
|
| 356 |
+
*[
|
| 357 |
+
ResNet.Block(
|
| 358 |
+
d_main=d_main,
|
| 359 |
+
d_hidden=d_hidden,
|
| 360 |
+
bias_first=True,
|
| 361 |
+
bias_second=True,
|
| 362 |
+
dropout_first=dropout_first,
|
| 363 |
+
dropout_second=dropout_second,
|
| 364 |
+
normalization=normalization,
|
| 365 |
+
activation=activation,
|
| 366 |
+
skip_connection=True,
|
| 367 |
+
)
|
| 368 |
+
for _ in range(n_blocks)
|
| 369 |
+
]
|
| 370 |
+
)
|
| 371 |
+
self.head = ResNet.Head(
|
| 372 |
+
d_in=d_main,
|
| 373 |
+
d_out=d_out,
|
| 374 |
+
bias=True,
|
| 375 |
+
normalization=normalization,
|
| 376 |
+
activation=activation,
|
| 377 |
+
)
|
| 378 |
+
|
| 379 |
+
@classmethod
|
| 380 |
+
def make_baseline(
|
| 381 |
+
cls: Type['ResNet'],
|
| 382 |
+
*,
|
| 383 |
+
d_in: int,
|
| 384 |
+
n_blocks: int,
|
| 385 |
+
d_main: int,
|
| 386 |
+
d_hidden: int,
|
| 387 |
+
dropout_first: float,
|
| 388 |
+
dropout_second: float,
|
| 389 |
+
d_out: int,
|
| 390 |
+
) -> 'ResNet':
|
| 391 |
+
"""Create a "baseline" `ResNet`.
|
| 392 |
+
This variation of ResNet was used in [gorishniy2021revisiting]. Features:
|
| 393 |
+
* :code:`Activation` = :code:`ReLU`
|
| 394 |
+
* :code:`Norm` = :code:`BatchNorm1d`
|
| 395 |
+
Args:
|
| 396 |
+
d_in: the input size
|
| 397 |
+
n_blocks: the number of Blocks
|
| 398 |
+
d_main: the input size (or, equivalently, the output size) of each Block
|
| 399 |
+
d_hidden: the output size of the first linear layer in each Block
|
| 400 |
+
dropout_first: the dropout rate of the first dropout layer in each Block.
|
| 401 |
+
dropout_second: the dropout rate of the second dropout layer in each Block.
|
| 402 |
+
References:
|
| 403 |
+
* [gorishniy2021revisiting] Yury Gorishniy, Ivan Rubachev, Valentin Khrulkov, Artem Babenko, "Revisiting Deep Learning Models for Tabular Data", 2021
|
| 404 |
+
"""
|
| 405 |
+
return cls(
|
| 406 |
+
d_in=d_in,
|
| 407 |
+
n_blocks=n_blocks,
|
| 408 |
+
d_main=d_main,
|
| 409 |
+
d_hidden=d_hidden,
|
| 410 |
+
dropout_first=dropout_first,
|
| 411 |
+
dropout_second=dropout_second,
|
| 412 |
+
normalization='BatchNorm1d',
|
| 413 |
+
activation='ReLU',
|
| 414 |
+
d_out=d_out,
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 418 |
+
x = x.float()
|
| 419 |
+
x = self.first_layer(x)
|
| 420 |
+
x = self.blocks(x)
|
| 421 |
+
x = self.head(x)
|
| 422 |
+
return x
|
| 423 |
+
#### For diffusion
|
| 424 |
+
|
| 425 |
+
class MLPDiffusion(nn.Module):
|
| 426 |
+
def __init__(self, d_in, num_classes, is_y_cond, rtdl_params, dim_t = 128):
|
| 427 |
+
super().__init__()
|
| 428 |
+
self.dim_t = dim_t
|
| 429 |
+
self.num_classes = num_classes
|
| 430 |
+
self.is_y_cond = is_y_cond
|
| 431 |
+
|
| 432 |
+
# d0 = rtdl_params['d_layers'][0]
|
| 433 |
+
|
| 434 |
+
rtdl_params['d_in'] = dim_t
|
| 435 |
+
rtdl_params['d_out'] = d_in
|
| 436 |
+
|
| 437 |
+
self.mlp = MLP.make_baseline(**rtdl_params)
|
| 438 |
+
|
| 439 |
+
if self.num_classes > 0 and is_y_cond:
|
| 440 |
+
self.label_emb = nn.Embedding(self.num_classes, dim_t)
|
| 441 |
+
elif self.num_classes == 0 and is_y_cond:
|
| 442 |
+
self.label_emb = nn.Linear(1, dim_t)
|
| 443 |
+
|
| 444 |
+
self.proj = nn.Linear(d_in, dim_t)
|
| 445 |
+
self.time_embed = nn.Sequential(
|
| 446 |
+
nn.Linear(dim_t, dim_t),
|
| 447 |
+
nn.SiLU(),
|
| 448 |
+
nn.Linear(dim_t, dim_t)
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
def forward(self, x, timesteps, y=None):
|
| 452 |
+
emb = self.time_embed(timestep_embedding(timesteps, self.dim_t))
|
| 453 |
+
if self.is_y_cond and y is not None:
|
| 454 |
+
if self.num_classes > 0:
|
| 455 |
+
y = y.squeeze()
|
| 456 |
+
else:
|
| 457 |
+
y = y.resize(y.size(0), 1).float()
|
| 458 |
+
emb += F.silu(self.label_emb(y))
|
| 459 |
+
x = self.proj(x) + emb
|
| 460 |
+
return self.mlp(x)
|
| 461 |
+
|
| 462 |
+
class ResNetDiffusion(nn.Module):
|
| 463 |
+
def __init__(self, d_in, num_classes, rtdl_params, dim_t = 256):
|
| 464 |
+
super().__init__()
|
| 465 |
+
self.dim_t = dim_t
|
| 466 |
+
self.num_classes = num_classes
|
| 467 |
+
|
| 468 |
+
rtdl_params['d_in'] = d_in
|
| 469 |
+
rtdl_params['d_out'] = d_in
|
| 470 |
+
rtdl_params['emb_d'] = dim_t
|
| 471 |
+
self.resnet = ResNet.make_baseline(**rtdl_params)
|
| 472 |
+
|
| 473 |
+
if self.num_classes > 0:
|
| 474 |
+
self.label_emb = nn.Embedding(self.num_classes, dim_t)
|
| 475 |
+
|
| 476 |
+
self.time_embed = nn.Sequential(
|
| 477 |
+
nn.Linear(dim_t, dim_t),
|
| 478 |
+
nn.SiLU(),
|
| 479 |
+
nn.Linear(dim_t, dim_t)
|
| 480 |
+
)
|
| 481 |
+
|
| 482 |
+
def forward(self, x, timesteps, y=None):
|
| 483 |
+
emb = self.time_embed(timestep_embedding(timesteps, self.dim_t))
|
| 484 |
+
if y is not None and self.num_classes > 0:
|
| 485 |
+
emb += self.label_emb(y.squeeze())
|
| 486 |
+
return self.resnet(x, emb)
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/utils.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
from torch.profiler import record_function
|
| 5 |
+
from inspect import isfunction
|
| 6 |
+
|
| 7 |
+
def normal_kl(mean1, logvar1, mean2, logvar2):
|
| 8 |
+
"""
|
| 9 |
+
Compute the KL divergence between two gaussians.
|
| 10 |
+
|
| 11 |
+
Shapes are automatically broadcasted, so batches can be compared to
|
| 12 |
+
scalars, among other use cases.
|
| 13 |
+
"""
|
| 14 |
+
tensor = None
|
| 15 |
+
for obj in (mean1, logvar1, mean2, logvar2):
|
| 16 |
+
if isinstance(obj, torch.Tensor):
|
| 17 |
+
tensor = obj
|
| 18 |
+
break
|
| 19 |
+
assert tensor is not None, "at least one argument must be a Tensor"
|
| 20 |
+
|
| 21 |
+
# Force variances to be Tensors. Broadcasting helps convert scalars to
|
| 22 |
+
# Tensors, but it does not work for torch.exp().
|
| 23 |
+
logvar1, logvar2 = [
|
| 24 |
+
x if isinstance(x, torch.Tensor) else torch.tensor(x).to(tensor)
|
| 25 |
+
for x in (logvar1, logvar2)
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
return 0.5 * (
|
| 29 |
+
-1.0
|
| 30 |
+
+ logvar2
|
| 31 |
+
- logvar1
|
| 32 |
+
+ torch.exp(logvar1 - logvar2)
|
| 33 |
+
+ ((mean1 - mean2) ** 2) * torch.exp(-logvar2)
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
def approx_standard_normal_cdf(x):
|
| 37 |
+
"""
|
| 38 |
+
A fast approximation of the cumulative distribution function of the
|
| 39 |
+
standard normal.
|
| 40 |
+
"""
|
| 41 |
+
return 0.5 * (1.0 + torch.tanh(np.sqrt(2.0 / np.pi) * (x + 0.044715 * torch.pow(x, 3))))
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def discretized_gaussian_log_likelihood(x, *, means, log_scales):
|
| 45 |
+
"""
|
| 46 |
+
Compute the log-likelihood of a Gaussian distribution discretizing to a
|
| 47 |
+
given image.
|
| 48 |
+
|
| 49 |
+
:param x: the target images. It is assumed that this was uint8 values,
|
| 50 |
+
rescaled to the range [-1, 1].
|
| 51 |
+
:param means: the Gaussian mean Tensor.
|
| 52 |
+
:param log_scales: the Gaussian log stddev Tensor.
|
| 53 |
+
:return: a tensor like x of log probabilities (in nats).
|
| 54 |
+
"""
|
| 55 |
+
assert x.shape == means.shape == log_scales.shape
|
| 56 |
+
centered_x = x - means
|
| 57 |
+
inv_stdv = torch.exp(-log_scales)
|
| 58 |
+
plus_in = inv_stdv * (centered_x + 1.0 / 255.0)
|
| 59 |
+
cdf_plus = approx_standard_normal_cdf(plus_in)
|
| 60 |
+
min_in = inv_stdv * (centered_x - 1.0 / 255.0)
|
| 61 |
+
cdf_min = approx_standard_normal_cdf(min_in)
|
| 62 |
+
log_cdf_plus = torch.log(cdf_plus.clamp(min=1e-12))
|
| 63 |
+
log_one_minus_cdf_min = torch.log((1.0 - cdf_min).clamp(min=1e-12))
|
| 64 |
+
cdf_delta = cdf_plus - cdf_min
|
| 65 |
+
log_probs = torch.where(
|
| 66 |
+
x < -0.999,
|
| 67 |
+
log_cdf_plus,
|
| 68 |
+
torch.where(x > 0.999, log_one_minus_cdf_min, torch.log(cdf_delta.clamp(min=1e-12))),
|
| 69 |
+
)
|
| 70 |
+
assert log_probs.shape == x.shape
|
| 71 |
+
return log_probs
|
| 72 |
+
|
| 73 |
+
def sum_except_batch(x, num_dims=1):
|
| 74 |
+
'''
|
| 75 |
+
Sums all dimensions except the first.
|
| 76 |
+
|
| 77 |
+
Args:
|
| 78 |
+
x: Tensor, shape (batch_size, ...)
|
| 79 |
+
num_dims: int, number of batch dims (default=1)
|
| 80 |
+
|
| 81 |
+
Returns:
|
| 82 |
+
x_sum: Tensor, shape (batch_size,)
|
| 83 |
+
'''
|
| 84 |
+
return x.reshape(*x.shape[:num_dims], -1).sum(-1)
|
| 85 |
+
|
| 86 |
+
def mean_flat(tensor):
|
| 87 |
+
"""
|
| 88 |
+
Take the mean over all non-batch dimensions.
|
| 89 |
+
"""
|
| 90 |
+
return tensor.mean(dim=list(range(1, len(tensor.shape))))
|
| 91 |
+
|
| 92 |
+
def ohe_to_categories(ohe, K):
|
| 93 |
+
K = torch.from_numpy(K)
|
| 94 |
+
indices = torch.cat([torch.zeros((1,)), K.cumsum(dim=0)], dim=0).int().tolist()
|
| 95 |
+
res = []
|
| 96 |
+
for i in range(len(indices) - 1):
|
| 97 |
+
res.append(ohe[:, indices[i]:indices[i+1]].argmax(dim=1))
|
| 98 |
+
return torch.stack(res, dim=1)
|
| 99 |
+
|
| 100 |
+
def log_1_min_a(a):
|
| 101 |
+
return torch.log(1 - a.exp() + 1e-40)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def log_add_exp(a, b):
|
| 105 |
+
maximum = torch.max(a, b)
|
| 106 |
+
return maximum + torch.log(torch.exp(a - maximum) + torch.exp(b - maximum))
|
| 107 |
+
|
| 108 |
+
def exists(x):
|
| 109 |
+
return x is not None
|
| 110 |
+
|
| 111 |
+
def extract(a, t, x_shape):
|
| 112 |
+
b, *_ = t.shape
|
| 113 |
+
t = t.to(a.device)
|
| 114 |
+
out = a.gather(-1, t)
|
| 115 |
+
while len(out.shape) < len(x_shape):
|
| 116 |
+
out = out[..., None]
|
| 117 |
+
return out.expand(x_shape)
|
| 118 |
+
|
| 119 |
+
def default(val, d):
|
| 120 |
+
if exists(val):
|
| 121 |
+
return val
|
| 122 |
+
return d() if isfunction(d) else d
|
| 123 |
+
|
| 124 |
+
def log_categorical(log_x_start, log_prob):
|
| 125 |
+
return (log_x_start.exp() * log_prob).sum(dim=1)
|
| 126 |
+
|
| 127 |
+
def index_to_log_onehot(x, num_classes):
|
| 128 |
+
onehots = []
|
| 129 |
+
for i in range(len(num_classes)):
|
| 130 |
+
onehots.append(F.one_hot(x[:, i], num_classes[i]))
|
| 131 |
+
|
| 132 |
+
x_onehot = torch.cat(onehots, dim=1)
|
| 133 |
+
log_onehot = torch.log(x_onehot.float().clamp(min=1e-30))
|
| 134 |
+
return log_onehot
|
| 135 |
+
|
| 136 |
+
def log_sum_exp_by_classes(x, slices):
|
| 137 |
+
device = x.device
|
| 138 |
+
res = torch.zeros_like(x)
|
| 139 |
+
for ixs in slices:
|
| 140 |
+
res[:, ixs] = torch.logsumexp(x[:, ixs], dim=1, keepdim=True)
|
| 141 |
+
|
| 142 |
+
assert x.size() == res.size()
|
| 143 |
+
|
| 144 |
+
return res
|
| 145 |
+
|
| 146 |
+
@torch.jit.script
|
| 147 |
+
def log_sub_exp(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
|
| 148 |
+
m = torch.maximum(a, b)
|
| 149 |
+
return torch.log(torch.exp(a - m) - torch.exp(b - m)) + m
|
| 150 |
+
|
| 151 |
+
@torch.jit.script
|
| 152 |
+
def sliced_logsumexp(x, slices):
|
| 153 |
+
lse = torch.logcumsumexp(
|
| 154 |
+
torch.nn.functional.pad(x, [1, 0, 0, 0], value=-float('inf')),
|
| 155 |
+
dim=-1)
|
| 156 |
+
|
| 157 |
+
slice_starts = slices[:-1]
|
| 158 |
+
slice_ends = slices[1:]
|
| 159 |
+
|
| 160 |
+
slice_lse = log_sub_exp(lse[:, slice_ends], lse[:, slice_starts])
|
| 161 |
+
slice_lse_repeated = torch.repeat_interleave(
|
| 162 |
+
slice_lse,
|
| 163 |
+
slice_ends - slice_starts,
|
| 164 |
+
dim=-1
|
| 165 |
+
)
|
| 166 |
+
return slice_lse_repeated
|
| 167 |
+
|
| 168 |
+
def log_onehot_to_index(log_x):
|
| 169 |
+
return log_x.argmax(1)
|
| 170 |
+
|
| 171 |
+
class FoundNANsError(BaseException):
|
| 172 |
+
"""Found NANs during sampling"""
|
| 173 |
+
def __init__(self, message='Found NANs during sampling.'):
|
| 174 |
+
super(FoundNANsError, self).__init__(message)
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tools/convert_synth_to_csv.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Convert generated synthetic data from npy files to CSV format.
|
| 4 |
+
"""
|
| 5 |
+
import os
|
| 6 |
+
import sys
|
| 7 |
+
import numpy as np
|
| 8 |
+
import pandas as pd
|
| 9 |
+
import argparse
|
| 10 |
+
|
| 11 |
+
def convert_to_csv(parent_dir, output_path=None):
|
| 12 |
+
"""
|
| 13 |
+
Convert generated synthetic data to CSV.
|
| 14 |
+
|
| 15 |
+
Args:
|
| 16 |
+
parent_dir: Directory containing X_num_train.npy, X_cat_train.npy, y_train.npy
|
| 17 |
+
output_path: Output CSV file path (default: parent_dir/synth_train.csv)
|
| 18 |
+
"""
|
| 19 |
+
parent_dir = os.path.abspath(parent_dir)
|
| 20 |
+
|
| 21 |
+
# Load npy files
|
| 22 |
+
x_num_path = os.path.join(parent_dir, 'X_num_train.npy')
|
| 23 |
+
x_cat_path = os.path.join(parent_dir, 'X_cat_train.npy')
|
| 24 |
+
y_path = os.path.join(parent_dir, 'y_train.npy')
|
| 25 |
+
|
| 26 |
+
data_parts = []
|
| 27 |
+
column_names = []
|
| 28 |
+
|
| 29 |
+
# Load numerical features
|
| 30 |
+
if os.path.exists(x_num_path):
|
| 31 |
+
X_num = np.load(x_num_path, allow_pickle=True)
|
| 32 |
+
print(f"Loaded X_num: shape {X_num.shape}")
|
| 33 |
+
data_parts.append(X_num)
|
| 34 |
+
# Create column names for numerical features
|
| 35 |
+
for i in range(X_num.shape[1]):
|
| 36 |
+
column_names.append(f'num_{i}')
|
| 37 |
+
|
| 38 |
+
# Load categorical features
|
| 39 |
+
if os.path.exists(x_cat_path):
|
| 40 |
+
X_cat = np.load(x_cat_path, allow_pickle=True)
|
| 41 |
+
print(f"Loaded X_cat: shape {X_cat.shape}")
|
| 42 |
+
data_parts.append(X_cat)
|
| 43 |
+
# Create column names for categorical features
|
| 44 |
+
for i in range(X_cat.shape[1]):
|
| 45 |
+
column_names.append(f'cat_{i}')
|
| 46 |
+
|
| 47 |
+
# Load target
|
| 48 |
+
if os.path.exists(y_path):
|
| 49 |
+
y = np.load(y_path, allow_pickle=True)
|
| 50 |
+
print(f"Loaded y: shape {y.shape}")
|
| 51 |
+
# Reshape if needed
|
| 52 |
+
if y.ndim == 1:
|
| 53 |
+
y = y.reshape(-1, 1)
|
| 54 |
+
data_parts.append(y)
|
| 55 |
+
column_names.append('y')
|
| 56 |
+
|
| 57 |
+
if not data_parts:
|
| 58 |
+
raise ValueError(f"No data files found in {parent_dir}")
|
| 59 |
+
|
| 60 |
+
# Concatenate all parts
|
| 61 |
+
data = np.hstack(data_parts)
|
| 62 |
+
print(f"Combined data shape: {data.shape}")
|
| 63 |
+
print(f"Number of columns: {len(column_names)}")
|
| 64 |
+
|
| 65 |
+
# Create DataFrame
|
| 66 |
+
df = pd.DataFrame(data, columns=column_names)
|
| 67 |
+
|
| 68 |
+
# Determine output path
|
| 69 |
+
if output_path is None:
|
| 70 |
+
output_path = os.path.join(parent_dir, 'synth_train.csv')
|
| 71 |
+
|
| 72 |
+
# Save to CSV
|
| 73 |
+
df.to_csv(output_path, index=False)
|
| 74 |
+
print(f"[OK] Saved synthetic data to: {output_path}")
|
| 75 |
+
print(f"[OK] Total samples: {len(df)}, Total columns: {len(df.columns)}")
|
| 76 |
+
|
| 77 |
+
# Print summary statistics
|
| 78 |
+
print("\n=== Data Summary ===")
|
| 79 |
+
print(df.describe())
|
| 80 |
+
|
| 81 |
+
return output_path
|
| 82 |
+
|
| 83 |
+
if __name__ == '__main__':
|
| 84 |
+
parser = argparse.ArgumentParser(description='Convert synthetic npy files to CSV')
|
| 85 |
+
parser.add_argument('parent_dir', type=str, help='Directory containing generated npy files')
|
| 86 |
+
parser.add_argument('--output', '-o', type=str, default=None, help='Output CSV file path (default: parent_dir/synth_train.csv)')
|
| 87 |
+
|
| 88 |
+
args = parser.parse_args()
|
| 89 |
+
convert_to_csv(args.parent_dir, args.output)
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tools/make_tabddpm_info.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os, json
|
| 2 |
+
import numpy as np
|
| 3 |
+
|
| 4 |
+
def load(path):
|
| 5 |
+
return np.load(path, allow_pickle=True)
|
| 6 |
+
|
| 7 |
+
def main(data_dir: str):
|
| 8 |
+
# required files
|
| 9 |
+
req = [
|
| 10 |
+
"X_num_train.npy","X_num_val.npy","X_num_test.npy",
|
| 11 |
+
"X_cat_train.npy","X_cat_val.npy","X_cat_test.npy",
|
| 12 |
+
"y_train.npy","y_val.npy","y_test.npy"
|
| 13 |
+
]
|
| 14 |
+
for f in req:
|
| 15 |
+
p = os.path.join(data_dir, f)
|
| 16 |
+
if not os.path.exists(p):
|
| 17 |
+
raise FileNotFoundError(p)
|
| 18 |
+
|
| 19 |
+
Xn_tr = load(os.path.join(data_dir,"X_num_train.npy"))
|
| 20 |
+
Xc_tr = load(os.path.join(data_dir,"X_cat_train.npy"))
|
| 21 |
+
y_tr = load(os.path.join(data_dir,"y_train.npy"))
|
| 22 |
+
|
| 23 |
+
# basic dims
|
| 24 |
+
n_num = 0 if Xn_tr.ndim < 2 else int(Xn_tr.shape[1])
|
| 25 |
+
n_cat = 0 if Xc_tr.ndim < 2 else int(Xc_tr.shape[1])
|
| 26 |
+
|
| 27 |
+
# infer task / y info
|
| 28 |
+
y_flat = y_tr.reshape(-1)
|
| 29 |
+
uniq = np.unique(y_flat)
|
| 30 |
+
# if y is integer and has few unique values, could be classification
|
| 31 |
+
is_int = np.issubdtype(y_flat.dtype, np.integer)
|
| 32 |
+
num_classes = int(len(uniq)) if is_int else 0
|
| 33 |
+
|
| 34 |
+
# determine task_type
|
| 35 |
+
if is_int and num_classes == 2:
|
| 36 |
+
task_type = "binclass"
|
| 37 |
+
elif is_int and num_classes > 2 and num_classes <= 100:
|
| 38 |
+
task_type = "multiclass"
|
| 39 |
+
else:
|
| 40 |
+
task_type = "regression"
|
| 41 |
+
|
| 42 |
+
# cat sizes (per categorical column)
|
| 43 |
+
cat_sizes = []
|
| 44 |
+
if n_cat > 0:
|
| 45 |
+
# compute max+1 per column (assume categories encoded 0..K-1)
|
| 46 |
+
for j in range(n_cat):
|
| 47 |
+
col = Xc_tr[:, j].reshape(-1)
|
| 48 |
+
if col.size == 0:
|
| 49 |
+
cat_sizes.append(0)
|
| 50 |
+
else:
|
| 51 |
+
mx = int(np.max(col))
|
| 52 |
+
cat_sizes.append(mx + 1)
|
| 53 |
+
|
| 54 |
+
# numeric stats (optional but useful)
|
| 55 |
+
num_stats = {}
|
| 56 |
+
if n_num > 0:
|
| 57 |
+
# mean/std/min/max over train numeric
|
| 58 |
+
num_stats = {
|
| 59 |
+
"mean": np.mean(Xn_tr, axis=0).tolist(),
|
| 60 |
+
"std": (np.std(Xn_tr, axis=0) + 1e-12).tolist(),
|
| 61 |
+
"min": np.min(Xn_tr, axis=0).tolist(),
|
| 62 |
+
"max": np.max(Xn_tr, axis=0).tolist(),
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
# This repo expects info.json. Keep fields simple & robust.
|
| 66 |
+
info = {
|
| 67 |
+
"task_type": task_type,
|
| 68 |
+
"n_num_features": n_num,
|
| 69 |
+
"n_cat_features": n_cat,
|
| 70 |
+
"cat_sizes": cat_sizes,
|
| 71 |
+
"y_dtype": str(y_flat.dtype),
|
| 72 |
+
"y_unique_count": int(len(uniq)),
|
| 73 |
+
"y_unique_head": uniq[:20].tolist(),
|
| 74 |
+
# heuristics: user can override in config.toml
|
| 75 |
+
"is_classification_like": bool(is_int and len(uniq) <= 100),
|
| 76 |
+
"num_classes_like": num_classes,
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
# write files
|
| 80 |
+
with open(os.path.join(data_dir, "info.json"), "w", encoding="utf-8") as f:
|
| 81 |
+
json.dump(info, f, ensure_ascii=False, indent=2)
|
| 82 |
+
|
| 83 |
+
# some codepaths may look for these (harmless if unused)
|
| 84 |
+
with open(os.path.join(data_dir, "cat_sizes.json"), "w", encoding="utf-8") as f:
|
| 85 |
+
json.dump({"cat_sizes": cat_sizes}, f, ensure_ascii=False, indent=2)
|
| 86 |
+
|
| 87 |
+
with open(os.path.join(data_dir, "num_stats.json"), "w", encoding="utf-8") as f:
|
| 88 |
+
json.dump(num_stats, f, ensure_ascii=False, indent=2)
|
| 89 |
+
|
| 90 |
+
print("[OK] wrote:", os.path.join(data_dir,"info.json"))
|
| 91 |
+
print("[OK] n_num =", n_num, "n_cat =", n_cat, "cat_sizes =", cat_sizes)
|
| 92 |
+
print("[OK] y unique count =", len(uniq), "head =", uniq[:20])
|
| 93 |
+
|
| 94 |
+
if __name__ == "__main__":
|
| 95 |
+
data_dir = "data/Tab-Cate-1"
|
| 96 |
+
main(data_dir)
|
| 97 |
+
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/abalone_cv.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:aad08aabbf726ab65389e42c3a524f407e6bc791edcb5af304c31ba9037f6c10
|
| 3 |
+
size 351
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/adult_cv.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:956a488f34e502db9975d86ef25b75cf5c01c08a3e5a47c7ade4f72cbf11374c
|
| 3 |
+
size 432
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/buddy_cv.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d4577f6d2af34360bff6faf7a01af5501463e8b13ff0fc0c18bf2bfa67c6c63b
|
| 3 |
+
size 393
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/california_cv.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0508cdc40c02386321976c9537fbe54a5f2b0fa0e8e7dde72a6d4d289ced862c
|
| 3 |
+
size 335
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/cardio_cv.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a411285e39c4cb685233ec73375cfd023fb834897dd6b5a8f99cf7a7ec1c6656
|
| 3 |
+
size 403
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/churn2_cv.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e4dea09bdea9006ce44f71eef0e1740f639eceff44dd021c351ece84a428a00a
|
| 3 |
+
size 380
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/default_cv.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fb7ad47bb5b1c9fbe54cf14cc854581b22ed72f9dbc47f0a022e48fa572b5ffc
|
| 3 |
+
size 372
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/diabetes_cv.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0d1265117a3d8688b7878c62656b6d85bb543e723b1f5f01a2ed5bd4b12878dc
|
| 3 |
+
size 335
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/fb-comments_cv.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:18ccbc230cd0959834d3155e67c29d259af90720d29bc4284b3209df5374886e
|
| 3 |
+
size 519
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/gesture_cv.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:efa67605a7699adf3cd46bb7d7d5512516ab3e5da3e01451004aadf9ee4f9d62
|
| 3 |
+
size 333
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/higgs-small_cv.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d4c67d2f9937dc5548b3c3a1ae71846e5fccc66853b8067670b979ff2a4f0201
|
| 3 |
+
size 334
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/house_cv.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:852eea0c2f88f7032cebc5dc7c9422be385d231f1ce8b5c9364a534d64fdf4f3
|
| 3 |
+
size 332
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/insurance_cv.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2201078a643eb78c649a3d4a9e897ecf39c2d7f35c5a9fdb055c91251694b808
|
| 3 |
+
size 369
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/king_cv.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a94473811e28035ef4781122c3da6e4f81b232b68a0042b64c30a1df648e02d3
|
| 3 |
+
size 374
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/miniboone_cv.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:14dcf192aa15f491f147b30e2312b55889a146c546d72d89ee2d07ff26cc2103
|
| 3 |
+
size 334
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/wilt_cv.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4f6989397bf0029ee07b2ca9ab9335645ea3402bd6b782f2cec4cb40ad70b2ed
|
| 3 |
+
size 334
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/abalone_cv.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f99f28009311b8bb5413fbdbf72af25d1d384eec3c079c156e6a6eafa93e46bb
|
| 3 |
+
size 157
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/adult_cv.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1d4d4e1b062e420ce1838117b872e1794a632ea7f1dd8220eb640b71f793cd3a
|
| 3 |
+
size 229
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/buddy_cv.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:bfe610df17eb46233b0dbba7fb71ea6117e9992763ae8ccd789159c296f3cc43
|
| 3 |
+
size 165
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/california_cv.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b9970d5c42859dce6fded5b3fb285bba98181076d8db75b8ef78e5e0167c7b0c
|
| 3 |
+
size 163
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/cardio_cv.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:bc9642d070f056675cd4d004c0b446576eb162e2819dec052325fe7da59ce85d
|
| 3 |
+
size 148
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/churn2_cv.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ebea18b44a2d33a6643f283adf68961099d44d7e4f11e29148b501ddabb5894a
|
| 3 |
+
size 152
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/default_cv.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2d6082a82af0fb59906d778c57e4229eeff861066c1e24bea9c5e721f804214c
|
| 3 |
+
size 201
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/diabetes_cv.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:243a914fe90215cab4867d415cb82078366b5d2472264c91ea46d3e0e3291534
|
| 3 |
+
size 147
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/gesture_cv.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a3a819ad5093581e1b94eeddb0655b99cccce3bb121f405b0b7e3b230c3c1a11
|
| 3 |
+
size 190
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/higgs-small_cv.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3520fe130d4570aa07a79031b6016f31a4f36cd5fdc9ff7167f0c7e1768a6697
|
| 3 |
+
size 230
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/house_cv.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:22f1903d9a59e6cc1df1a643b9bc216392fbb3549cb6555482898d4a7ac936aa
|
| 3 |
+
size 164
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/insurance_cv.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:381e76611b072a0fb5fa41a7c640740453293a6d0cda8210697d4b9833d715e4
|
| 3 |
+
size 171
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/king_cv.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:afbbb1a2be60833c9468ded47ba78228e5a00c42bed93681e4e2aa0c6b68278d
|
| 3 |
+
size 163
|