diff --git a/.gitattributes b/.gitattributes index 86a43df8e4c3e39f7380a53edeb656de1372aea8..9022744703db3acc190f7e910ed61f7b0bebfd8e 100644 --- a/.gitattributes +++ b/.gitattributes @@ -5271,3 +5271,33 @@ SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wi SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/tvae/eval_catboost.json filter=lfs diff=lfs merge=lfs -text SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/tvae/eval_simple.json filter=lfs diff=lfs merge=lfs -text SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/wilt/tvae/info.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/abalone_cv.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/adult_cv.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/buddy_cv.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/california_cv.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/cardio_cv.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/churn2_cv.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/default_cv.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/diabetes_cv.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/fb-comments_cv.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/gesture_cv.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/higgs-small_cv.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/house_cv.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/insurance_cv.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/king_cv.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/miniboone_cv.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/wilt_cv.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/abalone_cv.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/adult_cv.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/buddy_cv.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/california_cv.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/cardio_cv.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/churn2_cv.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/default_cv.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/diabetes_cv.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/gesture_cv.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/higgs-small_cv.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/house_cv.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/insurance_cv.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/king_cv.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/miniboone_cv.json filter=lfs diff=lfs merge=lfs -text diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/pipeline.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..64a297813fd582cb86438f00981939571b53c162 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/pipeline.py @@ -0,0 +1,112 @@ +import tomli +import shutil +import os +import argparse +from scripts.train import train +from scripts.sample import sample +from scripts.eval_catboost import train_catboost +from scripts.eval_mlp import train_mlp +from scripts.eval_simple import train_simple +import pandas as pd +import matplotlib.pyplot as plt +import zero +import lib +import torch + +def load_config(path) : + with open(path, 'rb') as f: + return tomli.load(f) + +def save_file(parent_dir, config_path): + try: + dst = os.path.join(parent_dir) + os.makedirs(os.path.dirname(dst), exist_ok=True) + shutil.copyfile(os.path.abspath(config_path), dst) + except shutil.SameFileError: + pass + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--config', metavar='FILE') + parser.add_argument('--train', action='store_true', default=False) + parser.add_argument('--sample', action='store_true', default=False) + parser.add_argument('--eval', action='store_true', default=False) + parser.add_argument('--change_val', action='store_true', default=False) + + args = parser.parse_args() + raw_config = lib.load_config(args.config) + if 'device' in raw_config: + device = torch.device(raw_config['device']) + else: + device = torch.device('cuda:1') + + timer = zero.Timer() + timer.run() + save_file(os.path.join(raw_config['parent_dir'], 'config.toml'), args.config) + + if args.train: + train( + **raw_config['train']['main'], + **raw_config['diffusion_params'], + parent_dir=raw_config['parent_dir'], + real_data_path=raw_config['real_data_path'], + model_type=raw_config['model_type'], + model_params=raw_config['model_params'], + T_dict=raw_config['train']['T'], + num_numerical_features=raw_config['num_numerical_features'], + device=device, + change_val=args.change_val + ) + if args.sample: + sample( + num_samples=raw_config['sample']['num_samples'], + batch_size=raw_config['sample']['batch_size'], + disbalance=raw_config['sample'].get('disbalance', None), + **raw_config['diffusion_params'], + parent_dir=raw_config['parent_dir'], + real_data_path=raw_config['real_data_path'], + model_path=os.path.join(raw_config['parent_dir'], 'model.pt'), + model_type=raw_config['model_type'], + model_params=raw_config['model_params'], + T_dict=raw_config['train']['T'], + num_numerical_features=raw_config['num_numerical_features'], + device=device, + seed=raw_config['sample'].get('seed', 0), + change_val=args.change_val + ) + + save_file(os.path.join(raw_config['parent_dir'], 'info.json'), os.path.join(raw_config['real_data_path'], 'info.json')) + if args.eval: + if raw_config['eval']['type']['eval_model'] == 'catboost': + train_catboost( + parent_dir=raw_config['parent_dir'], + real_data_path=raw_config['real_data_path'], + eval_type=raw_config['eval']['type']['eval_type'], + T_dict=raw_config['eval']['T'], + seed=raw_config['seed'], + change_val=args.change_val + ) + elif raw_config['eval']['type']['eval_model'] == 'mlp': + train_mlp( + parent_dir=raw_config['parent_dir'], + real_data_path=raw_config['real_data_path'], + eval_type=raw_config['eval']['type']['eval_type'], + T_dict=raw_config['eval']['T'], + seed=raw_config['seed'], + change_val=args.change_val, + device=device + ) + elif raw_config['eval']['type']['eval_model'] == 'simple': + train_simple( + parent_dir=raw_config['parent_dir'], + real_data_path=raw_config['real_data_path'], + eval_type=raw_config['eval']['type']['eval_type'], + T_dict=raw_config['eval']['T'], + seed=raw_config['seed'], + change_val=args.change_val + ) + + print(f'Elapsed time: {str(timer)}') + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/resample_privacy.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/resample_privacy.py new file mode 100644 index 0000000000000000000000000000000000000000..54d320c3bb19ce5275d25704ad82f086601ee65d --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/resample_privacy.py @@ -0,0 +1,257 @@ +""" +Adapted from https://github.com/Team-TUD/CTAB-GAN/tree/main/model/eval +""" + +import argparse +import lib +import os +import shutil +import zero +from sample import sample +from smote.sample_smote import sample_smote +from sklearn.preprocessing import MinMaxScaler, OneHotEncoder +from sklearn.metrics import pairwise_distances +from pathlib import Path +import tempfile +from eval_seeds import eval_seeds +import numpy as np +import subprocess +import warnings +import torch + +zero.improve_reproducibility(0) + +warnings.filterwarnings("ignore", category=FutureWarning) + + +def privacy_metrics(real_path,fake_path, data_percent=15): + + """ + Returns privacy metrics + + Inputs: + 1) real_path -> path to real data + 2) fake_path -> path to corresponding synthetic data + 3) data_percent -> percentage of data to be sampled from real and synthetic datasets for computing privacy metrics + Outputs: + 1) List containing the 5th percentile distance to closest record (DCR) between real and synthetic as well as within real and synthetic datasets + along with 5th percentile of nearest neighbour distance ratio (NNDR) between real and synthetic as well as within real and synthetic datasets + + """ + task_type = lib.load_json(real_path + "/info.json")["task_type"] + X_num_real, X_cat_real, y_real = lib.read_pure_data(real_path, 'train') + X_num_fake, X_cat_fake, y_fake = lib.read_pure_data(fake_path, 'train') + + if task_type == 'regression': + X_num_real = np.concatenate([X_num_real, y_real[:, np.newaxis]], axis=1) + X_num_fake = np.concatenate([X_num_fake, y_fake[:, np.newaxis]], axis=1) + else: + if X_cat_fake is None: + X_cat_real = y_real[:, np.newaxis].astype(int).astype(str) + X_cat_fake = y_fake[:, np.newaxis].astype(int).astype(str) + else: + X_cat_real = np.concatenate([X_cat_real, y_real[:, np.newaxis].astype(int).astype(str)], axis=1) + X_cat_fake = np.concatenate([X_cat_fake, y_fake[:, np.newaxis].astype(int).astype(str)], axis=1) + + if len(y_real) > 50000: + ixs = np.random.choice(len(y_real), 50000, replace=False) + X_num_real = X_num_real[ixs] + X_cat_real = X_cat_real[ixs] if X_cat_real is not None else None + + if len(y_fake) > 50000: + ixs = np.random.choice(len(y_fake), 50000, replace=False) + X_num_fake = X_num_fake[ixs] + X_cat_fake = X_cat_fake[ixs] if X_cat_fake is not None else None + + + mm = MinMaxScaler().fit(X_num_real) + X_real = mm.transform(X_num_real) + X_fake = mm.transform(X_num_fake) + if X_cat_real is not None: + ohe = OneHotEncoder().fit(X_cat_real) + X_cat_real = ohe.transform(X_cat_real) / np.sqrt(2) + X_cat_fake = ohe.transform(X_cat_fake) / np.sqrt(2) + + X_real = np.concatenate([X_real, X_cat_real.todense()], axis=1) + X_fake = np.concatenate([X_fake, X_cat_fake.todense()], axis=1) + + # X_real = np.unique(X_real, axis=0) + # X_fake = np.unique(X_fake, axis=0) + + # Computing pair-wise distances between real and synthetic + dist_rf = pairwise_distances(X_fake, Y=X_real, metric='l2', n_jobs=-1) + # Computing pair-wise distances within real + # dist_rr = pairwise_distances(X_real, Y=None, metric='l2', n_jobs=-1) + # Computing pair-wise distances within synthetic + # dist_ff = pairwise_distances(X_fake, Y=None, metric='l2', n_jobs=-1) + + + # Removes distances of data points to themselves to avoid 0s within real and synthetic + # rd_dist_rr = dist_rr[~np.eye(dist_rr.shape[0],dtype=bool)].reshape(dist_rr.shape[0],-1) + # rd_dist_ff = dist_ff[~np.eye(dist_ff.shape[0],dtype=bool)].reshape(dist_ff.shape[0],-1) + + # Computing first and second smallest nearest neighbour distances between real and synthetic + smallest_two_indexes_rf = [dist_rf[i].argsort()[:2] for i in range(len(dist_rf))] + smallest_two_rf = [dist_rf[i][smallest_two_indexes_rf[i]] for i in range(len(dist_rf))] + # Computing first and second smallest nearest neighbour distances within real + # smallest_two_indexes_rr = [rd_dist_rr[i].argsort()[:2] for i in range(len(rd_dist_rr))] + # smallest_two_rr = [rd_dist_rr[i][smallest_two_indexes_rr[i]] for i in range(len(rd_dist_rr))] + # Computing first and second smallest nearest neighbour distances within synthetic + # smallest_two_indexes_ff = [rd_dist_ff[i].argsort()[:2] for i in range(len(rd_dist_ff))] + # smallest_two_ff = [rd_dist_ff[i][smallest_two_indexes_ff[i]] for i in range(len(rd_dist_ff))] + + + # Computing 5th percentiles for DCR and NNDR between and within real and synthetic datasets + min_dist_rf = np.array([i[0] for i in smallest_two_rf]) + fifth_perc_rf = np.percentile(min_dist_rf,5) + # min_dist_rr = np.array([i[0] for i in smallest_two_rr]) + # fifth_perc_rr = np.percentile(min_dist_rr,5) + # min_dist_ff = np.array([i[0] for i in smallest_two_ff]) + # fifth_perc_ff = np.percentile(min_dist_ff,5) + # nn_ratio_rf = np.array([i[0]/i[1] for i in smallest_two_rf]) + # nn_fifth_perc_rf = np.percentile(nn_ratio_rf,5) + # nn_ratio_rr = np.array([i[0]/i[1] for i in smallest_two_rr]) + # nn_fifth_perc_rr = np.percentile(nn_ratio_rr,5) + # nn_ratio_ff = np.array([i[0]/i[1] for i in smallest_two_ff]) + # nn_fifth_perc_ff = np.percentile(nn_ratio_ff,5) + + # 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) + return min_dist_rf # , min_dist_rr + +def sample_wrapper(method, config, num_samples=None, seed=0): + if method == "ddpm": + sample( + num_samples=num_samples, + batch_size=config['sample']['batch_size'], + disbalance=config['sample'].get('disbalance', None), + **config['diffusion_params'], + parent_dir=config['parent_dir'], + real_data_path=config['real_data_path'], + model_path=os.path.join(config['parent_dir'], 'model.pt'), + model_type=config['model_type'], + model_params=config['model_params'], + T_dict=config['train']['T'], + num_numerical_features=config['num_numerical_features'], + seed=seed, + change_val=False, + device=torch.device(config["device"]) + ) + elif method == "smote": + sample_smote( + parent_dir=config['parent_dir'], + real_data_path=config['real_data_path'], + **config['smote_params'], + seed=seed, + change_val=False + ) + +def resample_privacy(config_path, method, q): + with tempfile.TemporaryDirectory() as dir_: + config = lib.load_config(config_path) + if method == "ddpm": + shutil.copy2(os.path.join(config['parent_dir'], 'model.pt'), os.path.join(dir_, 'model.pt')) + config["parent_dir"] = str(dir_) + parent_dir = config["parent_dir"] + + sample_wrapper(method, config, num_samples=config["sample"].get("num_samples", 0)) + + dists = privacy_metrics(config["real_data_path"], parent_dir) + old_privacy = np.median(dists) + + q10 = np.quantile(dists, q=q) + print(f"Q: {q10}") + to_drop = np.where(dists < q10) + + X_num, X_cat, y = lib.read_pure_data(parent_dir) + num_samples = len(y) + X_num = np.delete(X_num, to_drop, axis=0) + X_cat = np.delete(X_cat, to_drop, axis=0) if X_cat is not None else None + y = np.delete(y, to_drop, axis=0) + i = 1 + + while len(y) < num_samples and i <= 10: + print(f"{len(y)}/{num_samples}") + + sample_wrapper(method, config, num_samples=config["sample"].get("batch_size", 0), seed=i) + + i += 1 + + X_num_t, X_cat_t, y_t = lib.read_pure_data(parent_dir) + dists = privacy_metrics(config["real_data_path"], parent_dir) + to_drop = np.where(dists < q10) + X_num_t = np.delete(X_num_t, to_drop, axis=0) + X_cat_t = np.delete(X_cat_t, to_drop, axis=0) if X_cat is not None else None + y_t = np.delete(y_t, to_drop, axis=0) + + X_num = np.concatenate([X_num, X_num_t], axis=0)[:num_samples] + X_cat = np.concatenate([X_cat, X_cat_t], axis=0)[:num_samples] if X_cat is not None else None + y = np.concatenate([y, y_t], axis=0)[:num_samples] + + # np.save(os.path.join(parent_dir, 'X_num_train'), X_num) + # if X_cat is not None: + # np.save(os.path.join(parent_dir, 'X_cat_train'), X_cat) + # np.save(os.path.join(parent_dir, 'y_train'), y) + + np.save(os.path.join(parent_dir, 'X_num_train'), X_num) + if X_cat is not None: + np.save(os.path.join(parent_dir, 'X_cat_train'), X_cat) + np.save(os.path.join(parent_dir, 'y_train'), y) + + new_dists = privacy_metrics(config["real_data_path"], parent_dir) + + res = eval_seeds( + config, + n_seeds=10, + eval_type="synthetic", + model_type="catboost", + n_datasets=1, + dump=False + ) + print(f"Old: {old_privacy:.4f}, New: {np.median(new_dists):.4f}") + + metric = "r2-mean" if "r2-mean" in res["test"] else "f1-mean" + return res["test"][metric], np.around(np.median(new_dists), 4) + +def resample_privacy_qs(config_path, method): + config = lib.load_config(config_path) + scores = [] + privacies = [] + + eval_res = lib.load_json(Path(config["parent_dir"]) / "eval_catboost.json")["synthetic"]["test"] + metric = "r2-mean" if "r2-mean" in eval_res else "f1-mean" + scores.append(eval_res[metric]) + privacies.append(np.median(privacy_metrics(config["real_data_path"], config["parent_dir"]))) + + for q in [0.1, 0.2, 0.3, 0.4]: + score, privacy = resample_privacy(config_path, method, q) + scores.append(score) + privacies.append(privacy) + + lib.dump_json( + {"scores": scores, "privacies": privacies}, + Path(config["parent_dir"]) / "privacies.json" + ) + +def calc_privacy(config_path, method, seed=0): + config = lib.load_config(config_path) + sample_wrapper(method, config, num_samples=config["sample"]["num_samples"], seed=seed) + timer = zero.Timer() + timer.run() + dists = privacy_metrics(config["real_data_path"], config["parent_dir"]) + privacy_val = np.median(dists) + lib.dump_json({"privacy": privacy_val}, os.path.join(config["parent_dir"], "privacy.json")) + print(f"Elapsed tine:{str(timer)}") + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--config', metavar='FILE') + parser.add_argument('method', type=str) + args = parser.parse_args() + + calc_privacy( + args.config, + args.method + ) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/sample.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/sample.py new file mode 100644 index 0000000000000000000000000000000000000000..35d7f2158ba8c345bb57a840de1a7936ba59a0f6 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/sample.py @@ -0,0 +1,160 @@ +import torch +import numpy as np +import zero +import os +from tab_ddpm.gaussian_multinomial_diffsuion import GaussianMultinomialDiffusion +from tab_ddpm.utils import FoundNANsError +from scripts.utils_train import get_model, make_dataset +from lib import round_columns +import lib + +def to_good_ohe(ohe, X): + indices = np.cumsum([0] + ohe._n_features_outs) + Xres = [] + for i in range(1, len(indices)): + x_ = np.max(X[:, indices[i - 1]:indices[i]], axis=1) + t = X[:, indices[i - 1]:indices[i]] - x_.reshape(-1, 1) + Xres.append(np.where(t >= 0, 1, 0)) + return np.hstack(Xres) + +def sample( + parent_dir, + real_data_path = 'data/higgs-small', + batch_size = 2000, + num_samples = 0, + model_type = 'mlp', + model_params = None, + model_path = None, + num_timesteps = 1000, + gaussian_loss_type = 'mse', + scheduler = 'cosine', + T_dict = None, + num_numerical_features = 0, + disbalance = None, + device = torch.device('cuda:1'), + seed = 0, + change_val = False +): + zero.improve_reproducibility(seed) + + T = lib.Transformations(**T_dict) + D = make_dataset( + real_data_path, + T, + num_classes=model_params['num_classes'], + is_y_cond=model_params['is_y_cond'], + change_val=change_val + ) + + K = np.array(D.get_category_sizes('train')) + if len(K) == 0 or T_dict['cat_encoding'] == 'one-hot': + K = np.array([0]) + + num_numerical_features_ = D.X_num['train'].shape[1] if D.X_num is not None else 0 + d_in = np.sum(K) + num_numerical_features_ + model_params['d_in'] = int(d_in) + model = get_model( + model_type, + model_params, + num_numerical_features_, + category_sizes=D.get_category_sizes('train') + ) + + model.load_state_dict( + torch.load(model_path, map_location="cpu") + ) + + diffusion = GaussianMultinomialDiffusion( + K, + num_numerical_features=num_numerical_features_, + denoise_fn=model, num_timesteps=num_timesteps, + gaussian_loss_type=gaussian_loss_type, scheduler=scheduler, device=device + ) + + diffusion.to(device) + diffusion.eval() + + _, empirical_class_dist = torch.unique(torch.from_numpy(D.y['train']), return_counts=True) + # empirical_class_dist = empirical_class_dist.float() + torch.tensor([-5000., 10000.]).float() + if disbalance == 'fix': + empirical_class_dist[0], empirical_class_dist[1] = empirical_class_dist[1], empirical_class_dist[0] + x_gen, y_gen = diffusion.sample_all(num_samples, batch_size, empirical_class_dist.float(), ddim=False) + + elif disbalance == 'fill': + ix_major = empirical_class_dist.argmax().item() + val_major = empirical_class_dist[ix_major].item() + x_gen, y_gen = [], [] + for i in range(empirical_class_dist.shape[0]): + if i == ix_major: + continue + distrib = torch.zeros_like(empirical_class_dist) + distrib[i] = 1 + num_samples = val_major - empirical_class_dist[i].item() + x_temp, y_temp = diffusion.sample_all(num_samples, batch_size, distrib.float(), ddim=False) + x_gen.append(x_temp) + y_gen.append(y_temp) + + x_gen = torch.cat(x_gen, dim=0) + y_gen = torch.cat(y_gen, dim=0) + + else: + x_gen, y_gen = diffusion.sample_all(num_samples, batch_size, empirical_class_dist.float(), ddim=False) + + + # try: + # except FoundNANsError as ex: + # print("Found NaNs during sampling!") + # loader = lib.prepare_fast_dataloader(D, 'train', 8) + # x_gen = next(loader)[0] + # y_gen = torch.multinomial( + # empirical_class_dist.float(), + # num_samples=8, + # replacement=True + # ) + X_gen, y_gen = x_gen.numpy(), y_gen.numpy() + + ### + # X_num_unnorm = X_gen[:, :num_numerical_features] + # lo = np.percentile(X_num_unnorm, 2.5, axis=0) + # hi = np.percentile(X_num_unnorm, 97.5, axis=0) + # idx = (lo < X_num_unnorm) & (hi > X_num_unnorm) + # X_gen = X_gen[np.all(idx, axis=1)] + # y_gen = y_gen[np.all(idx, axis=1)] + ### + + num_numerical_features = num_numerical_features + int(D.is_regression and not model_params["is_y_cond"]) + + X_num_ = X_gen + if num_numerical_features < X_gen.shape[1]: + np.save(os.path.join(parent_dir, 'X_cat_unnorm'), X_gen[:, num_numerical_features:]) + # _, _, cat_encoder = lib.cat_encode({'train': X_cat_real}, T_dict['cat_encoding'], y_real, T_dict['seed'], True) + if T_dict['cat_encoding'] == 'one-hot': + X_gen[:, num_numerical_features:] = to_good_ohe(D.cat_transform.steps[0][1], X_num_[:, num_numerical_features:]) + X_cat = D.cat_transform.inverse_transform(X_gen[:, num_numerical_features:]) + + if num_numerical_features_ != 0: + # _, normalize = lib.normalize({'train' : X_num_real}, T_dict['normalization'], T_dict['seed'], True) + np.save(os.path.join(parent_dir, 'X_num_unnorm'), X_gen[:, :num_numerical_features]) + X_num_ = D.num_transform.inverse_transform(X_gen[:, :num_numerical_features]) + X_num = X_num_[:, :num_numerical_features] + + X_num_real = np.load(os.path.join(real_data_path, "X_num_train.npy"), allow_pickle=True) + disc_cols = [] + for col in range(X_num_real.shape[1]): + uniq_vals = np.unique(X_num_real[:, col]) + if len(uniq_vals) <= 32 and ((uniq_vals - np.round(uniq_vals)) == 0).all(): + disc_cols.append(col) + print("Discrete cols:", disc_cols) + # 仅当 regression 且 y 在 X_num 中(非 is_y_cond)时才提取 y;否则 y_gen 已由 sample_all 返回 + if model_params['num_classes'] == 0 and not model_params.get('is_y_cond', True): + y_gen = X_num[:, 0] + X_num = X_num[:, 1:] + if len(disc_cols): + X_num = round_columns(X_num_real, X_num, disc_cols) + + if num_numerical_features != 0: + print("Num shape: ", X_num.shape) + np.save(os.path.join(parent_dir, 'X_num_train'), X_num) + if num_numerical_features < X_gen.shape[1]: + np.save(os.path.join(parent_dir, 'X_cat_train'), X_cat) + np.save(os.path.join(parent_dir, 'y_train'), y_gen) \ No newline at end of file diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/train.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/train.py new file mode 100644 index 0000000000000000000000000000000000000000..84a4eef3c97b080d1cf1b122c7d4117b74a1cefd --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/train.py @@ -0,0 +1,158 @@ +from copy import deepcopy +import torch +import os +import numpy as np +import zero +from tab_ddpm import GaussianMultinomialDiffusion +from scripts.utils_train import get_model, make_dataset, update_ema +import lib +import pandas as pd + +class Trainer: + def __init__(self, diffusion, train_iter, lr, weight_decay, steps, device=torch.device('cuda:1')): + self.diffusion = diffusion + self.ema_model = deepcopy(self.diffusion._denoise_fn) + for param in self.ema_model.parameters(): + param.detach_() + + self.train_iter = train_iter + self.steps = steps + self.init_lr = lr + self.optimizer = torch.optim.AdamW(self.diffusion.parameters(), lr=lr, weight_decay=weight_decay) + self.device = device + self.loss_history = pd.DataFrame(columns=['step', 'mloss', 'gloss', 'loss']) + self.log_every = 100 + self.print_every = 500 + self.ema_every = 1000 + + def _anneal_lr(self, step): + frac_done = step / self.steps + lr = self.init_lr * (1 - frac_done) + for param_group in self.optimizer.param_groups: + param_group["lr"] = lr + + def _run_step(self, x, out_dict): + x = x.to(self.device) + for k in out_dict: + out_dict[k] = out_dict[k].long().to(self.device) + self.optimizer.zero_grad() + loss_multi, loss_gauss = self.diffusion.mixed_loss(x, out_dict) + loss = loss_multi + loss_gauss + loss.backward() + self.optimizer.step() + + return loss_multi, loss_gauss + + def run_loop(self): + step = 0 + curr_loss_multi = 0.0 + curr_loss_gauss = 0.0 + + curr_count = 0 + while step < self.steps: + x, out_dict = next(self.train_iter) + out_dict = {'y': out_dict} + batch_loss_multi, batch_loss_gauss = self._run_step(x, out_dict) + + self._anneal_lr(step) + + curr_count += len(x) + curr_loss_multi += batch_loss_multi.item() * len(x) + curr_loss_gauss += batch_loss_gauss.item() * len(x) + + if (step + 1) % self.log_every == 0: + mloss = np.around(curr_loss_multi / curr_count, 4) + gloss = np.around(curr_loss_gauss / curr_count, 4) + if (step + 1) % self.print_every == 0: + print(f'Step {(step + 1)}/{self.steps} MLoss: {mloss} GLoss: {gloss} Sum: {mloss + gloss}') + self.loss_history.loc[len(self.loss_history)] =[step + 1, mloss, gloss, mloss + gloss] + curr_count = 0 + curr_loss_gauss = 0.0 + curr_loss_multi = 0.0 + + update_ema(self.ema_model.parameters(), self.diffusion._denoise_fn.parameters()) + + step += 1 + +def train( + parent_dir, + real_data_path = 'data/higgs-small', + steps = 1000, + lr = 0.002, + weight_decay = 1e-4, + batch_size = 1024, + model_type = 'mlp', + model_params = None, + num_timesteps = 1000, + gaussian_loss_type = 'mse', + scheduler = 'cosine', + T_dict = None, + num_numerical_features = 0, + device = torch.device('cuda:1'), + seed = 0, + change_val = False +): + real_data_path = os.path.normpath(real_data_path) + parent_dir = os.path.normpath(parent_dir) + + zero.improve_reproducibility(seed) + + T = lib.Transformations(**T_dict) + + dataset = make_dataset( + real_data_path, + T, + num_classes=model_params['num_classes'], + is_y_cond=model_params['is_y_cond'], + change_val=change_val + ) + + K = np.array(dataset.get_category_sizes('train')) + if len(K) == 0 or T_dict['cat_encoding'] == 'one-hot': + K = np.array([0]) + print(K) + + num_numerical_features = dataset.X_num['train'].shape[1] if dataset.X_num is not None else 0 + d_in = np.sum(K) + num_numerical_features + model_params['d_in'] = d_in + print(d_in) + + print(model_params) + model = get_model( + model_type, + model_params, + num_numerical_features, + category_sizes=dataset.get_category_sizes('train') + ) + model.to(device) + + # train_loader = lib.prepare_beton_loader(dataset, split='train', batch_size=batch_size) + train_loader = lib.prepare_fast_dataloader(dataset, split='train', batch_size=batch_size) + + + + diffusion = GaussianMultinomialDiffusion( + num_classes=K, + num_numerical_features=num_numerical_features, + denoise_fn=model, + gaussian_loss_type=gaussian_loss_type, + num_timesteps=num_timesteps, + scheduler=scheduler, + device=device + ) + diffusion.to(device) + diffusion.train() + + trainer = Trainer( + diffusion, + train_loader, + lr=lr, + weight_decay=weight_decay, + steps=steps, + device=device + ) + trainer.run_loop() + + trainer.loss_history.to_csv(os.path.join(parent_dir, 'loss.csv'), index=False) + torch.save(diffusion._denoise_fn.state_dict(), os.path.join(parent_dir, 'model.pt')) + torch.save(trainer.ema_model.state_dict(), os.path.join(parent_dir, 'model_ema.pt')) \ No newline at end of file diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/tune_ddpm.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/tune_ddpm.py new file mode 100644 index 0000000000000000000000000000000000000000..5a95dc23cab775a9ca7b7eb496bcefef58691dce --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/tune_ddpm.py @@ -0,0 +1,127 @@ +import subprocess +import lib +import os +import optuna +from copy import deepcopy +import shutil +import argparse +from pathlib import Path + +parser = argparse.ArgumentParser() +parser.add_argument('ds_name', type=str) +parser.add_argument('train_size', type=int) +parser.add_argument('eval_type', type=str) +parser.add_argument('eval_model', type=str) +parser.add_argument('prefix', type=str) +parser.add_argument('--eval_seeds', action='store_true', default=False) + +args = parser.parse_args() +train_size = args.train_size +ds_name = args.ds_name +eval_type = args.eval_type +assert eval_type in ('merged', 'synthetic') +prefix = str(args.prefix) + +pipeline = f'scripts/pipeline.py' +base_config_path = f'exp/{ds_name}/config.toml' +parent_path = Path(f'exp/{ds_name}/') +exps_path = Path(f'exp/{ds_name}/many-exps/') # temporary dir. maybe will be replaced with tempdiвdr +eval_seeds = f'scripts/eval_seeds.py' + +os.makedirs(exps_path, exist_ok=True) + +def _suggest_mlp_layers(trial): + def suggest_dim(name): + t = trial.suggest_int(name, d_min, d_max) + return 2 ** t + min_n_layers, max_n_layers, d_min, d_max = 1, 4, 7, 10 + n_layers = 2 * trial.suggest_int('n_layers', min_n_layers, max_n_layers) + d_first = [suggest_dim('d_first')] if n_layers else [] + d_middle = ( + [suggest_dim('d_middle')] * (n_layers - 2) + if n_layers > 2 + else [] + ) + d_last = [suggest_dim('d_last')] if n_layers > 1 else [] + d_layers = d_first + d_middle + d_last + return d_layers + +def objective(trial): + + lr = trial.suggest_loguniform('lr', 0.00001, 0.003) + d_layers = _suggest_mlp_layers(trial) + weight_decay = 0.0 + batch_size = trial.suggest_categorical('batch_size', [256, 4096]) + steps = trial.suggest_categorical('steps', [5000, 20000, 30000]) + # steps = trial.suggest_categorical('steps', [500]) # for debug + gaussian_loss_type = 'mse' + # scheduler = trial.suggest_categorical('scheduler', ['cosine', 'linear']) + num_timesteps = trial.suggest_categorical('num_timesteps', [100, 1000]) + num_samples = int(train_size * (2 ** trial.suggest_int('num_samples', -2, 1))) + + base_config = lib.load_config(base_config_path) + + base_config['train']['main']['lr'] = lr + base_config['train']['main']['steps'] = steps + base_config['train']['main']['batch_size'] = batch_size + base_config['train']['main']['weight_decay'] = weight_decay + base_config['model_params']['rtdl_params']['d_layers'] = d_layers + base_config['eval']['type']['eval_type'] = eval_type + base_config['sample']['num_samples'] = num_samples + base_config['diffusion_params']['gaussian_loss_type'] = gaussian_loss_type + base_config['diffusion_params']['num_timesteps'] = num_timesteps + # base_config['diffusion_params']['scheduler'] = scheduler + + base_config['parent_dir'] = str(exps_path / f"{trial.number}") + base_config['eval']['type']['eval_model'] = args.eval_model + if args.eval_model == "mlp": + base_config['eval']['T']['normalization'] = "quantile" + base_config['eval']['T']['cat_encoding'] = "one-hot" + + trial.set_user_attr("config", base_config) + + lib.dump_config(base_config, exps_path / 'config.toml') + + subprocess.run(['python3.9', f'{pipeline}', '--config', f'{exps_path / "config.toml"}', '--train', '--change_val'], check=True) + + n_datasets = 5 + score = 0.0 + + for sample_seed in range(n_datasets): + base_config['sample']['seed'] = sample_seed + lib.dump_config(base_config, exps_path / 'config.toml') + + subprocess.run(['python3.9', f'{pipeline}', '--config', f'{exps_path / "config.toml"}', '--sample', '--eval', '--change_val'], check=True) + + report_path = str(Path(base_config['parent_dir']) / f'results_{args.eval_model}.json') + report = lib.load_json(report_path) + + if 'r2' in report['metrics']['val']: + score += report['metrics']['val']['r2'] + else: + score += report['metrics']['val']['macro avg']['f1-score'] + + shutil.rmtree(exps_path / f"{trial.number}") + + return score / n_datasets + +study = optuna.create_study( + direction='maximize', + sampler=optuna.samplers.TPESampler(seed=0), +) + +study.optimize(objective, n_trials=50, show_progress_bar=True) + +best_config_path = parent_path / f'{prefix}_best/config.toml' +best_config = study.best_trial.user_attrs['config'] +best_config["parent_dir"] = str(parent_path / f'{prefix}_best/') + +os.makedirs(parent_path / f'{prefix}_best', exist_ok=True) +lib.dump_config(best_config, best_config_path) +lib.dump_json(optuna.importance.get_param_importances(study), parent_path / f'{prefix}_best/importance.json') + +subprocess.run(['python3.9', f'{pipeline}', '--config', f'{best_config_path}', '--train', '--sample'], check=True) + +if args.eval_seeds: + best_exp = str(parent_path / f'{prefix}_best/config.toml') + subprocess.run(['python3.9', f'{eval_seeds}', '--config', f'{best_exp}', '10', "ddpm", eval_type, args.eval_model, '5'], check=True) \ No newline at end of file diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/tune_evaluation_model.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/tune_evaluation_model.py new file mode 100644 index 0000000000000000000000000000000000000000..8def5fd6cd1f609893e4de5f5c9708edb0a2efb7 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/tune_evaluation_model.py @@ -0,0 +1,145 @@ +import optuna +import lib +import argparse +from eval_catboost import train_catboost +from eval_mlp import train_mlp +from pathlib import Path + +parser = argparse.ArgumentParser() +parser.add_argument('ds_name', type=str) +parser.add_argument('model', type=str) +parser.add_argument('tune_type', type=str) +parser.add_argument('device', type=str) + +args = parser.parse_args() +data_path = Path(f"data/{args.ds_name}") +best_params = None + +assert args.tune_type in ("cv", "val") + +def _suggest(trial: optuna.trial.Trial, distribution: str, label: str, *args): + return getattr(trial, f'suggest_{distribution}')(label, *args) + +def _suggest_optional(trial: optuna.trial.Trial, distribution: str, label: str, *args): + if trial.suggest_categorical(f"optional_{label}", [True, False]): + return _suggest(trial, distribution, label, *args) + else: + return 0.0 + +def _suggest_mlp_layers(trial: optuna.trial.Trial, mlp_d_layers: list[int]): + + min_n_layers, max_n_layers = mlp_d_layers[0], mlp_d_layers[1] + d_min, d_max = mlp_d_layers[2], mlp_d_layers[3] + + def suggest_dim(name): + t = trial.suggest_int(name, d_min, d_max) + return 2 ** t + + + n_layers = trial.suggest_int('n_layers', min_n_layers, max_n_layers) + d_first = [suggest_dim('d_first')] if n_layers else [] + d_middle = ( + [suggest_dim('d_middle')] * (n_layers - 2) + if n_layers > 2 + else [] + ) + d_last = [suggest_dim('d_last')] if n_layers > 1 else [] + d_layers = d_first + d_middle + d_last + + return d_layers + +def suggest_mlp_params(trial): + params = {} + params["lr"] = trial.suggest_loguniform("lr", 5e-5, 0.005) + params["dropout"] = _suggest_optional(trial, "uniform", "dropout", 0.0, 0.5) + params["weight_decay"] = _suggest_optional(trial, "loguniform", "weight_decay", 1e-6, 1e-2) + params["d_layers"] = _suggest_mlp_layers(trial, [1, 8, 6, 10]) + + return params + +def suggest_catboost_params(trial): + params = {} + params["learning_rate"] = trial.suggest_loguniform("learning_rate", 0.001, 1.0) + params["depth"] = trial.suggest_int("depth", 3, 10) + params["l2_leaf_reg"] = trial.suggest_uniform("l2_leaf_reg", 0.1, 10.0) + params["bagging_temperature"] = trial.suggest_uniform("bagging_temperature", 0.0, 1.0) + params["leaf_estimation_iterations"] = trial.suggest_int("leaf_estimation_iterations", 1, 10) + + params = params | { + "iterations": 2000, + "early_stopping_rounds": 50, + "od_pval": 0.001, + "task_type": "CPU", # "GPU", may affect performance + "thread_count": 4, + # "devices": "0", # for GPU + } + + return params + +def objective(trial): + if args.model == "mlp": + params = suggest_mlp_params(trial) + train_func = train_mlp + T_dict = { + "seed": 0, + "normalization": "quantile", + "num_nan_policy": None, + "cat_nan_policy": None, + "cat_min_frequency": None, + "cat_encoding": "one-hot", + "y_policy": "default" + } + else: + params = suggest_catboost_params(trial) + train_func = train_catboost + T_dict = { + "seed": 0, + "normalization": None, + "num_nan_policy": None, + "cat_nan_policy": None, + "cat_min_frequency": None, + "cat_encoding": None, + "y_policy": "default" + } + trial.set_user_attr("params", params) + if args.tune_type == "cv": + score = 0.0 + for fold in range(5): + metrics_report = train_func( + parent_dir=None, + real_data_path=data_path / f"kfolds/{fold}", + eval_type="real", + T_dict=T_dict, + params=params, + change_val=False, + device=args.device + ) + score += metrics_report.get_val_score() + score /= 5 + + elif args.tune_type == "val": + metrics_report = train_func( + parent_dir=None, + real_data_path=data_path, + eval_type="real", + T_dict=T_dict, + params=params, + change_val=False, + device=args.device + ) + score = metrics_report.get_val_score() + + return score + +study = optuna.create_study( + direction='maximize', + sampler=optuna.samplers.TPESampler(seed=0), +) + +study.optimize(objective, n_trials=100, show_progress_bar=True) + +bets_params = study.best_trial.user_attrs['params'] + +best_params_path = f"tuned_models/{args.model}/{args.ds_name}_{args.tune_type}.json" + +lib.dump_json(bets_params, best_params_path) \ No newline at end of file diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/utils_train.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/utils_train.py new file mode 100644 index 0000000000000000000000000000000000000000..4132ca56fb8e063111f916f903ef4e99206486e3 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/utils_train.py @@ -0,0 +1,89 @@ +import numpy as np +import os +import lib +from tab_ddpm.modules import MLPDiffusion, ResNetDiffusion + +def get_model( + model_name, + model_params, + n_num_features, + category_sizes +): + print(model_name) + if model_name == 'mlp': + model = MLPDiffusion(**model_params) + elif model_name == 'resnet': + model = ResNetDiffusion(**model_params) + else: + raise "Unknown model!" + return model + +def update_ema(target_params, source_params, rate=0.999): + """ + Update target parameters to be closer to those of source parameters using + an exponential moving average. + :param target_params: the target parameter sequence. + :param source_params: the source parameter sequence. + :param rate: the EMA rate (closer to 1 means slower). + """ + for targ, src in zip(target_params, source_params): + targ.detach().mul_(rate).add_(src.detach(), alpha=1 - rate) + +def concat_y_to_X(X, y): + if X is None: + return y.reshape(-1, 1) + return np.concatenate([y.reshape(-1, 1), X], axis=1) + +def make_dataset( + data_path: str, + T: lib.Transformations, + num_classes: int, + is_y_cond: bool, + change_val: bool +): + # classification + if num_classes > 0: + X_cat = {} if os.path.exists(os.path.join(data_path, 'X_cat_train.npy')) or not is_y_cond else None + X_num = {} if os.path.exists(os.path.join(data_path, 'X_num_train.npy')) else None + y = {} + + for split in ['train']: + X_num_t, X_cat_t, y_t = lib.read_pure_data(data_path, split) + if X_num is not None: + X_num[split] = X_num_t + if not is_y_cond: + X_cat_t = concat_y_to_X(X_cat_t, y_t) + if X_cat is not None: + X_cat[split] = X_cat_t + y[split] = y_t + else: + # regression + X_cat = {} if os.path.exists(os.path.join(data_path, 'X_cat_train.npy')) else None + X_num = {} if os.path.exists(os.path.join(data_path, 'X_num_train.npy')) or not is_y_cond else None + y = {} + + for split in ['train']: + X_num_t, X_cat_t, y_t = lib.read_pure_data(data_path, split) + if not is_y_cond: + X_num_t = concat_y_to_X(X_num_t, y_t) + if X_num is not None: + X_num[split] = X_num_t + if X_cat is not None: + X_cat[split] = X_cat_t + y[split] = y_t + + info = lib.load_json(os.path.join(data_path, 'info.json')) + + D = lib.Dataset( + X_num, + X_cat, + y, + y_info={}, + task_type=lib.TaskType(info['task_type']), + n_classes=info.get('n_classes') + ) + + if change_val: + D = lib.change_val(D) + + return lib.transform_dataset(D, T, None) \ No newline at end of file diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/smote/pipeline_smote.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/smote/pipeline_smote.py new file mode 100644 index 0000000000000000000000000000000000000000..4a6775493e975104c268a2cd177f953ea9589d0a --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/smote/pipeline_smote.py @@ -0,0 +1,68 @@ +import tomli +import shutil +import os +import argparse +from sample_smote import sample_smote +from scripts.eval_catboost import train_catboost +# from scripts.eval_mlp import train_mlp +import zero +import lib + +def load_config(path) : + with open(path, 'rb') as f: + return tomli.load(f) + +def save_file(parent_dir, config_path): + try: + dst = os.path.join(parent_dir) + os.makedirs(os.path.dirname(dst), exist_ok=True) + shutil.copyfile(os.path.abspath(config_path), dst) + except shutil.SameFileError: + pass + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--config', metavar='FILE') + parser.add_argument('--sample', action='store_true', default=False) + parser.add_argument('--eval', action='store_true', default=False) + parser.add_argument('--change_val', action='store_true', default=False) + + args = parser.parse_args() + raw_config = lib.load_config(args.config) + timer = zero.Timer() + timer.run() + save_file(os.path.join(raw_config['parent_dir'], 'config.toml'), args.config) + if args.sample: + sample_smote( + parent_dir=raw_config['parent_dir'], + real_data_path=raw_config['real_data_path'], + **raw_config['smote_params'], + seed=raw_config['seed'], + change_val=args.change_val + ) + + save_file(os.path.join(raw_config['parent_dir'], 'info.json'), os.path.join(raw_config['real_data_path'], 'info.json')) + if args.eval: + if raw_config['eval']['type']['eval_model'] == 'catboost': + train_catboost( + parent_dir=raw_config['parent_dir'], + real_data_path=raw_config['real_data_path'], + eval_type=raw_config['eval']['type']['eval_type'], + T_dict=raw_config['eval']['T'], + seed=raw_config['seed'], + change_val=args.change_val + ) + # elif raw_config['eval']['type']['eval_model'] == 'mlp': + # train_mlp( + # parent_dir=raw_config['parent_dir'], + # real_data_path=raw_config['real_data_path'], + # eval_type=raw_config['eval']['type']['eval_type'], + # T_dict=raw_config['eval']['T'], + # seed=raw_config['seed'], + # change_val=args.change_val + # ) + + print(f'Elapsed time: {str(timer)}') + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/smote/sample_smote.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/smote/sample_smote.py new file mode 100644 index 0000000000000000000000000000000000000000..63674186c3f1524d57bb4882f0c3dd432147230f --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/smote/sample_smote.py @@ -0,0 +1,210 @@ +import os +import lib +import argparse +import numpy as np +from pathlib import Path +from typing import Union, Any +from imblearn.over_sampling import SMOTE, SMOTENC +from sklearn.model_selection import train_test_split +from sklearn.preprocessing import MinMaxScaler +from sklearn.utils import check_random_state + +class MySMOTE(SMOTE): + def __init__( + self, + lam1=0.0, + lam2=1.0, + *, + sampling_strategy="auto", + random_state=None, + k_neighbors=5, + n_jobs=None, + ): + super().__init__( + sampling_strategy=sampling_strategy, + random_state=random_state, + k_neighbors=k_neighbors, + n_jobs=n_jobs, + ) + + self.lam1=lam1 + self.lam2=lam2 + + def _make_samples( + self, X, y_dtype, y_type, nn_data, nn_num, n_samples, step_size=1.0 + ): + random_state = check_random_state(self.random_state) + samples_indices = random_state.randint(low=0, high=nn_num.size, size=n_samples) + + # np.newaxis for backwards compatability with random_state + steps = step_size * random_state.uniform(low=self.lam1, high=self.lam2, size=n_samples)[:, np.newaxis] + rows = np.floor_divide(samples_indices, nn_num.shape[1]) + cols = np.mod(samples_indices, nn_num.shape[1]) + + X_new = self._generate_samples(X, nn_data, nn_num, rows, cols, steps) + y_new = np.full(n_samples, fill_value=y_type, dtype=y_dtype) + return X_new, y_new + +class MySMOTENC(SMOTENC): + def __init__( + self, + lam1=0.0, + lam2=1.0, + *, + categorical_features, + sampling_strategy="auto", + random_state=None, + k_neighbors=5, + n_jobs=None + ): + super().__init__( + categorical_features=categorical_features, + sampling_strategy=sampling_strategy, + random_state=random_state, + k_neighbors=k_neighbors, + n_jobs=n_jobs, + ) + + self.lam1=0.0 + self.lam2=1.0 + + def _make_samples( + self, X, y_dtype, y_type, nn_data, nn_num, n_samples, step_size=1.0, lam1=0.0, lam2=1.0 + ): + random_state = check_random_state(self.random_state) + samples_indices = random_state.randint(low=0, high=nn_num.size, size=n_samples) + + # np.newaxis for backwards compatability with random_state + steps = step_size * random_state.uniform(low=self.lam1, high=self.lam2, size=n_samples)[:, np.newaxis] + rows = np.floor_divide(samples_indices, nn_num.shape[1]) + cols = np.mod(samples_indices, nn_num.shape[1]) + + X_new = self._generate_samples(X, nn_data, nn_num, rows, cols, steps) + y_new = np.full(n_samples, fill_value=y_type, dtype=y_dtype) + return X_new, y_new + +def save_data(X, y, path, n_cat_features=0): + if n_cat_features > 0: + X_num = X[:, :-n_cat_features] + X_cat = X[:, -n_cat_features:] + else: + X_num = X + X_cat = None + + + np.save(path / "X_num_train", X_num.astype(float), allow_pickle=True) + np.save(path / "y_train", y, allow_pickle=True) + if X_cat is not None: + np.save(path / "X_cat_train", X_cat, allow_pickle=True) + +def sample_smote( + parent_dir, + real_data_path, + eval_type = "synthetic", + k_neighbours = 5, + frac_samples = 1.0, + frac_lam_del = 0.0, + change_val = False, + save = True, + seed = 0 +): + lam1 = 0.0 + frac_lam_del / 2 + lam2 = 1.0 - frac_lam_del / 2 + + real_data_path = Path(real_data_path) + info = lib.load_json(real_data_path / 'info.json') + is_regression = info['task_type'] == 'regression' + + X_num = {} + X_cat = {} + y = {} + + if change_val: + X_num['train'], X_cat['train'], y['train'], X_num['val'], X_cat['val'], y['val'] = lib.read_changed_val(real_data_path) + else: + X_num['train'], X_cat['train'], y['train'] = lib.read_pure_data(real_data_path, 'train') + X_num['val'], X_cat['val'], y['val'] = lib.read_pure_data(real_data_path, 'val') + X_num['test'], X_cat['test'], y['test'] = lib.read_pure_data(real_data_path, 'test') + + + X = {k: X_num[k] for k in X_num.keys()} + + if is_regression: + X['train'] = np.concatenate([X["train"], y["train"].reshape(-1, 1)], axis=1, dtype=object) + y['train'] = np.where(y["train"] > np.median(y["train"]), 1, 0) + + n_num_features = X['train'].shape[1] + n_cat_features = X_cat['train'].shape[1] if X_cat['train'] is not None else 0 + cat_features = list(range(n_num_features, n_num_features+n_cat_features)) + print(cat_features) + + scaler = MinMaxScaler().fit(X["train"]) + X["train"] = scaler.transform(X["train"]).astype(object) + + if X_cat['train'] is not None: + for k in X_num.keys(): + X[k] = np.concatenate([X[k], X_cat[k]], axis=1, dtype=object) + + print("Before:", X['train'].shape) + + if eval_type != 'real': + strat = {k: int((1 + frac_samples) * np.sum(y['train'] == k)) for k in np.unique(y['train'])} + print(strat) + if n_cat_features > 0: + sm = MySMOTENC( + lam1=lam1, + lam2=lam2, + random_state=seed, + k_neighbors=k_neighbours, + categorical_features=cat_features, + sampling_strategy=strat + ) + else: + sm = MySMOTE( + lam1=lam1, + lam2=lam2, + random_state=seed, + k_neighbors=k_neighbours, + sampling_strategy=strat + ) + + X_res, y_res = sm.fit_resample(X['train'], y['train']) + if is_regression: + X_res[:, :X_num["train"].shape[1]+1] = scaler.inverse_transform(X_res[:, :X_num["train"].shape[1]+1]) + y_res = X_res[:, X_num["train"].shape[1]] + X_res = np.delete(X_res, [X_num["train"].shape[1]], axis=1) + else: + X_res[:, :X_num["train"].shape[1]] = scaler.inverse_transform(X_res[:, :X_num["train"].shape[1]]) + y_res = y_res.astype(int) + + if eval_type == "synthetic": + X_res = X_res[X['train'].shape[0]:] + y_res = y_res[X['train'].shape[0]:] + + disc_cols = [] + for col in range(X_num["train"].shape[1]): + uniq_vals = np.unique(X_num["train"][:, col]) + if len(uniq_vals) <= 32 and ((uniq_vals - np.round(uniq_vals)) == 0).all(): + disc_cols.append(col) + if len(disc_cols): + X_res[:, :X_num["train"].shape[1]] = lib.round_columns(X_num["train"], X_res[:, :X_num["train"].shape[1]], disc_cols) + + if save: + save_data(X_res, y_res, Path(parent_dir), n_cat_features) + + X['train'] = X_res + y['train'] = y_res + + return X, y + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('data_path', type=str) + parser.add_argument('method', type=str) + + args = parser.parse_args() + + sample_smote(args.data_path, args.method, save=False) + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/smote/tune_smote.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/smote/tune_smote.py new file mode 100644 index 0000000000000000000000000000000000000000..9c98e205150bd02fee9ce399280714101bd427c3 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/smote/tune_smote.py @@ -0,0 +1,98 @@ +import optuna +import lib +from copy import deepcopy +import argparse +import tempfile +from pathlib import Path +import os +from scripts.eval_catboost import train_catboost +from sample_smote import sample_smote +import subprocess + +parser = argparse.ArgumentParser() +parser.add_argument('data_path', type=str) +parser.add_argument('eval_type', type=str) + +args = parser.parse_args() +real_data_path = args.data_path +eval_type = args.eval_type + +def objective(trial): + + k_neighbours = trial.suggest_int("k_neighbours", 5, 20) + frac_samples = 2 ** trial.suggest_int('frac_samples', -2, 3) + + # z = \lam*x + (1 - \lam)*y, \lam ~ U[frac_lam_del/2, 1-frac_lam_del/2] + frac_lam_del = trial.suggest_float("frac_lam_del", 0.0, 0.95, step=0.05) + + score = 0.0 + with tempfile.TemporaryDirectory() as dir_: + dir_ = Path(dir_) + for seed in range(5): + sample_smote( + parent_dir=dir_, + real_data_path=real_data_path, + eval_type=eval_type, + frac_samples=frac_samples, + frac_lam_del=frac_lam_del, + k_neighbours=k_neighbours, + change_val=True, + seed=seed + ) + T_dict = { + "seed": 0, + "normalization": None, + "num_nan_policy": None, + "cat_nan_policy": None, + "cat_min_frequency": None, + "cat_encoding": None, + "y_policy": "default" + } + metrics = train_catboost( + parent_dir=dir_, + real_data_path=real_data_path, + eval_type=eval_type, + T_dict=T_dict, + change_val=True, + seed = 0 + ) + + score += metrics.get_val_score() + + return score / 5 + +study = optuna.create_study( + direction='maximize', + sampler=optuna.samplers.TPESampler(seed=0), +) + +study.optimize(objective, n_trials=5, show_progress_bar=True) + +os.makedirs(f"exp/{Path(real_data_path).name}/smote/", exist_ok=True) +config = { + "parent_dir": f"exp/{Path(real_data_path).name}/smote/", + "real_data_path": real_data_path, + "seed": 0, + "smote_params": {}, + "sample": {"seed": 0}, + "eval": { + "type": {"eval_model": "catboost", "eval_type": eval_type}, + "T": { + "seed": 0, + "normalization": None, + "num_nan_policy": None, + "cat_nan_policy": None, + "cat_min_frequency": None, + "cat_encoding": None, + "y_policy": "default" + }, + } +} + +config["smote_params"] = study.best_params +config["smote_params"]["frac_samples"] = 2 ** config["smote_params"]["frac_samples"] + +lib.dump_config(config, config["parent_dir"]+"config.toml") + +subprocess.run(['python3.9', "scripts/eval_seeds.py", '--config', f'{config["parent_dir"]+"config.toml"}', + '10', "smote", eval_type, "catboost", "5"], check=True) \ No newline at end of file diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/__init__.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8ad340c806b61da5a372186d04f2e7ab88a74daa --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/__init__.py @@ -0,0 +1,2 @@ +from .gaussian_multinomial_diffsuion import * # noqa +from .modules import * # noqa \ No newline at end of file diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/__pycache__/__init__.cpython-311.pyc b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b52259c1bb2f7b39a98b0227bc259f713397e4e Binary files /dev/null and b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/__pycache__/__init__.cpython-311.pyc differ diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/__pycache__/gaussian_multinomial_diffsuion.cpython-311.pyc b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/__pycache__/gaussian_multinomial_diffsuion.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f15fcf941f38c05c485dcf0e5ebc8e3324cd37fb Binary files /dev/null and b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/__pycache__/gaussian_multinomial_diffsuion.cpython-311.pyc differ diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/__pycache__/modules.cpython-311.pyc b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/__pycache__/modules.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9033bfe943ef7f87f2194e7c77d453068ad30e81 Binary files /dev/null and b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/__pycache__/modules.cpython-311.pyc differ diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/__pycache__/utils.cpython-311.pyc b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94dd849838c2a91264cf74ef9183d287f54f2491 Binary files /dev/null and b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/__pycache__/utils.cpython-311.pyc differ diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/gaussian_multinomial_diffsuion.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/gaussian_multinomial_diffsuion.py new file mode 100644 index 0000000000000000000000000000000000000000..5e3cb1c3086b2fa5862552e91e648677bb673dd9 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/gaussian_multinomial_diffsuion.py @@ -0,0 +1,993 @@ +""" +Based on https://github.com/openai/guided-diffusion/blob/main/guided_diffusion +and https://github.com/ehoogeboom/multinomial_diffusion +""" + +import torch.nn.functional as F +import torch +import math + +import numpy as np +from .utils import * + +""" +Based in part on: https://github.com/lucidrains/denoising-diffusion-pytorch/blob/5989f4c77eafcdc6be0fb4739f0f277a6dd7f7d8/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py#L281 +""" +eps = 1e-8 + +def get_named_beta_schedule(schedule_name, num_diffusion_timesteps): + """ + Get a pre-defined beta schedule for the given name. + The beta schedule library consists of beta schedules which remain similar + in the limit of num_diffusion_timesteps. + Beta schedules may be added, but should not be removed or changed once + they are committed to maintain backwards compatibility. + """ + if schedule_name == "linear": + # Linear schedule from Ho et al, extended to work for any number of + # diffusion steps. + scale = 1000 / num_diffusion_timesteps + beta_start = scale * 0.0001 + beta_end = scale * 0.02 + return np.linspace( + beta_start, beta_end, num_diffusion_timesteps, dtype=np.float64 + ) + elif schedule_name == "cosine": + return betas_for_alpha_bar( + num_diffusion_timesteps, + lambda t: math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2, + ) + else: + raise NotImplementedError(f"unknown beta schedule: {schedule_name}") + + +def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999): + """ + Create a beta schedule that discretizes the given alpha_t_bar function, + which defines the cumulative product of (1-beta) over time from t = [0,1]. + :param num_diffusion_timesteps: the number of betas to produce. + :param alpha_bar: a lambda that takes an argument t from 0 to 1 and + produces the cumulative product of (1-beta) up to that + part of the diffusion process. + :param max_beta: the maximum beta to use; use values lower than 1 to + prevent singularities. + """ + betas = [] + for i in range(num_diffusion_timesteps): + t1 = i / num_diffusion_timesteps + t2 = (i + 1) / num_diffusion_timesteps + betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta)) + return np.array(betas) + +class GaussianMultinomialDiffusion(torch.nn.Module): + def __init__( + self, + num_classes: np.array, + num_numerical_features: int, + denoise_fn, + num_timesteps=1000, + gaussian_loss_type='mse', + gaussian_parametrization='eps', + multinomial_loss_type='vb_stochastic', + parametrization='x0', + scheduler='cosine', + device=torch.device('cpu') + ): + + super(GaussianMultinomialDiffusion, self).__init__() + assert multinomial_loss_type in ('vb_stochastic', 'vb_all') + assert parametrization in ('x0', 'direct') + + if multinomial_loss_type == 'vb_all': + print('Computing the loss using the bound on _all_ timesteps.' + ' This is expensive both in terms of memory and computation.') + + self.num_numerical_features = num_numerical_features + self.num_classes = num_classes # it as a vector [K1, K2, ..., Km] + self.num_classes_expanded = torch.from_numpy( + np.concatenate([num_classes[i].repeat(num_classes[i]) for i in range(len(num_classes))]) + ).to(device) + + self.slices_for_classes = [np.arange(self.num_classes[0])] + offsets = np.cumsum(self.num_classes) + for i in range(1, len(offsets)): + self.slices_for_classes.append(np.arange(offsets[i - 1], offsets[i])) + self.offsets = torch.from_numpy(np.append([0], offsets)).to(device) + + self._denoise_fn = denoise_fn + self.gaussian_loss_type = gaussian_loss_type + self.gaussian_parametrization = gaussian_parametrization + self.multinomial_loss_type = multinomial_loss_type + self.num_timesteps = num_timesteps + self.parametrization = parametrization + self.scheduler = scheduler + + alphas = 1. - get_named_beta_schedule(scheduler, num_timesteps) + alphas = torch.tensor(alphas.astype('float64')) + betas = 1. - alphas + + log_alpha = np.log(alphas) + log_cumprod_alpha = np.cumsum(log_alpha) + + log_1_min_alpha = log_1_min_a(log_alpha) + log_1_min_cumprod_alpha = log_1_min_a(log_cumprod_alpha) + + alphas_cumprod = np.cumprod(alphas, axis=0) + alphas_cumprod_prev = torch.tensor(np.append(1.0, alphas_cumprod[:-1])) + alphas_cumprod_next = torch.tensor(np.append(alphas_cumprod[1:], 0.0)) + sqrt_alphas_cumprod = np.sqrt(alphas_cumprod) + sqrt_one_minus_alphas_cumprod = np.sqrt(1.0 - alphas_cumprod) + sqrt_recip_alphas_cumprod = np.sqrt(1.0 / alphas_cumprod) + sqrt_recipm1_alphas_cumprod = np.sqrt(1.0 / alphas_cumprod - 1) + + # Gaussian diffusion + + self.posterior_variance = ( + betas * (1.0 - alphas_cumprod_prev) / (1.0 - alphas_cumprod) + ) + self.posterior_log_variance_clipped = torch.from_numpy( + np.log(np.append(self.posterior_variance[1], self.posterior_variance[1:])) + ).float().to(device) + self.posterior_mean_coef1 = ( + betas * np.sqrt(alphas_cumprod_prev) / (1.0 - alphas_cumprod) + ).float().to(device) + self.posterior_mean_coef2 = ( + (1.0 - alphas_cumprod_prev) + * np.sqrt(alphas.numpy()) + / (1.0 - alphas_cumprod) + ).float().to(device) + + assert log_add_exp(log_alpha, log_1_min_alpha).abs().sum().item() < 1.e-5 + assert log_add_exp(log_cumprod_alpha, log_1_min_cumprod_alpha).abs().sum().item() < 1e-5 + assert (np.cumsum(log_alpha) - log_cumprod_alpha).abs().sum().item() < 1.e-5 + + # Convert to float32 and register buffers. + self.register_buffer('alphas', alphas.float().to(device)) + self.register_buffer('log_alpha', log_alpha.float().to(device)) + self.register_buffer('log_1_min_alpha', log_1_min_alpha.float().to(device)) + self.register_buffer('log_1_min_cumprod_alpha', log_1_min_cumprod_alpha.float().to(device)) + self.register_buffer('log_cumprod_alpha', log_cumprod_alpha.float().to(device)) + self.register_buffer('alphas_cumprod', alphas_cumprod.float().to(device)) + self.register_buffer('alphas_cumprod_prev', alphas_cumprod_prev.float().to(device)) + self.register_buffer('alphas_cumprod_next', alphas_cumprod_next.float().to(device)) + self.register_buffer('sqrt_alphas_cumprod', sqrt_alphas_cumprod.float().to(device)) + self.register_buffer('sqrt_one_minus_alphas_cumprod', sqrt_one_minus_alphas_cumprod.float().to(device)) + self.register_buffer('sqrt_recip_alphas_cumprod', sqrt_recip_alphas_cumprod.float().to(device)) + self.register_buffer('sqrt_recipm1_alphas_cumprod', sqrt_recipm1_alphas_cumprod.float().to(device)) + + self.register_buffer('Lt_history', torch.zeros(num_timesteps)) + self.register_buffer('Lt_count', torch.zeros(num_timesteps)) + + # Gaussian part + def gaussian_q_mean_variance(self, x_start, t): + mean = ( + extract(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start + ) + variance = extract(1.0 - self.alphas_cumprod, t, x_start.shape) + log_variance = extract( + self.log_1_min_cumprod_alpha, t, x_start.shape + ) + return mean, variance, log_variance + + def gaussian_q_sample(self, x_start, t, noise=None): + if noise is None: + noise = torch.randn_like(x_start) + assert noise.shape == x_start.shape + return ( + extract(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start + + extract(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) + * noise + ) + + def gaussian_q_posterior_mean_variance(self, x_start, x_t, t): + assert x_start.shape == x_t.shape + posterior_mean = ( + extract(self.posterior_mean_coef1, t, x_t.shape) * x_start + + extract(self.posterior_mean_coef2, t, x_t.shape) * x_t + ) + posterior_variance = extract(self.posterior_variance, t, x_t.shape) + posterior_log_variance_clipped = extract( + self.posterior_log_variance_clipped, t, x_t.shape + ) + assert ( + posterior_mean.shape[0] + == posterior_variance.shape[0] + == posterior_log_variance_clipped.shape[0] + == x_start.shape[0] + ) + return posterior_mean, posterior_variance, posterior_log_variance_clipped + + def gaussian_p_mean_variance( + self, model_output, x, t, clip_denoised=False, denoised_fn=None, model_kwargs=None + ): + if model_kwargs is None: + model_kwargs = {} + + B, C = x.shape[:2] + assert t.shape == (B,) + + model_variance = torch.cat([self.posterior_variance[1].unsqueeze(0).to(x.device), (1. - self.alphas)[1:]], dim=0) + # model_variance = self.posterior_variance.to(x.device) + model_log_variance = torch.log(model_variance) + + model_variance = extract(model_variance, t, x.shape) + model_log_variance = extract(model_log_variance, t, x.shape) + + + if self.gaussian_parametrization == 'eps': + pred_xstart = self._predict_xstart_from_eps(x_t=x, t=t, eps=model_output) + elif self.gaussian_parametrization == 'x0': + pred_xstart = model_output + else: + raise NotImplementedError + + model_mean, _, _ = self.gaussian_q_posterior_mean_variance( + x_start=pred_xstart, x_t=x, t=t + ) + + assert ( + model_mean.shape == model_log_variance.shape == pred_xstart.shape == x.shape + ), f'{model_mean.shape}, {model_log_variance.shape}, {pred_xstart.shape}, {x.shape}' + + return { + "mean": model_mean, + "variance": model_variance, + "log_variance": model_log_variance, + "pred_xstart": pred_xstart, + } + + def _vb_terms_bpd( + self, model_output, x_start, x_t, t, clip_denoised=False, model_kwargs=None + ): + true_mean, _, true_log_variance_clipped = self.gaussian_q_posterior_mean_variance( + x_start=x_start, x_t=x_t, t=t + ) + out = self.gaussian_p_mean_variance( + model_output, x_t, t, clip_denoised=clip_denoised, model_kwargs=model_kwargs + ) + kl = normal_kl( + true_mean, true_log_variance_clipped, out["mean"], out["log_variance"] + ) + kl = mean_flat(kl) / np.log(2.0) + + decoder_nll = -discretized_gaussian_log_likelihood( + x_start, means=out["mean"], log_scales=0.5 * out["log_variance"] + ) + assert decoder_nll.shape == x_start.shape + decoder_nll = mean_flat(decoder_nll) / np.log(2.0) + + # At the first timestep return the decoder NLL, + # otherwise return KL(q(x_{t-1}|x_t,x_0) || p(x_{t-1}|x_t)) + output = torch.where((t == 0), decoder_nll, kl) + return {"output": output, "pred_xstart": out["pred_xstart"], "out_mean": out["mean"], "true_mean": true_mean} + + def _prior_gaussian(self, x_start): + """ + Get the prior KL term for the variational lower-bound, measured in + bits-per-dim. + + This term can't be optimized, as it only depends on the encoder. + + :param x_start: the [N x C x ...] tensor of inputs. + :return: a batch of [N] KL values (in bits), one per batch element. + """ + batch_size = x_start.shape[0] + t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device) + qt_mean, _, qt_log_variance = self.gaussian_q_mean_variance(x_start, t) + kl_prior = normal_kl( + mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0 + ) + return mean_flat(kl_prior) / np.log(2.0) + + def _gaussian_loss(self, model_out, x_start, x_t, t, noise, model_kwargs=None): + if model_kwargs is None: + model_kwargs = {} + + terms = {} + if self.gaussian_loss_type == 'mse': + terms["loss"] = mean_flat((noise - model_out) ** 2) + elif self.gaussian_loss_type == 'kl': + terms["loss"] = self._vb_terms_bpd( + model_output=model_out, + x_start=x_start, + x_t=x_t, + t=t, + clip_denoised=False, + model_kwargs=model_kwargs, + )["output"] + + + return terms['loss'] + + def _predict_xstart_from_eps(self, x_t, t, eps): + assert x_t.shape == eps.shape + return ( + extract(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t + - extract(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * eps + ) + + def _predict_eps_from_xstart(self, x_t, t, pred_xstart): + return ( + extract(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t + - pred_xstart + ) / extract(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) + + def gaussian_p_sample( + self, + model_out, + x, + t, + clip_denoised=False, + denoised_fn=None, + model_kwargs=None, + ): + out = self.gaussian_p_mean_variance( + model_out, + x, + t, + clip_denoised=clip_denoised, + denoised_fn=denoised_fn, + model_kwargs=model_kwargs, + ) + noise = torch.randn_like(x) + nonzero_mask = ( + (t != 0).float().view(-1, *([1] * (len(x.shape) - 1))) + ) # no noise when t == 0 + + sample = out["mean"] + nonzero_mask * torch.exp(0.5 * out["log_variance"]) * noise + return {"sample": sample, "pred_xstart": out["pred_xstart"]} + + # Multinomial part + + def multinomial_kl(self, log_prob1, log_prob2): + kl = (log_prob1.exp() * (log_prob1 - log_prob2)).sum(dim=1) + return kl + + def q_pred_one_timestep(self, log_x_t, t): + log_alpha_t = extract(self.log_alpha, t, log_x_t.shape) + log_1_min_alpha_t = extract(self.log_1_min_alpha, t, log_x_t.shape) + + # alpha_t * E[xt] + (1 - alpha_t) 1 / K + log_probs = log_add_exp( + log_x_t + log_alpha_t, + log_1_min_alpha_t - torch.log(self.num_classes_expanded) + ) + + return log_probs + + def q_pred(self, log_x_start, t): + log_cumprod_alpha_t = extract(self.log_cumprod_alpha, t, log_x_start.shape) + log_1_min_cumprod_alpha = extract(self.log_1_min_cumprod_alpha, t, log_x_start.shape) + + log_probs = log_add_exp( + log_x_start + log_cumprod_alpha_t, + log_1_min_cumprod_alpha - torch.log(self.num_classes_expanded) + ) + + return log_probs + + def predict_start(self, model_out, log_x_t, t, out_dict): + + # model_out = self._denoise_fn(x_t, t.to(x_t.device), **out_dict) + + assert model_out.size(0) == log_x_t.size(0) + assert model_out.size(1) == self.num_classes.sum(), f'{model_out.size()}' + + log_pred = torch.empty_like(model_out) + for ix in self.slices_for_classes: + log_pred[:, ix] = F.log_softmax(model_out[:, ix], dim=1) + return log_pred + + def q_posterior(self, log_x_start, log_x_t, t): + # q(xt-1 | xt, x0) = q(xt | xt-1, x0) * q(xt-1 | x0) / q(xt | x0) + # where q(xt | xt-1, x0) = q(xt | xt-1). + + # EV_log_qxt_x0 = self.q_pred(log_x_start, t) + + # print('sum exp', EV_log_qxt_x0.exp().sum(1).mean()) + # assert False + + # log_qxt_x0 = (log_x_t.exp() * EV_log_qxt_x0).sum(dim=1) + t_minus_1 = t - 1 + # Remove negative values, will not be used anyway for final decoder + t_minus_1 = torch.where(t_minus_1 < 0, torch.zeros_like(t_minus_1), t_minus_1) + log_EV_qxtmin_x0 = self.q_pred(log_x_start, t_minus_1) + + num_axes = (1,) * (len(log_x_start.size()) - 1) + t_broadcast = t.to(log_x_start.device).view(-1, *num_axes) * torch.ones_like(log_x_start) + log_EV_qxtmin_x0 = torch.where(t_broadcast == 0, log_x_start, log_EV_qxtmin_x0.to(torch.float32)) + + # unnormed_logprobs = log_EV_qxtmin_x0 + + # log q_pred_one_timestep(x_t, t) + # Note: _NOT_ x_tmin1, which is how the formula is typically used!!! + # Not very easy to see why this is true. But it is :) + unnormed_logprobs = log_EV_qxtmin_x0 + self.q_pred_one_timestep(log_x_t, t) + + log_EV_xtmin_given_xt_given_xstart = \ + unnormed_logprobs \ + - sliced_logsumexp(unnormed_logprobs, self.offsets) + + return log_EV_xtmin_given_xt_given_xstart + + def p_pred(self, model_out, log_x, t, out_dict): + if self.parametrization == 'x0': + log_x_recon = self.predict_start(model_out, log_x, t=t, out_dict=out_dict) + log_model_pred = self.q_posterior( + log_x_start=log_x_recon, log_x_t=log_x, t=t) + elif self.parametrization == 'direct': + log_model_pred = self.predict_start(model_out, log_x, t=t, out_dict=out_dict) + else: + raise ValueError + return log_model_pred + + @torch.no_grad() + def p_sample(self, model_out, log_x, t, out_dict): + model_log_prob = self.p_pred(model_out, log_x=log_x, t=t, out_dict=out_dict) + out = self.log_sample_categorical(model_log_prob) + return out + + @torch.no_grad() + def p_sample_loop(self, shape, out_dict): + device = self.log_alpha.device + + b = shape[0] + # start with random normal image. + img = torch.randn(shape, device=device) + + for i in reversed(range(1, self.num_timesteps)): + img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long), out_dict) + return img + + @torch.no_grad() + def _sample(self, image_size, out_dict, batch_size = 16): + return self.p_sample_loop((batch_size, 3, image_size, image_size), out_dict) + + @torch.no_grad() + def interpolate(self, x1, x2, t = None, lam = 0.5): + b, *_, device = *x1.shape, x1.device + t = default(t, self.num_timesteps - 1) + + assert x1.shape == x2.shape + + t_batched = torch.stack([torch.tensor(t, device=device)] * b) + xt1, xt2 = map(lambda x: self.q_sample(x, t=t_batched), (x1, x2)) + + img = (1 - lam) * xt1 + lam * xt2 + for i in reversed(range(0, t)): + img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long)) + + return img + + def log_sample_categorical(self, logits): + full_sample = [] + for i in range(len(self.num_classes)): + one_class_logits = logits[:, self.slices_for_classes[i]] + uniform = torch.rand_like(one_class_logits) + gumbel_noise = -torch.log(-torch.log(uniform + 1e-30) + 1e-30) + sample = (gumbel_noise + one_class_logits).argmax(dim=1) + full_sample.append(sample.unsqueeze(1)) + full_sample = torch.cat(full_sample, dim=1) + log_sample = index_to_log_onehot(full_sample, self.num_classes) + return log_sample + + def q_sample(self, log_x_start, t): + log_EV_qxt_x0 = self.q_pred(log_x_start, t) + + log_sample = self.log_sample_categorical(log_EV_qxt_x0) + + return log_sample + + def nll(self, log_x_start, out_dict): + b = log_x_start.size(0) + device = log_x_start.device + loss = 0 + for t in range(0, self.num_timesteps): + t_array = (torch.ones(b, device=device) * t).long() + + kl = self.compute_Lt( + log_x_start=log_x_start, + log_x_t=self.q_sample(log_x_start=log_x_start, t=t_array), + t=t_array, + out_dict=out_dict) + + loss += kl + + loss += self.kl_prior(log_x_start) + + return loss + + def kl_prior(self, log_x_start): + b = log_x_start.size(0) + device = log_x_start.device + ones = torch.ones(b, device=device).long() + + log_qxT_prob = self.q_pred(log_x_start, t=(self.num_timesteps - 1) * ones) + log_half_prob = -torch.log(self.num_classes_expanded * torch.ones_like(log_qxT_prob)) + + kl_prior = self.multinomial_kl(log_qxT_prob, log_half_prob) + return sum_except_batch(kl_prior) + + def compute_Lt(self, model_out, log_x_start, log_x_t, t, out_dict, detach_mean=False): + log_true_prob = self.q_posterior( + log_x_start=log_x_start, log_x_t=log_x_t, t=t) + log_model_prob = self.p_pred(model_out, log_x=log_x_t, t=t, out_dict=out_dict) + + if detach_mean: + log_model_prob = log_model_prob.detach() + + kl = self.multinomial_kl(log_true_prob, log_model_prob) + kl = sum_except_batch(kl) + + decoder_nll = -log_categorical(log_x_start, log_model_prob) + decoder_nll = sum_except_batch(decoder_nll) + + mask = (t == torch.zeros_like(t)).float() + loss = mask * decoder_nll + (1. - mask) * kl + + return loss + + def sample_time(self, b, device, method='uniform'): + if method == 'importance': + if not (self.Lt_count > 10).all(): + return self.sample_time(b, device, method='uniform') + + Lt_sqrt = torch.sqrt(self.Lt_history + 1e-10) + 0.0001 + Lt_sqrt[0] = Lt_sqrt[1] # Overwrite decoder term with L1. + pt_all = (Lt_sqrt / Lt_sqrt.sum()).to(device) + + t = torch.multinomial(pt_all, num_samples=b, replacement=True).to(device) + + pt = pt_all.gather(dim=0, index=t) + + return t, pt + + elif method == 'uniform': + t = torch.randint(0, self.num_timesteps, (b,), device=device).long() + + pt = torch.ones_like(t).float() / self.num_timesteps + return t, pt + else: + raise ValueError + + def _multinomial_loss(self, model_out, log_x_start, log_x_t, t, pt, out_dict): + + if self.multinomial_loss_type == 'vb_stochastic': + kl = self.compute_Lt( + model_out, log_x_start, log_x_t, t, out_dict + ) + kl_prior = self.kl_prior(log_x_start) + # Upweigh loss term of the kl + vb_loss = kl / pt + kl_prior + + return vb_loss + + elif self.multinomial_loss_type == 'vb_all': + # Expensive, dont do it ;). + # DEPRECATED + return -self.nll(log_x_start) + else: + raise ValueError() + + def log_prob(self, x, out_dict): + b, device = x.size(0), x.device + if self.training: + return self._multinomial_loss(x, out_dict) + + else: + log_x_start = index_to_log_onehot(x, self.num_classes) + + t, pt = self.sample_time(b, device, 'importance') + + kl = self.compute_Lt( + log_x_start, self.q_sample(log_x_start=log_x_start, t=t), t, out_dict) + + kl_prior = self.kl_prior(log_x_start) + + # Upweigh loss term of the kl + loss = kl / pt + kl_prior + + return -loss + + def mixed_loss(self, x, out_dict): + b = x.shape[0] + device = x.device + t, pt = self.sample_time(b, device, 'uniform') + + x_num = x[:, :self.num_numerical_features] + x_cat = x[:, self.num_numerical_features:] + + x_num_t = x_num + log_x_cat_t = x_cat + if x_num.shape[1] > 0: + noise = torch.randn_like(x_num) + x_num_t = self.gaussian_q_sample(x_num, t, noise=noise) + if x_cat.shape[1] > 0: + log_x_cat = index_to_log_onehot(x_cat.long(), self.num_classes) + log_x_cat_t = self.q_sample(log_x_start=log_x_cat, t=t) + + x_in = torch.cat([x_num_t, log_x_cat_t], dim=1) + + model_out = self._denoise_fn( + x_in, + t, + **out_dict + ) + + model_out_num = model_out[:, :self.num_numerical_features] + model_out_cat = model_out[:, self.num_numerical_features:] + + loss_multi = torch.zeros((1,)).float() + loss_gauss = torch.zeros((1,)).float() + if x_cat.shape[1] > 0: + loss_multi = self._multinomial_loss(model_out_cat, log_x_cat, log_x_cat_t, t, pt, out_dict) / len(self.num_classes) + + if x_num.shape[1] > 0: + loss_gauss = self._gaussian_loss(model_out_num, x_num, x_num_t, t, noise) + + # loss_multi = torch.where(out_dict['y'] == 1, loss_multi, 2 * loss_multi) + # loss_gauss = torch.where(out_dict['y'] == 1, loss_gauss, 2 * loss_gauss) + + return loss_multi.mean(), loss_gauss.mean() + + @torch.no_grad() + def mixed_elbo(self, x0, out_dict): + b = x0.size(0) + device = x0.device + + x_num = x0[:, :self.num_numerical_features] + x_cat = x0[:, self.num_numerical_features:] + has_cat = x_cat.shape[1] > 0 + if has_cat: + log_x_cat = index_to_log_onehot(x_cat.long(), self.num_classes).to(device) + + gaussian_loss = [] + xstart_mse = [] + mse = [] + mu_mse = [] + out_mean = [] + true_mean = [] + multinomial_loss = [] + for t in range(self.num_timesteps): + t_array = (torch.ones(b, device=device) * t).long() + noise = torch.randn_like(x_num) + + x_num_t = self.gaussian_q_sample(x_start=x_num, t=t_array, noise=noise) + if has_cat: + log_x_cat_t = self.q_sample(log_x_start=log_x_cat, t=t_array) + else: + log_x_cat_t = x_cat + + model_out = self._denoise_fn( + torch.cat([x_num_t, log_x_cat_t], dim=1), + t_array, + **out_dict + ) + + model_out_num = model_out[:, :self.num_numerical_features] + model_out_cat = model_out[:, self.num_numerical_features:] + + kl = torch.tensor([0.0]) + if has_cat: + kl = self.compute_Lt( + model_out=model_out_cat, + log_x_start=log_x_cat, + log_x_t=log_x_cat_t, + t=t_array, + out_dict=out_dict + ) + + out = self._vb_terms_bpd( + model_out_num, + x_start=x_num, + x_t=x_num_t, + t=t_array, + clip_denoised=False + ) + + multinomial_loss.append(kl) + gaussian_loss.append(out["output"]) + xstart_mse.append(mean_flat((out["pred_xstart"] - x_num) ** 2)) + # mu_mse.append(mean_flat(out["mean_mse"])) + out_mean.append(mean_flat(out["out_mean"])) + true_mean.append(mean_flat(out["true_mean"])) + + eps = self._predict_eps_from_xstart(x_num_t, t_array, out["pred_xstart"]) + mse.append(mean_flat((eps - noise) ** 2)) + + gaussian_loss = torch.stack(gaussian_loss, dim=1) + multinomial_loss = torch.stack(multinomial_loss, dim=1) + xstart_mse = torch.stack(xstart_mse, dim=1) + mse = torch.stack(mse, dim=1) + # mu_mse = torch.stack(mu_mse, dim=1) + out_mean = torch.stack(out_mean, dim=1) + true_mean = torch.stack(true_mean, dim=1) + + + + prior_gauss = self._prior_gaussian(x_num) + + prior_multin = torch.tensor([0.0]) + if has_cat: + prior_multin = self.kl_prior(log_x_cat) + + total_gauss = gaussian_loss.sum(dim=1) + prior_gauss + total_multin = multinomial_loss.sum(dim=1) + prior_multin + return { + "total_gaussian": total_gauss, + "total_multinomial": total_multin, + "losses_gaussian": gaussian_loss, + "losses_multinimial": multinomial_loss, + "xstart_mse": xstart_mse, + "mse": mse, + # "mu_mse": mu_mse + "out_mean": out_mean, + "true_mean": true_mean + } + + @torch.no_grad() + def gaussian_ddim_step( + self, + model_out_num, + x, + t, + clip_denoised=False, + denoised_fn=None, + eta=0.0 + ): + out = self.gaussian_p_mean_variance( + model_out_num, + x, + t, + clip_denoised=clip_denoised, + denoised_fn=denoised_fn, + model_kwargs=None, + ) + + eps = self._predict_eps_from_xstart(x, t, out["pred_xstart"]) + + alpha_bar = extract(self.alphas_cumprod, t, x.shape) + alpha_bar_prev = extract(self.alphas_cumprod_prev, t, x.shape) + sigma = ( + eta + * torch.sqrt((1 - alpha_bar_prev) / (1 - alpha_bar)) + * torch.sqrt(1 - alpha_bar / alpha_bar_prev) + ) + + noise = torch.randn_like(x) + mean_pred = ( + out["pred_xstart"] * torch.sqrt(alpha_bar_prev) + + torch.sqrt(1 - alpha_bar_prev - sigma ** 2) * eps + ) + nonzero_mask = ( + (t != 0).float().view(-1, *([1] * (len(x.shape) - 1))) + ) # no noise when t == 0 + sample = mean_pred + nonzero_mask * sigma * noise + + return sample + + @torch.no_grad() + def gaussian_ddim_sample( + self, + noise, + T, + out_dict, + eta=0.0 + ): + x = noise + b = x.shape[0] + device = x.device + for t in reversed(range(T)): + print(f'Sample timestep {t:4d}', end='\r') + t_array = (torch.ones(b, device=device) * t).long() + out_num = self._denoise_fn(x, t_array, **out_dict) + x = self.gaussian_ddim_step( + out_num, + x, + t_array + ) + print() + return x + + + @torch.no_grad() + def gaussian_ddim_reverse_step( + self, + model_out_num, + x, + t, + clip_denoised=False, + eta=0.0 + ): + assert eta == 0.0, "Eta must be zero." + out = self.gaussian_p_mean_variance( + model_out_num, + x, + t, + clip_denoised=clip_denoised, + denoised_fn=None, + model_kwargs=None, + ) + + eps = ( + extract(self.sqrt_recip_alphas_cumprod, t, x.shape) * x + - out["pred_xstart"] + ) / extract(self.sqrt_recipm1_alphas_cumprod, t, x.shape) + alpha_bar_next = extract(self.alphas_cumprod_next, t, x.shape) + + mean_pred = ( + out["pred_xstart"] * torch.sqrt(alpha_bar_next) + + torch.sqrt(1 - alpha_bar_next) * eps + ) + + return mean_pred + + @torch.no_grad() + def gaussian_ddim_reverse_sample( + self, + x, + T, + out_dict, + ): + b = x.shape[0] + device = x.device + for t in range(T): + print(f'Reverse timestep {t:4d}', end='\r') + t_array = (torch.ones(b, device=device) * t).long() + out_num = self._denoise_fn(x, t_array, **out_dict) + x = self.gaussian_ddim_reverse_step( + out_num, + x, + t_array, + eta=0.0 + ) + print() + + return x + + + @torch.no_grad() + def multinomial_ddim_step( + self, + model_out_cat, + log_x_t, + t, + out_dict, + eta=0.0 + ): + # not ddim, essentially + log_x0 = self.predict_start(model_out_cat, log_x_t=log_x_t, t=t, out_dict=out_dict) + + alpha_bar = extract(self.alphas_cumprod, t, log_x_t.shape) + alpha_bar_prev = extract(self.alphas_cumprod_prev, t, log_x_t.shape) + sigma = ( + eta + * torch.sqrt((1 - alpha_bar_prev) / (1 - alpha_bar)) + * torch.sqrt(1 - alpha_bar / alpha_bar_prev) + ) + + coef1 = sigma + coef2 = alpha_bar_prev - sigma * alpha_bar + coef3 = 1 - coef1 - coef2 + + + log_ps = torch.stack([ + torch.log(coef1) + log_x_t, + torch.log(coef2) + log_x0, + torch.log(coef3) - torch.log(self.num_classes_expanded) + ], dim=2) + + log_prob = torch.logsumexp(log_ps, dim=2) + + out = self.log_sample_categorical(log_prob) + + return out + + @torch.no_grad() + def sample_ddim(self, num_samples, y_dist): + b = num_samples + device = self.log_alpha.device + z_norm = torch.randn((b, self.num_numerical_features), device=device) + + has_cat = self.num_classes[0] != 0 + log_z = torch.zeros((b, 0), device=device).float() + if has_cat: + uniform_logits = torch.zeros((b, len(self.num_classes_expanded)), device=device) + log_z = self.log_sample_categorical(uniform_logits) + + y = torch.multinomial( + y_dist, + num_samples=b, + replacement=True + ) + out_dict = {'y': y.long().to(device)} + for i in reversed(range(0, self.num_timesteps)): + print(f'Sample timestep {i:4d}', end='\r') + t = torch.full((b,), i, device=device, dtype=torch.long) + model_out = self._denoise_fn( + torch.cat([z_norm, log_z], dim=1).float(), + t, + **out_dict + ) + model_out_num = model_out[:, :self.num_numerical_features] + model_out_cat = model_out[:, self.num_numerical_features:] + z_norm = self.gaussian_ddim_step(model_out_num, z_norm, t, clip_denoised=False) + if has_cat: + log_z = self.multinomial_ddim_step(model_out_cat, log_z, t, out_dict) + + print() + z_ohe = torch.exp(log_z).round() + z_cat = log_z + if has_cat: + z_cat = ohe_to_categories(z_ohe, self.num_classes) + sample = torch.cat([z_norm, z_cat], dim=1).cpu() + return sample, out_dict + + + @torch.no_grad() + def sample(self, num_samples, y_dist): + b = num_samples + device = self.log_alpha.device + z_norm = torch.randn((b, self.num_numerical_features), device=device) + + has_cat = self.num_classes[0] != 0 + log_z = torch.zeros((b, 0), device=device).float() + if has_cat: + uniform_logits = torch.zeros((b, len(self.num_classes_expanded)), device=device) + log_z = self.log_sample_categorical(uniform_logits) + + y = torch.multinomial( + y_dist, + num_samples=b, + replacement=True + ) + out_dict = {'y': y.long().to(device)} + for i in reversed(range(0, self.num_timesteps)): + print(f'Sample timestep {i:4d}', end='\r') + t = torch.full((b,), i, device=device, dtype=torch.long) + model_out = self._denoise_fn( + torch.cat([z_norm, log_z], dim=1).float(), + t, + **out_dict + ) + model_out_num = model_out[:, :self.num_numerical_features] + model_out_cat = model_out[:, self.num_numerical_features:] + z_norm = self.gaussian_p_sample(model_out_num, z_norm, t, clip_denoised=False)['sample'] + if has_cat: + log_z = self.p_sample(model_out_cat, log_z, t, out_dict) + + print() + z_ohe = torch.exp(log_z).round() + z_cat = log_z + if has_cat: + z_cat = ohe_to_categories(z_ohe, self.num_classes) + sample = torch.cat([z_norm, z_cat], dim=1).cpu() + return sample, out_dict + + def sample_all(self, num_samples, batch_size, y_dist, ddim=False): + if ddim: + print('Sample using DDIM.') + sample_fn = self.sample_ddim + else: + sample_fn = self.sample + + b = batch_size + + all_y = [] + all_samples = [] + num_generated = 0 + while num_generated < num_samples: + sample, out_dict = sample_fn(b, y_dist) + mask_nan = torch.any(sample.isnan(), dim=1) + sample = sample[~mask_nan] + out_dict['y'] = out_dict['y'][~mask_nan] + + all_samples.append(sample) + all_y.append(out_dict['y'].cpu()) + if sample.shape[0] != b: + raise FoundNANsError + num_generated += sample.shape[0] + + x_gen = torch.cat(all_samples, dim=0)[:num_samples] + y_gen = torch.cat(all_y, dim=0)[:num_samples] + + return x_gen, y_gen \ No newline at end of file diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/modules.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/modules.py new file mode 100644 index 0000000000000000000000000000000000000000..472ba5b5f44b646e83d429f0d6272a8fe6d7130d --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/modules.py @@ -0,0 +1,486 @@ +""" +Code was adapted from https://github.com/Yura52/rtdl +""" + +import math +from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union, cast + +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.optim +from torch import Tensor + +ModuleType = Union[str, Callable[..., nn.Module]] + +class SiLU(nn.Module): + def forward(self, x): + return x * torch.sigmoid(x) + +def timestep_embedding(timesteps, dim, max_period=10000): + """ + Create sinusoidal timestep embeddings. + + :param timesteps: a 1-D Tensor of N indices, one per batch element. + These may be fractional. + :param dim: the dimension of the output. + :param max_period: controls the minimum frequency of the embeddings. + :return: an [N x dim] Tensor of positional embeddings. + """ + half = dim // 2 + freqs = torch.exp( + -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half + ).to(device=timesteps.device) + args = timesteps[:, None].float() * freqs[None] + embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) + if dim % 2: + embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) + return embedding + +def _is_glu_activation(activation: ModuleType): + return ( + isinstance(activation, str) + and activation.endswith('GLU') + or activation in [ReGLU, GEGLU] + ) + + +def _all_or_none(values): + assert all(x is None for x in values) or all(x is not None for x in values) + +def reglu(x: Tensor) -> Tensor: + """The ReGLU activation function from [1]. + References: + [1] Noam Shazeer, "GLU Variants Improve Transformer", 2020 + """ + assert x.shape[-1] % 2 == 0 + a, b = x.chunk(2, dim=-1) + return a * F.relu(b) + + +def geglu(x: Tensor) -> Tensor: + """The GEGLU activation function from [1]. + References: + [1] Noam Shazeer, "GLU Variants Improve Transformer", 2020 + """ + assert x.shape[-1] % 2 == 0 + a, b = x.chunk(2, dim=-1) + return a * F.gelu(b) + +class ReGLU(nn.Module): + """The ReGLU activation function from [shazeer2020glu]. + + Examples: + .. testcode:: + + module = ReGLU() + x = torch.randn(3, 4) + assert module(x).shape == (3, 2) + + References: + * [shazeer2020glu] Noam Shazeer, "GLU Variants Improve Transformer", 2020 + """ + + def forward(self, x: Tensor) -> Tensor: + return reglu(x) + + +class GEGLU(nn.Module): + """The GEGLU activation function from [shazeer2020glu]. + + Examples: + .. testcode:: + + module = GEGLU() + x = torch.randn(3, 4) + assert module(x).shape == (3, 2) + + References: + * [shazeer2020glu] Noam Shazeer, "GLU Variants Improve Transformer", 2020 + """ + + def forward(self, x: Tensor) -> Tensor: + return geglu(x) + +def _make_nn_module(module_type: ModuleType, *args) -> nn.Module: + return ( + ( + ReGLU() + if module_type == 'ReGLU' + else GEGLU() + if module_type == 'GEGLU' + else getattr(nn, module_type)(*args) + ) + if isinstance(module_type, str) + else module_type(*args) + ) + + +class MLP(nn.Module): + """The MLP model used in [gorishniy2021revisiting]. + + The following scheme describes the architecture: + + .. code-block:: text + + MLP: (in) -> Block -> ... -> Block -> Linear -> (out) + Block: (in) -> Linear -> Activation -> Dropout -> (out) + + Examples: + .. testcode:: + + x = torch.randn(4, 2) + module = MLP.make_baseline(x.shape[1], [3, 5], 0.1, 1) + assert module(x).shape == (len(x), 1) + + References: + * [gorishniy2021revisiting] Yury Gorishniy, Ivan Rubachev, Valentin Khrulkov, Artem Babenko, "Revisiting Deep Learning Models for Tabular Data", 2021 + """ + + class Block(nn.Module): + """The main building block of `MLP`.""" + + def __init__( + self, + *, + d_in: int, + d_out: int, + bias: bool, + activation: ModuleType, + dropout: float, + ) -> None: + super().__init__() + self.linear = nn.Linear(d_in, d_out, bias) + self.activation = _make_nn_module(activation) + self.dropout = nn.Dropout(dropout) + + def forward(self, x: Tensor) -> Tensor: + return self.dropout(self.activation(self.linear(x))) + + def __init__( + self, + *, + d_in: int, + d_layers: List[int], + dropouts: Union[float, List[float]], + activation: Union[str, Callable[[], nn.Module]], + d_out: int, + ) -> None: + """ + Note: + `make_baseline` is the recommended constructor. + """ + super().__init__() + if isinstance(dropouts, float): + dropouts = [dropouts] * len(d_layers) + assert len(d_layers) == len(dropouts) + assert activation not in ['ReGLU', 'GEGLU'] + + self.blocks = nn.ModuleList( + [ + MLP.Block( + d_in=d_layers[i - 1] if i else d_in, + d_out=d, + bias=True, + activation=activation, + dropout=dropout, + ) + for i, (d, dropout) in enumerate(zip(d_layers, dropouts)) + ] + ) + self.head = nn.Linear(d_layers[-1] if d_layers else d_in, d_out) + + @classmethod + def make_baseline( + cls: Type['MLP'], + d_in: int, + d_layers: List[int], + dropout: float, + d_out: int, + ) -> 'MLP': + """Create a "baseline" `MLP`. + + This variation of MLP was used in [gorishniy2021revisiting]. Features: + + * :code:`Activation` = :code:`ReLU` + * all linear layers except for the first one and the last one are of the same dimension + * the dropout rate is the same for all dropout layers + + Args: + d_in: the input size + d_layers: the dimensions of the linear layers. If there are more than two + layers, then all of them except for the first and the last ones must + have the same dimension. Valid examples: :code:`[]`, :code:`[8]`, + :code:`[8, 16]`, :code:`[2, 2, 2, 2]`, :code:`[1, 2, 2, 4]`. Invalid + example: :code:`[1, 2, 3, 4]`. + dropout: the dropout rate for all hidden layers + d_out: the output size + Returns: + MLP + + References: + * [gorishniy2021revisiting] Yury Gorishniy, Ivan Rubachev, Valentin Khrulkov, Artem Babenko, "Revisiting Deep Learning Models for Tabular Data", 2021 + """ + assert isinstance(dropout, float) + if len(d_layers) > 2: + assert len(set(d_layers[1:-1])) == 1, ( + 'if d_layers contains more than two elements, then' + ' all elements except for the first and the last ones must be equal.' + ) + return MLP( + d_in=d_in, + d_layers=d_layers, # type: ignore + dropouts=dropout, + activation='ReLU', + d_out=d_out, + ) + + def forward(self, x: Tensor) -> Tensor: + x = x.float() + for block in self.blocks: + x = block(x) + x = self.head(x) + return x + + +class ResNet(nn.Module): + """The ResNet model used in [gorishniy2021revisiting]. + The following scheme describes the architecture: + .. code-block:: text + ResNet: (in) -> Linear -> Block -> ... -> Block -> Head -> (out) + |-> Norm -> Linear -> Activation -> Dropout -> Linear -> Dropout ->| + | | + Block: (in) ------------------------------------------------------------> Add -> (out) + Head: (in) -> Norm -> Activation -> Linear -> (out) + Examples: + .. testcode:: + x = torch.randn(4, 2) + module = ResNet.make_baseline( + d_in=x.shape[1], + n_blocks=2, + d_main=3, + d_hidden=4, + dropout_first=0.25, + dropout_second=0.0, + d_out=1 + ) + assert module(x).shape == (len(x), 1) + References: + * [gorishniy2021revisiting] Yury Gorishniy, Ivan Rubachev, Valentin Khrulkov, Artem Babenko, "Revisiting Deep Learning Models for Tabular Data", 2021 + """ + + class Block(nn.Module): + """The main building block of `ResNet`.""" + + def __init__( + self, + *, + d_main: int, + d_hidden: int, + bias_first: bool, + bias_second: bool, + dropout_first: float, + dropout_second: float, + normalization: ModuleType, + activation: ModuleType, + skip_connection: bool, + ) -> None: + super().__init__() + self.normalization = _make_nn_module(normalization, d_main) + self.linear_first = nn.Linear(d_main, d_hidden, bias_first) + self.activation = _make_nn_module(activation) + self.dropout_first = nn.Dropout(dropout_first) + self.linear_second = nn.Linear(d_hidden, d_main, bias_second) + self.dropout_second = nn.Dropout(dropout_second) + self.skip_connection = skip_connection + + def forward(self, x: Tensor) -> Tensor: + x_input = x + x = self.normalization(x) + x = self.linear_first(x) + x = self.activation(x) + x = self.dropout_first(x) + x = self.linear_second(x) + x = self.dropout_second(x) + if self.skip_connection: + x = x_input + x + return x + + class Head(nn.Module): + """The final module of `ResNet`.""" + + def __init__( + self, + *, + d_in: int, + d_out: int, + bias: bool, + normalization: ModuleType, + activation: ModuleType, + ) -> None: + super().__init__() + self.normalization = _make_nn_module(normalization, d_in) + self.activation = _make_nn_module(activation) + self.linear = nn.Linear(d_in, d_out, bias) + + def forward(self, x: Tensor) -> Tensor: + if self.normalization is not None: + x = self.normalization(x) + x = self.activation(x) + x = self.linear(x) + return x + + def __init__( + self, + *, + d_in: int, + n_blocks: int, + d_main: int, + d_hidden: int, + dropout_first: float, + dropout_second: float, + normalization: ModuleType, + activation: ModuleType, + d_out: int, + ) -> None: + """ + Note: + `make_baseline` is the recommended constructor. + """ + super().__init__() + + self.first_layer = nn.Linear(d_in, d_main) + if d_main is None: + d_main = d_in + self.blocks = nn.Sequential( + *[ + ResNet.Block( + d_main=d_main, + d_hidden=d_hidden, + bias_first=True, + bias_second=True, + dropout_first=dropout_first, + dropout_second=dropout_second, + normalization=normalization, + activation=activation, + skip_connection=True, + ) + for _ in range(n_blocks) + ] + ) + self.head = ResNet.Head( + d_in=d_main, + d_out=d_out, + bias=True, + normalization=normalization, + activation=activation, + ) + + @classmethod + def make_baseline( + cls: Type['ResNet'], + *, + d_in: int, + n_blocks: int, + d_main: int, + d_hidden: int, + dropout_first: float, + dropout_second: float, + d_out: int, + ) -> 'ResNet': + """Create a "baseline" `ResNet`. + This variation of ResNet was used in [gorishniy2021revisiting]. Features: + * :code:`Activation` = :code:`ReLU` + * :code:`Norm` = :code:`BatchNorm1d` + Args: + d_in: the input size + n_blocks: the number of Blocks + d_main: the input size (or, equivalently, the output size) of each Block + d_hidden: the output size of the first linear layer in each Block + dropout_first: the dropout rate of the first dropout layer in each Block. + dropout_second: the dropout rate of the second dropout layer in each Block. + References: + * [gorishniy2021revisiting] Yury Gorishniy, Ivan Rubachev, Valentin Khrulkov, Artem Babenko, "Revisiting Deep Learning Models for Tabular Data", 2021 + """ + return cls( + d_in=d_in, + n_blocks=n_blocks, + d_main=d_main, + d_hidden=d_hidden, + dropout_first=dropout_first, + dropout_second=dropout_second, + normalization='BatchNorm1d', + activation='ReLU', + d_out=d_out, + ) + + def forward(self, x: Tensor) -> Tensor: + x = x.float() + x = self.first_layer(x) + x = self.blocks(x) + x = self.head(x) + return x +#### For diffusion + +class MLPDiffusion(nn.Module): + def __init__(self, d_in, num_classes, is_y_cond, rtdl_params, dim_t = 128): + super().__init__() + self.dim_t = dim_t + self.num_classes = num_classes + self.is_y_cond = is_y_cond + + # d0 = rtdl_params['d_layers'][0] + + rtdl_params['d_in'] = dim_t + rtdl_params['d_out'] = d_in + + self.mlp = MLP.make_baseline(**rtdl_params) + + if self.num_classes > 0 and is_y_cond: + self.label_emb = nn.Embedding(self.num_classes, dim_t) + elif self.num_classes == 0 and is_y_cond: + self.label_emb = nn.Linear(1, dim_t) + + self.proj = nn.Linear(d_in, dim_t) + self.time_embed = nn.Sequential( + nn.Linear(dim_t, dim_t), + nn.SiLU(), + nn.Linear(dim_t, dim_t) + ) + + def forward(self, x, timesteps, y=None): + emb = self.time_embed(timestep_embedding(timesteps, self.dim_t)) + if self.is_y_cond and y is not None: + if self.num_classes > 0: + y = y.squeeze() + else: + y = y.resize(y.size(0), 1).float() + emb += F.silu(self.label_emb(y)) + x = self.proj(x) + emb + return self.mlp(x) + +class ResNetDiffusion(nn.Module): + def __init__(self, d_in, num_classes, rtdl_params, dim_t = 256): + super().__init__() + self.dim_t = dim_t + self.num_classes = num_classes + + rtdl_params['d_in'] = d_in + rtdl_params['d_out'] = d_in + rtdl_params['emb_d'] = dim_t + self.resnet = ResNet.make_baseline(**rtdl_params) + + if self.num_classes > 0: + self.label_emb = nn.Embedding(self.num_classes, dim_t) + + self.time_embed = nn.Sequential( + nn.Linear(dim_t, dim_t), + nn.SiLU(), + nn.Linear(dim_t, dim_t) + ) + + def forward(self, x, timesteps, y=None): + emb = self.time_embed(timestep_embedding(timesteps, self.dim_t)) + if y is not None and self.num_classes > 0: + emb += self.label_emb(y.squeeze()) + return self.resnet(x, emb) diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/utils.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6376bfbfb6971c3e465fafe9d56320d92a5f508a --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/utils.py @@ -0,0 +1,174 @@ +import torch +import numpy as np +import torch.nn.functional as F +from torch.profiler import record_function +from inspect import isfunction + +def normal_kl(mean1, logvar1, mean2, logvar2): + """ + Compute the KL divergence between two gaussians. + + Shapes are automatically broadcasted, so batches can be compared to + scalars, among other use cases. + """ + tensor = None + for obj in (mean1, logvar1, mean2, logvar2): + if isinstance(obj, torch.Tensor): + tensor = obj + break + assert tensor is not None, "at least one argument must be a Tensor" + + # Force variances to be Tensors. Broadcasting helps convert scalars to + # Tensors, but it does not work for torch.exp(). + logvar1, logvar2 = [ + x if isinstance(x, torch.Tensor) else torch.tensor(x).to(tensor) + for x in (logvar1, logvar2) + ] + + return 0.5 * ( + -1.0 + + logvar2 + - logvar1 + + torch.exp(logvar1 - logvar2) + + ((mean1 - mean2) ** 2) * torch.exp(-logvar2) + ) + +def approx_standard_normal_cdf(x): + """ + A fast approximation of the cumulative distribution function of the + standard normal. + """ + return 0.5 * (1.0 + torch.tanh(np.sqrt(2.0 / np.pi) * (x + 0.044715 * torch.pow(x, 3)))) + + +def discretized_gaussian_log_likelihood(x, *, means, log_scales): + """ + Compute the log-likelihood of a Gaussian distribution discretizing to a + given image. + + :param x: the target images. It is assumed that this was uint8 values, + rescaled to the range [-1, 1]. + :param means: the Gaussian mean Tensor. + :param log_scales: the Gaussian log stddev Tensor. + :return: a tensor like x of log probabilities (in nats). + """ + assert x.shape == means.shape == log_scales.shape + centered_x = x - means + inv_stdv = torch.exp(-log_scales) + plus_in = inv_stdv * (centered_x + 1.0 / 255.0) + cdf_plus = approx_standard_normal_cdf(plus_in) + min_in = inv_stdv * (centered_x - 1.0 / 255.0) + cdf_min = approx_standard_normal_cdf(min_in) + log_cdf_plus = torch.log(cdf_plus.clamp(min=1e-12)) + log_one_minus_cdf_min = torch.log((1.0 - cdf_min).clamp(min=1e-12)) + cdf_delta = cdf_plus - cdf_min + log_probs = torch.where( + x < -0.999, + log_cdf_plus, + torch.where(x > 0.999, log_one_minus_cdf_min, torch.log(cdf_delta.clamp(min=1e-12))), + ) + assert log_probs.shape == x.shape + return log_probs + +def sum_except_batch(x, num_dims=1): + ''' + Sums all dimensions except the first. + + Args: + x: Tensor, shape (batch_size, ...) + num_dims: int, number of batch dims (default=1) + + Returns: + x_sum: Tensor, shape (batch_size,) + ''' + return x.reshape(*x.shape[:num_dims], -1).sum(-1) + +def mean_flat(tensor): + """ + Take the mean over all non-batch dimensions. + """ + return tensor.mean(dim=list(range(1, len(tensor.shape)))) + +def ohe_to_categories(ohe, K): + K = torch.from_numpy(K) + indices = torch.cat([torch.zeros((1,)), K.cumsum(dim=0)], dim=0).int().tolist() + res = [] + for i in range(len(indices) - 1): + res.append(ohe[:, indices[i]:indices[i+1]].argmax(dim=1)) + return torch.stack(res, dim=1) + +def log_1_min_a(a): + return torch.log(1 - a.exp() + 1e-40) + + +def log_add_exp(a, b): + maximum = torch.max(a, b) + return maximum + torch.log(torch.exp(a - maximum) + torch.exp(b - maximum)) + +def exists(x): + return x is not None + +def extract(a, t, x_shape): + b, *_ = t.shape + t = t.to(a.device) + out = a.gather(-1, t) + while len(out.shape) < len(x_shape): + out = out[..., None] + return out.expand(x_shape) + +def default(val, d): + if exists(val): + return val + return d() if isfunction(d) else d + +def log_categorical(log_x_start, log_prob): + return (log_x_start.exp() * log_prob).sum(dim=1) + +def index_to_log_onehot(x, num_classes): + onehots = [] + for i in range(len(num_classes)): + onehots.append(F.one_hot(x[:, i], num_classes[i])) + + x_onehot = torch.cat(onehots, dim=1) + log_onehot = torch.log(x_onehot.float().clamp(min=1e-30)) + return log_onehot + +def log_sum_exp_by_classes(x, slices): + device = x.device + res = torch.zeros_like(x) + for ixs in slices: + res[:, ixs] = torch.logsumexp(x[:, ixs], dim=1, keepdim=True) + + assert x.size() == res.size() + + return res + +@torch.jit.script +def log_sub_exp(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: + m = torch.maximum(a, b) + return torch.log(torch.exp(a - m) - torch.exp(b - m)) + m + +@torch.jit.script +def sliced_logsumexp(x, slices): + lse = torch.logcumsumexp( + torch.nn.functional.pad(x, [1, 0, 0, 0], value=-float('inf')), + dim=-1) + + slice_starts = slices[:-1] + slice_ends = slices[1:] + + slice_lse = log_sub_exp(lse[:, slice_ends], lse[:, slice_starts]) + slice_lse_repeated = torch.repeat_interleave( + slice_lse, + slice_ends - slice_starts, + dim=-1 + ) + return slice_lse_repeated + +def log_onehot_to_index(log_x): + return log_x.argmax(1) + +class FoundNANsError(BaseException): + """Found NANs during sampling""" + def __init__(self, message='Found NANs during sampling.'): + super(FoundNANsError, self).__init__(message) \ No newline at end of file diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tools/convert_synth_to_csv.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tools/convert_synth_to_csv.py new file mode 100644 index 0000000000000000000000000000000000000000..be1bb6180758714a938e9c5c73a51029523e20f0 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tools/convert_synth_to_csv.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +""" +Convert generated synthetic data from npy files to CSV format. +""" +import os +import sys +import numpy as np +import pandas as pd +import argparse + +def convert_to_csv(parent_dir, output_path=None): + """ + Convert generated synthetic data to CSV. + + Args: + parent_dir: Directory containing X_num_train.npy, X_cat_train.npy, y_train.npy + output_path: Output CSV file path (default: parent_dir/synth_train.csv) + """ + parent_dir = os.path.abspath(parent_dir) + + # Load npy files + x_num_path = os.path.join(parent_dir, 'X_num_train.npy') + x_cat_path = os.path.join(parent_dir, 'X_cat_train.npy') + y_path = os.path.join(parent_dir, 'y_train.npy') + + data_parts = [] + column_names = [] + + # Load numerical features + if os.path.exists(x_num_path): + X_num = np.load(x_num_path, allow_pickle=True) + print(f"Loaded X_num: shape {X_num.shape}") + data_parts.append(X_num) + # Create column names for numerical features + for i in range(X_num.shape[1]): + column_names.append(f'num_{i}') + + # Load categorical features + if os.path.exists(x_cat_path): + X_cat = np.load(x_cat_path, allow_pickle=True) + print(f"Loaded X_cat: shape {X_cat.shape}") + data_parts.append(X_cat) + # Create column names for categorical features + for i in range(X_cat.shape[1]): + column_names.append(f'cat_{i}') + + # Load target + if os.path.exists(y_path): + y = np.load(y_path, allow_pickle=True) + print(f"Loaded y: shape {y.shape}") + # Reshape if needed + if y.ndim == 1: + y = y.reshape(-1, 1) + data_parts.append(y) + column_names.append('y') + + if not data_parts: + raise ValueError(f"No data files found in {parent_dir}") + + # Concatenate all parts + data = np.hstack(data_parts) + print(f"Combined data shape: {data.shape}") + print(f"Number of columns: {len(column_names)}") + + # Create DataFrame + df = pd.DataFrame(data, columns=column_names) + + # Determine output path + if output_path is None: + output_path = os.path.join(parent_dir, 'synth_train.csv') + + # Save to CSV + df.to_csv(output_path, index=False) + print(f"[OK] Saved synthetic data to: {output_path}") + print(f"[OK] Total samples: {len(df)}, Total columns: {len(df.columns)}") + + # Print summary statistics + print("\n=== Data Summary ===") + print(df.describe()) + + return output_path + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='Convert synthetic npy files to CSV') + parser.add_argument('parent_dir', type=str, help='Directory containing generated npy files') + parser.add_argument('--output', '-o', type=str, default=None, help='Output CSV file path (default: parent_dir/synth_train.csv)') + + args = parser.parse_args() + convert_to_csv(args.parent_dir, args.output) diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tools/make_tabddpm_info.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tools/make_tabddpm_info.py new file mode 100644 index 0000000000000000000000000000000000000000..30acf64d04521bfa8fc1810c893395eed5bd57a4 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tools/make_tabddpm_info.py @@ -0,0 +1,97 @@ +import os, json +import numpy as np + +def load(path): + return np.load(path, allow_pickle=True) + +def main(data_dir: str): + # required files + req = [ + "X_num_train.npy","X_num_val.npy","X_num_test.npy", + "X_cat_train.npy","X_cat_val.npy","X_cat_test.npy", + "y_train.npy","y_val.npy","y_test.npy" + ] + for f in req: + p = os.path.join(data_dir, f) + if not os.path.exists(p): + raise FileNotFoundError(p) + + Xn_tr = load(os.path.join(data_dir,"X_num_train.npy")) + Xc_tr = load(os.path.join(data_dir,"X_cat_train.npy")) + y_tr = load(os.path.join(data_dir,"y_train.npy")) + + # basic dims + n_num = 0 if Xn_tr.ndim < 2 else int(Xn_tr.shape[1]) + n_cat = 0 if Xc_tr.ndim < 2 else int(Xc_tr.shape[1]) + + # infer task / y info + y_flat = y_tr.reshape(-1) + uniq = np.unique(y_flat) + # if y is integer and has few unique values, could be classification + is_int = np.issubdtype(y_flat.dtype, np.integer) + num_classes = int(len(uniq)) if is_int else 0 + + # determine task_type + if is_int and num_classes == 2: + task_type = "binclass" + elif is_int and num_classes > 2 and num_classes <= 100: + task_type = "multiclass" + else: + task_type = "regression" + + # cat sizes (per categorical column) + cat_sizes = [] + if n_cat > 0: + # compute max+1 per column (assume categories encoded 0..K-1) + for j in range(n_cat): + col = Xc_tr[:, j].reshape(-1) + if col.size == 0: + cat_sizes.append(0) + else: + mx = int(np.max(col)) + cat_sizes.append(mx + 1) + + # numeric stats (optional but useful) + num_stats = {} + if n_num > 0: + # mean/std/min/max over train numeric + num_stats = { + "mean": np.mean(Xn_tr, axis=0).tolist(), + "std": (np.std(Xn_tr, axis=0) + 1e-12).tolist(), + "min": np.min(Xn_tr, axis=0).tolist(), + "max": np.max(Xn_tr, axis=0).tolist(), + } + + # This repo expects info.json. Keep fields simple & robust. + info = { + "task_type": task_type, + "n_num_features": n_num, + "n_cat_features": n_cat, + "cat_sizes": cat_sizes, + "y_dtype": str(y_flat.dtype), + "y_unique_count": int(len(uniq)), + "y_unique_head": uniq[:20].tolist(), + # heuristics: user can override in config.toml + "is_classification_like": bool(is_int and len(uniq) <= 100), + "num_classes_like": num_classes, + } + + # write files + with open(os.path.join(data_dir, "info.json"), "w", encoding="utf-8") as f: + json.dump(info, f, ensure_ascii=False, indent=2) + + # some codepaths may look for these (harmless if unused) + with open(os.path.join(data_dir, "cat_sizes.json"), "w", encoding="utf-8") as f: + json.dump({"cat_sizes": cat_sizes}, f, ensure_ascii=False, indent=2) + + with open(os.path.join(data_dir, "num_stats.json"), "w", encoding="utf-8") as f: + json.dump(num_stats, f, ensure_ascii=False, indent=2) + + print("[OK] wrote:", os.path.join(data_dir,"info.json")) + print("[OK] n_num =", n_num, "n_cat =", n_cat, "cat_sizes =", cat_sizes) + print("[OK] y unique count =", len(uniq), "head =", uniq[:20]) + +if __name__ == "__main__": + data_dir = "data/Tab-Cate-1" + main(data_dir) + diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/abalone_cv.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/abalone_cv.json new file mode 100644 index 0000000000000000000000000000000000000000..7641bbf14b10338ac870e2a999866a64a3e119fa --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/abalone_cv.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aad08aabbf726ab65389e42c3a524f407e6bc791edcb5af304c31ba9037f6c10 +size 351 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/adult_cv.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/adult_cv.json new file mode 100644 index 0000000000000000000000000000000000000000..51f7cdde4deeb5adf383c063ca60fe69af2092a1 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/adult_cv.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:956a488f34e502db9975d86ef25b75cf5c01c08a3e5a47c7ade4f72cbf11374c +size 432 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/buddy_cv.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/buddy_cv.json new file mode 100644 index 0000000000000000000000000000000000000000..bc1fcb92e6fb025976224ef2fbf1335d1b1518a1 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/buddy_cv.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d4577f6d2af34360bff6faf7a01af5501463e8b13ff0fc0c18bf2bfa67c6c63b +size 393 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/california_cv.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/california_cv.json new file mode 100644 index 0000000000000000000000000000000000000000..19e1861532e4b5e50495f5444496fb558f45e875 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/california_cv.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0508cdc40c02386321976c9537fbe54a5f2b0fa0e8e7dde72a6d4d289ced862c +size 335 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/cardio_cv.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/cardio_cv.json new file mode 100644 index 0000000000000000000000000000000000000000..7fc8cd71e630bcadef6c582f458d3e328dfc7024 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/cardio_cv.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a411285e39c4cb685233ec73375cfd023fb834897dd6b5a8f99cf7a7ec1c6656 +size 403 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/churn2_cv.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/churn2_cv.json new file mode 100644 index 0000000000000000000000000000000000000000..d646aac53ef0d8ad9f508fb14f561739d52441a9 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/churn2_cv.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e4dea09bdea9006ce44f71eef0e1740f639eceff44dd021c351ece84a428a00a +size 380 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/default_cv.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/default_cv.json new file mode 100644 index 0000000000000000000000000000000000000000..53328b6729355daaba91f378caca2944b08dfb82 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/default_cv.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fb7ad47bb5b1c9fbe54cf14cc854581b22ed72f9dbc47f0a022e48fa572b5ffc +size 372 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/diabetes_cv.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/diabetes_cv.json new file mode 100644 index 0000000000000000000000000000000000000000..91aa99b5999ba8561744b73f036584956aa27735 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/diabetes_cv.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0d1265117a3d8688b7878c62656b6d85bb543e723b1f5f01a2ed5bd4b12878dc +size 335 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/fb-comments_cv.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/fb-comments_cv.json new file mode 100644 index 0000000000000000000000000000000000000000..8b118aadedc57bcea9ed8af0ac0318b17bd3850d --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/fb-comments_cv.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:18ccbc230cd0959834d3155e67c29d259af90720d29bc4284b3209df5374886e +size 519 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/gesture_cv.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/gesture_cv.json new file mode 100644 index 0000000000000000000000000000000000000000..39add46e4bb47ed0bb1e451e680788465aefa231 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/gesture_cv.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:efa67605a7699adf3cd46bb7d7d5512516ab3e5da3e01451004aadf9ee4f9d62 +size 333 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/higgs-small_cv.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/higgs-small_cv.json new file mode 100644 index 0000000000000000000000000000000000000000..6d0379ccd1631f30b7983ee0ed809a88c422aed2 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/higgs-small_cv.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d4c67d2f9937dc5548b3c3a1ae71846e5fccc66853b8067670b979ff2a4f0201 +size 334 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/house_cv.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/house_cv.json new file mode 100644 index 0000000000000000000000000000000000000000..9d636369299b13991976af26b6337be2c6c88494 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/house_cv.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:852eea0c2f88f7032cebc5dc7c9422be385d231f1ce8b5c9364a534d64fdf4f3 +size 332 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/insurance_cv.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/insurance_cv.json new file mode 100644 index 0000000000000000000000000000000000000000..0951c97fd762261760bf64abeee35635ac8b3277 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/insurance_cv.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2201078a643eb78c649a3d4a9e897ecf39c2d7f35c5a9fdb055c91251694b808 +size 369 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/king_cv.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/king_cv.json new file mode 100644 index 0000000000000000000000000000000000000000..b95d7e8aecc468014085b8c0959aa9e7be64812c --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/king_cv.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a94473811e28035ef4781122c3da6e4f81b232b68a0042b64c30a1df648e02d3 +size 374 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/miniboone_cv.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/miniboone_cv.json new file mode 100644 index 0000000000000000000000000000000000000000..19ec2cc100638b21b99c87f453a4d6d356803ecb --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/miniboone_cv.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:14dcf192aa15f491f147b30e2312b55889a146c546d72d89ee2d07ff26cc2103 +size 334 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/wilt_cv.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/wilt_cv.json new file mode 100644 index 0000000000000000000000000000000000000000..ea8143610c6a60053cbac687cb32b2c7b203ebc7 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/catboost/wilt_cv.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4f6989397bf0029ee07b2ca9ab9335645ea3402bd6b782f2cec4cb40ad70b2ed +size 334 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/abalone_cv.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/abalone_cv.json new file mode 100644 index 0000000000000000000000000000000000000000..f497e044f1e3a1ffd35f852d285ab43b841e7fc2 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/abalone_cv.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f99f28009311b8bb5413fbdbf72af25d1d384eec3c079c156e6a6eafa93e46bb +size 157 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/adult_cv.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/adult_cv.json new file mode 100644 index 0000000000000000000000000000000000000000..db818565ea71189907985b9a9424a41dec1b5261 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/adult_cv.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1d4d4e1b062e420ce1838117b872e1794a632ea7f1dd8220eb640b71f793cd3a +size 229 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/buddy_cv.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/buddy_cv.json new file mode 100644 index 0000000000000000000000000000000000000000..d12f3fe28d7b352a4bb737f24abf65feb094b39a --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/buddy_cv.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bfe610df17eb46233b0dbba7fb71ea6117e9992763ae8ccd789159c296f3cc43 +size 165 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/california_cv.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/california_cv.json new file mode 100644 index 0000000000000000000000000000000000000000..cb7256f2b264df6ee73bb260e84d4cafd983c2ad --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/california_cv.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b9970d5c42859dce6fded5b3fb285bba98181076d8db75b8ef78e5e0167c7b0c +size 163 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/cardio_cv.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/cardio_cv.json new file mode 100644 index 0000000000000000000000000000000000000000..cfa75fad250058c3798cb53873aaef3e60289b3e --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/cardio_cv.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bc9642d070f056675cd4d004c0b446576eb162e2819dec052325fe7da59ce85d +size 148 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/churn2_cv.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/churn2_cv.json new file mode 100644 index 0000000000000000000000000000000000000000..3e15732f32083afa27c5290d88430aab1fadf294 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/churn2_cv.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ebea18b44a2d33a6643f283adf68961099d44d7e4f11e29148b501ddabb5894a +size 152 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/default_cv.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/default_cv.json new file mode 100644 index 0000000000000000000000000000000000000000..45eb9feca3f3f48f560a1c136037e0e83e9acda7 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/default_cv.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2d6082a82af0fb59906d778c57e4229eeff861066c1e24bea9c5e721f804214c +size 201 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/diabetes_cv.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/diabetes_cv.json new file mode 100644 index 0000000000000000000000000000000000000000..69cfdc546559ac76088c0ce9e2abea88323bcd09 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/diabetes_cv.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:243a914fe90215cab4867d415cb82078366b5d2472264c91ea46d3e0e3291534 +size 147 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/gesture_cv.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/gesture_cv.json new file mode 100644 index 0000000000000000000000000000000000000000..27781e4df360af0c233babc28485990447ee59e8 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/gesture_cv.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a3a819ad5093581e1b94eeddb0655b99cccce3bb121f405b0b7e3b230c3c1a11 +size 190 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/higgs-small_cv.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/higgs-small_cv.json new file mode 100644 index 0000000000000000000000000000000000000000..826c0e4d0b890d21ac21a2b6b9015d2e80b88b1f --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/higgs-small_cv.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3520fe130d4570aa07a79031b6016f31a4f36cd5fdc9ff7167f0c7e1768a6697 +size 230 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/house_cv.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/house_cv.json new file mode 100644 index 0000000000000000000000000000000000000000..5f13b453f1c8978346138fbfae950bc48f8f419a --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/house_cv.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:22f1903d9a59e6cc1df1a643b9bc216392fbb3549cb6555482898d4a7ac936aa +size 164 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/insurance_cv.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/insurance_cv.json new file mode 100644 index 0000000000000000000000000000000000000000..00d8f78622f81428c7c94021982ae59c8890fa84 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/insurance_cv.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:381e76611b072a0fb5fa41a7c640740453293a6d0cda8210697d4b9833d715e4 +size 171 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/king_cv.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/king_cv.json new file mode 100644 index 0000000000000000000000000000000000000000..7c7fcaf8ef05cdad5022fb1430047318c48d2107 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/king_cv.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:afbbb1a2be60833c9468ded47ba78228e5a00c42bed93681e4e2aa0c6b68278d +size 163 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/miniboone_cv.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/miniboone_cv.json new file mode 100644 index 0000000000000000000000000000000000000000..6a2fa20fe823c8adf1023a889e918326997a7b8a --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tuned_models/mlp/miniboone_cv.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:896a60d6ce4628cacdf5a3ec5a4c70b9fcff7944e373082ca34a6b55d7c6871a +size 175