diff --git a/.gitattributes b/.gitattributes index 6def207dd70293529d97001506c23df76393ad43..6102cad38a961f4047a35e743ebfd268e3064650 100644 --- a/.gitattributes +++ b/.gitattributes @@ -2879,3 +2879,45 @@ SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabd SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/ckpt/pipeline_c19/adapter_learnable/ema_model_200.pt filter=lfs diff=lfs merge=lfs -text SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/ckpt/pipeline_c19/adapter_learnable/model_200.pt filter=lfs diff=lfs merge=lfs -text SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/configs/tabdiff_configs.toml filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/all_results.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/ema/all_results.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/ema/samples.csv filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/ema/shapes.csv filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/ema/trends.csv filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/samples.csv filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/shapes.csv filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/trends.csv filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/gen_20260512_235639.log filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/input_snapshot.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/models_tabdiff/trained.pt filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/public_gate/normalized_schema_snapshot.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/public_gate/public_gate_report.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/public_gate/staged_input_manifest.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/run_config.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/runtime_result.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/staged/public/staged_features.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/staged/public/test.csv filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/staged/public/train.csv filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/staged/public/val.csv filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/staged/tabdiff/adapter_report.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/staged/tabdiff/adapter_transforms_applied.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/staged/tabdiff/model_input_manifest.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabdiff-c19-32759-20260512_235639.csv filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabdiff_train_meta.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/X_cat_test.npy filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/X_cat_train.npy filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/X_cat_val.npy filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/X_num_test.npy filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/X_num_train.npy filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/X_num_val.npy filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/info.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/real.csv filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/staged_features.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/test.csv filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/train.csv filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/val.csv filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/y_test.npy filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/y_train.npy filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/y_val.npy filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/train_20260512_231308.log filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c19/tabpfgen/tabpfgen-c19-20260422_200215/gen_20260422_200228.log filter=lfs diff=lfs merge=lfs -text diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/models/noise_schedule.py b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/models/noise_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..0fc02778162edbf35ef9574aad67483c9e6a7cf1 --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/models/noise_schedule.py @@ -0,0 +1,157 @@ +import abc + +import torch +import torch.nn as nn + + +class Noise(abc.ABC, nn.Module): + """ + Baseline forward method to get the total + rate of noise at a timestep + """ + def forward(self, t): + # Assume time goes from 0 to 1 + return self.total_noise(t), self.rate_noise(t) + + @abc.abstractmethod + def total_noise(self, t): + """ + Total noise ie \int_0^t g(t) dt + g(0) + """ + pass + + +class LogLinearNoise(Noise): + """Log Linear noise schedule. + + """ + def __init__(self, eps_max=1e-3, eps_min=1e-5, **kwargs): + super().__init__() + self.eps_max = eps_max + self.eps_min = eps_min + self.sigma_max = self.total_noise(torch.tensor(1.0)) + self.sigma_min = self.total_noise(torch.tensor(0.0)) + + def k(self): + return torch.tensor(1) + + def rate_noise(self, t): + return (1 - self.eps_max - self.eps_min) / (1 - ((1 - self.eps_max - self.eps_min) * t + self.eps_min)) + + def total_noise(self, t): + """ + sigma_min=-log(1-eps_min), when t=0 + sigma_max=-log(eps_max), when t=1 + """ + return -torch.log1p(-((1 - self.eps_max - self.eps_min) * t + self.eps_min)) + +class PowerMeanNoise(Noise): + """The noise schedule using the power mean interpolation function. + + This is the schedule used in EDM + """ + def __init__(self, sigma_min=0.002, sigma_max=80, rho=7, **kwargs): + super().__init__() + self.sigma_min = sigma_min + self.sigma_max = sigma_max + self.raw_rho = rho + + def rho(self): + # Return the softplus-transformed rho for all num_numerical values + return torch.tensor(self.raw_rho) + + def total_noise(self, t): + sigma = (self.sigma_min ** (1/self.rho()) + t * ( + self.sigma_max ** (1/self.rho()) - self.sigma_min ** (1/self.rho()))).pow(self.rho()) + return sigma + + def inverse_to_t(self, sigma): + t = (sigma.pow(1/self.rho()) - self.sigma_min ** (1/self.rho())) / (self.sigma_max ** (1/self.rho()) - self.sigma_min ** (1/self.rho())) + return t + + +class PowerMeanNoise_PerColumn(nn.Module): + + def __init__(self, num_numerical, sigma_min=0.002, sigma_max=80, rho_init=1, rho_offset=2, **kwargs): + super().__init__() + self.sigma_min = sigma_min + self.sigma_max = sigma_max + self.num_numerical = num_numerical + self.rho_offset = rho_offset + self.rho_raw = nn.Parameter(torch.tensor([rho_init] * self.num_numerical, dtype=torch.float32)) + + def rho(self): + # Return the softplus-transformed rho for all num_numerical values + return nn.functional.softplus(self.rho_raw) + self.rho_offset + + def total_noise(self, t): + """ + Compute total noise for each t in the batch for all num_numerical rhos. + t: [batch_size] + Returns: [batch_size, num_numerical] + """ + batch_size = t.size(0) + + rho = self.rho() + + sigma_min_pow = self.sigma_min ** (1 / rho) # Shape: [num_numerical] + sigma_max_pow = self.sigma_max ** (1 / rho) # Shape: [num_numerical] + + sigma = (sigma_min_pow + t * (sigma_max_pow - sigma_min_pow)).pow(rho) # Shape: [batch_size, num_numerical] + + return sigma + + def rate_noise(self, t): + return None + + def inverse_to_t(self, sigma): + """ + Inverse function to map sigma back to t, with proper broadcasting support. + sigma: [batch_size, num_numerical] or [batch_size, 1] + Returns: t: [batch_size, num_numerical] + """ + rho = self.rho() + + sigma_min_pow = self.sigma_min ** (1 / rho) # Shape: [num_numerical] + sigma_max_pow = self.sigma_max ** (1 / rho) # Shape: [num_numerical] + + # To enable broadcasting between sigma and the per-column rho values, expand rho where needed. + t = (sigma.pow(1 / rho) - sigma_min_pow) / (sigma_max_pow - sigma_min_pow) + + return t + + +class LogLinearNoise_PerColumn(nn.Module): + + def __init__(self, num_categories, eps_max=1e-3, eps_min=1e-5, k_init=-6, k_offset=1, **kwargs): + + super().__init__() + self.eps_max = eps_max + self.eps_min = eps_min + # Use softplus to ensure k is positive + self.num_categories = num_categories + self.k_offset = k_offset + self.k_raw = nn.Parameter(torch.tensor([k_init] * self.num_categories, dtype=torch.float32)) + + def k(self): + return torch.nn.functional.softplus(self.k_raw) + self.k_offset + + def rate_noise(self, t, noise_fn=None): + """ + Compute rate noise for all categories with broadcasting. + t: [batch_size] + Returns: [batch_size, num_categories] + """ + k = self.k() # Shape: [num_categories] + + numerator = (1 - self.eps_max - self.eps_min) * k * t.pow(k - 1) + denominator = 1 - ((1 - self.eps_max - self.eps_min) * t.pow(k) + self.eps_min) + rate = numerator / denominator # Shape: [batch_size, num_categories] + + return rate + + def total_noise(self, t, noise_fn=None): + k = self.k() # Shape: [num_categories] + + total_noise = -torch.log1p(-((1 - self.eps_max - self.eps_min) * t.pow(k) + self.eps_min)) + + return total_noise diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/models/unified_ctime_diffusion.py b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/models/unified_ctime_diffusion.py new file mode 100644 index 0000000000000000000000000000000000000000..599463b6cdf2528c5f35ebd5ddc5c511e5f34d8f --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/models/unified_ctime_diffusion.py @@ -0,0 +1,597 @@ +import torch.nn.functional as F +import torch +import math +import numpy as np +from tabdiff.models.noise_schedule import * +from tqdm import tqdm +from itertools import chain + +""" +“Our implementation of the continuous-time masked diffusion is inspired by https://arxiv.org/abs/2406.07524's implementation at [https://github.com/kuleshov-group/mdlm], with modifications to support data distributions that include categorical dimensions of different sizes.” +""" + +S_churn= 1 +S_min=0 +S_max=float('inf') +S_noise=1 + +class UnifiedCtimeDiffusion(torch.nn.Module): + def __init__( + self, + num_classes: np.array, + num_numerical_features: int, + denoise_fn, + y_only_model, + num_timesteps=1000, + scheduler='power_mean', + cat_scheduler='log_linear', + noise_dist='uniform', + edm_params={}, + noise_dist_params={}, + noise_schedule_params={}, + sampler_params={}, + device=torch.device('cpu'), + **kwargs + ): + + super(UnifiedCtimeDiffusion, self).__init__() + + self.num_numerical_features = num_numerical_features + self.num_classes = num_classes # it as a vector [K1, K2, ..., Km] + self.num_classes_expanded = torch.from_numpy( + np.concatenate([num_classes[i].repeat(num_classes[i]) for i in range(len(num_classes))]) + ).to(device) if len(num_classes)>0 else torch.tensor([]).to(device).int() + self.mask_index = torch.tensor(self.num_classes).long().to(device) + self.neg_infinity = -1000000.0 + self.num_classes_w_mask = tuple(self.num_classes + 1) + + offsets = np.cumsum(self.num_classes) + offsets = np.append([0], offsets) + self.slices_for_classes = [] + for i in range(1, len(offsets)): + self.slices_for_classes.append(np.arange(offsets[i - 1], offsets[i])) + self.offsets = torch.from_numpy(offsets).to(device) + + offsets = np.cumsum(self.num_classes) + np.arange(1, len(self.num_classes)+1) + offsets = np.append([0], offsets) + self.slices_for_classes_with_mask = [] + for i in range(1, len(offsets)): + self.slices_for_classes_with_mask.append(np.arange(offsets[i - 1], offsets[i])) + + self._denoise_fn = denoise_fn + self.y_only_model = y_only_model + self.num_timesteps = num_timesteps + self.scheduler = scheduler + self.cat_scheduler = cat_scheduler + self.noise_dist = noise_dist + self.edm_params = edm_params + self.noise_dist_params = noise_dist_params + self.sampler_params = sampler_params + if self.num_numerical_features == 0: + self.sampler_params['stochastic_sampler'] = False + self.sampler_params['second_order_correction'] = False + + self.w_num = 0.0 + self.w_cat = 0.0 + self.num_mask_idx = [] + self.cat_mask_idx = [] + + self.device = device + + if self.scheduler == 'power_mean': + self.num_schedule = PowerMeanNoise(**noise_schedule_params) + elif self.scheduler == 'power_mean_per_column': + self.num_schedule = PowerMeanNoise_PerColumn(num_numerical = num_numerical_features, **noise_schedule_params) + else: + raise NotImplementedError(f"The noise schedule--{self.scheduler}-- is not implemented for contiuous data at CTIME ") + + if self.cat_scheduler == 'log_linear': + self.cat_schedule = LogLinearNoise(**noise_schedule_params) + elif self.cat_scheduler == 'log_linear_per_column': + self.cat_schedule = LogLinearNoise_PerColumn(num_categories = len(num_classes), **noise_schedule_params) + else: + raise NotImplementedError(f"The noise schedule--{self.cat_scheduler}-- is not implemented for discrete data at CTIME ") + + def mixed_loss(self, x): + b = x.shape[0] + device = x.device + + x_num = x[:, :self.num_numerical_features] + x_cat = x[:, self.num_numerical_features:].long() + # Sample noise level + if self.noise_dist == "uniform_t": + t = torch.rand(b, device=device, dtype=x_num.dtype) + t = t[:, None] + sigma_num = self.num_schedule.total_noise(t) + sigma_cat = self.cat_schedule.total_noise(t) + dsigma_cat = self.cat_schedule.rate_noise(t) + else: + sigma_num = self.sample_ctime_noise(x) + t = self.num_schedule.inverse_to_t(sigma_num) + while torch.any((t < 0) + (t > 1)): + # restrict t to [0,1] + # this iterative approach is equivalent to sampling from a truncated version of the orignal noise distribution + invalid_idx = ((t < 0) + (t > 1)).nonzero().squeeze(-1) + sigma_num[invalid_idx] = self.sample_ctime_noise(x[:len(invalid_idx)]) + t = self.num_schedule.inverse_to_t(sigma_num) + assert not torch.any((t < 0) + (t > 1)) + sigma_cat = self.cat_schedule.total_noise(t) + # Convert sigma_cat to the corresponding alpha and move_chance + alpha = torch.exp(-sigma_cat) + move_chance = -torch.expm1(-sigma_cat) # torch.expm1 gives better numertical stability + + # Continuous forward diff + x_num_t = x_num + if x_num.shape[1] > 0: + noise = torch.randn_like(x_num) + x_num_t = x_num + noise * sigma_num + + # Discrete forward diff + x_cat_t = x_cat + x_cat_t_soft = x_cat # in the case where x_cat is empty, x_cat_t_soft will have the same shape as x_cat + if x_cat.shape[1] > 0: + is_learnable = self.cat_scheduler == 'log_linear_per_column' + strategy = 'soft'if is_learnable else 'hard' + x_cat_t, x_cat_t_soft = self.q_xt(x_cat, move_chance, strategy=strategy) + + # Predict orignal data (distribution) + model_out_num, model_out_cat = self._denoise_fn( + x_num_t, x_cat_t_soft, + t.squeeze(), sigma=sigma_num + ) + + d_loss = torch.zeros((1,)).float() + c_loss = torch.zeros((1,)).float() + + if x_num.shape[1] > 0: + c_loss = self._edm_loss(model_out_num, x_num, sigma_num) + if x_cat.shape[1] > 0: + logits = self._subs_parameterization(model_out_cat, x_cat_t) # log normalized probabilities, with the entry mask category being set to -inf + d_loss = self._absorbed_closs(logits, x_cat, sigma_cat, dsigma_cat) + + return d_loss.mean(), c_loss.mean() + + @torch.no_grad() + def sample(self, num_samples): + b = num_samples + device = self.device + dtype = torch.float32 + + # Create the chain of t + t = torch.linspace(0,1,self.num_timesteps, dtype=dtype, device=device) # times = 0.0,...,1.0 + t = t[:, None] + + # Compute the chains of sigma + sigma_num_cur = self.num_schedule.total_noise(t) + sigma_cat_cur = self.cat_schedule.total_noise(t) + sigma_num_next = torch.zeros_like(sigma_num_cur) + sigma_num_next[1:] = sigma_num_cur[0:-1] + sigma_cat_next = torch.zeros_like(sigma_cat_cur) + sigma_cat_next[1:] = sigma_cat_cur[0:-1] + + # Prepare sigma_hat for stochastic sampling mode + if self.sampler_params['stochastic_sampler']: + gamma = min(S_churn / self.num_timesteps, np.sqrt(2) - 1) * (S_min <= sigma_num_cur) * (sigma_num_cur <= S_max) + sigma_num_hat = sigma_num_cur + gamma * sigma_num_cur + t_hat = self.num_schedule.inverse_to_t(sigma_num_hat) + t_hat = torch.min(t_hat, dim=-1, keepdim=True).values # take the samllest t_hat induced by sigma_num + zero_gamma = (gamma==0).any() + t_hat[zero_gamma] = t[zero_gamma] + out_of_bound = (t_hat > 1).squeeze() + sigma_num_hat[out_of_bound] = sigma_num_cur[out_of_bound] + t_hat[out_of_bound] = t[out_of_bound] + sigma_cat_hat = self.cat_schedule.total_noise(t_hat) + else: + t_hat = t + sigma_num_hat = sigma_num_cur + sigma_cat_hat = sigma_cat_cur + + # Sample priors for the continuous dimensions + z_norm = torch.randn((b, self.num_numerical_features), device=device) * sigma_num_cur[-1] + + # Sample priors for the discrete dimensions + has_cat = len(self.num_classes) > 0 + z_cat = torch.zeros((b, 0), device=device).float() # the default values for categorical sample if the dataset has no categorical entry + if has_cat: + z_cat = self._sample_masked_prior( + b, + len(self.num_classes), + ) + + pbar = tqdm(reversed(range(0, self.num_timesteps)), total=self.num_timesteps) + pbar.set_description(f"Sampling Progress") + for i in pbar: + z_norm, z_cat, q_xs = self.edm_update( + z_norm, z_cat, i, + t[i], t[i-1] if i > 0 else None, t_hat[i], + sigma_num_cur[i], sigma_num_next[i], sigma_num_hat[i], + sigma_cat_cur[i], sigma_cat_next[i], sigma_cat_hat[i], + ) + + assert torch.all(z_cat < self.mask_index) + sample = torch.cat([z_norm, z_cat], dim=1).cpu() + return sample + + def sample_all(self, num_samples, batch_size, keep_nan_samples=False): + b = batch_size + + all_samples = [] + num_generated = 0 + while num_generated < num_samples: + print(f"Samples left to generate: {num_samples-num_generated}") + sample = self.sample(b) + mask_nan = torch.any(sample.isnan(), dim=1) + if keep_nan_samples: + # If the sample instances that contains Nan are decided to be kept, the row with Nan will be foreced to all zeros + sample = sample * (~mask_nan)[:, None] + else: + # Otherwise the instances with Nan will be eliminated + sample = sample[~mask_nan] + + all_samples.append(sample) + num_generated += sample.shape[0] + + x_gen = torch.cat(all_samples, dim=0)[:num_samples] + + return x_gen + + def q_xt(self, x, move_chance, strategy='hard'): + """Computes the noisy sample xt. + + Args: + x: int torch.Tensor with shape (batch_size, + diffusion_model_input_length), input. + move_chance: float torch.Tensor with shape (batch_size, 1). + """ + if strategy == 'hard': + move_indices = torch.rand( + * x.shape, device=x.device) < move_chance + xt = torch.where(move_indices, self.mask_index, x) + xt_soft = self.to_one_hot(xt).to(move_chance.dtype) + return xt, xt_soft + elif strategy == 'soft': + bs = x.shape[0] + xt_soft = torch.zeros(bs, torch.sum(self.mask_index+1), device=x.device) + xt = torch.zeros_like(x) + for i in range(len(self.num_classes)): + slice_i = self.slices_for_classes_with_mask[i] + # set the bernoulli probabilities, which determines the "coin flip" transition to the mask class + prob_i = torch.zeros(bs, 2, device=x.device) + prob_i[:,0] = 1-move_chance[:,i] + prob_i[:,-1] = move_chance[:,i] + log_prob_i = torch.log(prob_i) + # draw soft samples and place them back to the corresponding columns + soft_sample_i = F.gumbel_softmax(log_prob_i, tau=0.01, hard=True) + idx = torch.stack((x[:,i]+slice_i[0], torch.ones_like(x[:,i])*slice_i[-1]), dim=-1) + xt_soft[torch.arange(len(idx)).unsqueeze(1), idx] = soft_sample_i + # retrieve the hard samples + xt[:, i] = torch.where(soft_sample_i[:,1] > soft_sample_i[:,0], self.mask_index[i], x[:,i]) + return xt, xt_soft + + + def _subs_parameterization(self, unormalized_prob, xt): + # log prob at the mask index = - infinity + unormalized_prob = self.pad(unormalized_prob, self.neg_infinity) + + unormalized_prob[:, range(unormalized_prob.shape[1]), self.mask_index] += self.neg_infinity + + # Take log softmax on the unnormalized probabilities to the logits + logits = unormalized_prob - torch.logsumexp(unormalized_prob, dim=-1, + keepdim=True) + # Apply updates directly in the logits matrix. + # For the logits of the unmasked tokens, set all values + # to -infinity except for the indices corresponding to + # the unmasked tokens. + unmasked_indices = (xt != self.mask_index) # (bs, K) + logits[unmasked_indices] = self.neg_infinity + logits[unmasked_indices, xt[unmasked_indices]] = 0 + return logits + + def pad(self, x, pad_value): + """ + Converts a concatenated tensor of class probabilities into a padded matrix, + where each sub-tensor is padded along the last dimension to match the largest + category size (max number of classes). + + Args: + x (Tensor): The input tensor containing concatenated probabilities for all the categories in x_cat. + [bs, sum(num_classes_w_mask)] + pad_value (float): The value filled into the dummy entries, which are padded to ensure all sub-tensors have equal size + along the last dimension. + + Returns: + Tensor: A new tensorwith + [bs, len(num_classes_w_mask), max(num_classes_w_mask)), num_categories] + """ + splited = torch.split(x, self.num_classes_w_mask, dim=-1) + max_K = max(self.num_classes_w_mask) + padded_ = [ + torch.cat(( + t, + pad_value*torch.ones(*(t.shape[:-1]), max_K-t.shape[-1], dtype=t.dtype, device=t.device) + ), dim=-1) + for t in splited] + out = torch.stack(padded_, dim=-2) + return out + + def to_one_hot(self, x_cat): + x_cat_oh = torch.cat( + [F.one_hot(x_cat[:, i], num_classes=self.num_classes[i]+1,) for i in range(len(self.num_classes))], + dim=-1 + ) + return x_cat_oh + + def _absorbed_closs(self, model_output, x0, sigma, dsigma): + """ + alpha: (bs,) + """ + log_p_theta = torch.gather( + model_output, -1, x0[:, :, None] + ).squeeze(-1) + alpha = torch.exp(-sigma) + if self.cat_scheduler in ['log_linear_unified', 'log_linear_per_column']: + elbo_weight = - dsigma / torch.expm1(sigma) + else: + elbo_weight = -1/(1-alpha) + + loss = elbo_weight * log_p_theta + return loss + + def _sample_masked_prior(self, *batch_dims): + return self.mask_index[None,:] * torch.ones( + * batch_dims, dtype=torch.int64, device=self.mask_index.device) + + def _mdlm_update(self, log_p_x0, x, alpha_t, alpha_s): + """ + # t: (bs,) + log_p_x0: (bs, K, K_max) + # alpha_t: (bs,) + # alpha_s: (bs,) + alpha_t: (bs, 1/K_cat) + alpha_s: (bs,1/K_cat) + """ + move_chance_t = 1 - alpha_t + move_chance_s = 1 - alpha_s + move_chance_t = move_chance_t.unsqueeze(-1) + move_chance_s = move_chance_s.unsqueeze(-1) + assert move_chance_t.ndim == log_p_x0.ndim + # Technically, this isn't q_xs since there's a division + # term that is missing. This division term doesn't affect + # the samples. + # There is a noremalizing term is (1-\alpha_t) who's responsility is to ensure q_xs is normalized. + # However, omiting it won't make a difference for the Gumbel-max sampling trick in _sample_categorical() + q_xs = log_p_x0.exp() * (move_chance_t + - move_chance_s) + q_xs[:, range(q_xs.shape[1]), self.mask_index] = move_chance_s[:, :, 0] + + # Important: make sure that prob of dummy classes are exactly 0 + dummy_mask = torch.tensor([[(1 if i <= mask_idx else 0) for i in range(max(self.mask_index+1))] for mask_idx in self.mask_index], device=q_xs.device) + dummy_mask = torch.ones_like(q_xs) * dummy_mask + q_xs *= dummy_mask + + _x = self._sample_categorical(q_xs) + + copy_flag = (x != self.mask_index).to(x.dtype) + + z_cat = copy_flag * x + (1 - copy_flag) * _x + return copy_flag * x + (1 - copy_flag) * _x, q_xs + + def _sample_categorical(self, categorical_probs): + gumbel_norm = ( + 1e-10 + - (torch.rand_like(categorical_probs) + 1e-10).log()) + return (categorical_probs / gumbel_norm).argmax(dim=-1) + + def sample_ctime_noise(self, batch): + if self.noise_dist == 'log_norm': + rnd_normal = torch.randn(batch.shape[0], device=batch.device) + sigma = (rnd_normal * self.noise_dist_params['P_std'] + self.noise_dist_params['P_mean']).exp() + else: + raise NotImplementedError(f"The noise distribution--{self.noise_dist}-- is not implemented for CTIME ") + return sigma + + def _edm_loss(self, D_yn, y, sigma): + weight = (sigma ** 2 + self.edm_params['sigma_data'] ** 2) / (sigma * self.edm_params['sigma_data']) ** 2 + + target = y + loss = weight * ((D_yn - target) ** 2) + + return loss + + def edm_update( + self, x_num_cur, x_cat_cur, i, + t_cur, t_next, t_hat, + sigma_num_cur, sigma_num_next, sigma_num_hat, + sigma_cat_cur, sigma_cat_next, sigma_cat_hat, + ): + """ + i = T-1,...,0 + """ + cfg = self.y_only_model is not None + + b = x_num_cur.shape[0] + has_cat = len(self.num_classes) > 0 + + # Get x_num_hat by move towards the noise by a small step + x_num_hat = x_num_cur + (sigma_num_hat ** 2 - sigma_num_cur ** 2).sqrt() * S_noise * torch.randn_like(x_num_cur) + # Get x_cat_hat + move_chance = -torch.expm1(sigma_cat_cur - sigma_cat_hat) # the incremental move change is 1 - alpha_t/alpha_s = 1 - exp(sigma_s - sigma_t) + x_cat_hat, _ = self.q_xt(x_cat_cur, move_chance) if has_cat else (x_cat_cur, x_cat_cur) + + # Get predictions + x_cat_hat_oh = self.to_one_hot(x_cat_hat).to(x_num_hat.dtype) if has_cat else x_cat_hat + denoised, raw_logits = self._denoise_fn( + x_num_hat.float(), x_cat_hat_oh, + t_hat.squeeze().repeat(b), sigma=sigma_num_hat.unsqueeze(0).repeat(b,1) # sigma accepts (bs, K_num) + ) + + # Apply cfg updates, if is in cfg mode + is_bin_class = len(self.num_mask_idx) == 0 + is_learnable = self.scheduler=="power_mean_per_column" + if cfg: + if not is_learnable: + sigma_cond = sigma_num_hat + else: + if is_bin_class: + sigma_cond = (0.002 ** (1/7) + t_hat * (80 ** (1/7) - 0.002 ** (1/7))).pow(7) + else: + sigma_cond = sigma_num_hat[self.num_mask_idx] + y_num_hat = x_num_hat.float()[:, self.num_mask_idx] + idx = list(chain(*[self.slices_for_classes_with_mask[i] for i in self.cat_mask_idx])) + y_cat_hat = x_cat_hat_oh[:,idx] + y_only_denoised, y_only_raw_logits = self.y_only_model( + y_num_hat, + y_cat_hat, + t_hat.squeeze().repeat(b), sigma=sigma_cond.unsqueeze(0).repeat(b,1) # sigma accepts (bs, K_num) + ) + + denoised[:, self.num_mask_idx] *= 1 + self.w_num + denoised[:, self.num_mask_idx] -= self.w_num*y_only_denoised + + mask_logit_idx = [self.slices_for_classes_with_mask[i] for i in self.cat_mask_idx] + mask_logit_idx = np.concatenate(mask_logit_idx) if len(mask_logit_idx)>0 else np.array([]) + + raw_logits[:, mask_logit_idx] *= 1 + self.w_cat + raw_logits[:, mask_logit_idx] -= self.w_cat*y_only_raw_logits + + # Euler step + d_cur = (x_num_hat - denoised) / sigma_num_hat + x_num_next = x_num_hat + (sigma_num_next - sigma_num_hat) * d_cur + + # Unmasking + x_cat_next = x_cat_cur + q_xs = torch.zeros_like(x_cat_cur).float() + if has_cat: + logits = self._subs_parameterization(raw_logits, x_cat_hat) + alpha_t = torch.exp(-sigma_cat_hat).unsqueeze(0).repeat(b,1) + alpha_s = torch.exp(-sigma_cat_next).unsqueeze(0).repeat(b,1) + x_cat_next, q_xs = self._mdlm_update(logits, x_cat_hat, alpha_t, alpha_s) + + # Apply 2nd order correction. + if self.sampler_params['second_order_correction']: + if i > 0: + x_cat_hat_oh = self.to_one_hot(x_cat_hat).to(x_num_next.dtype) if has_cat else x_cat_hat + denoised, raw_logits = self._denoise_fn( + x_num_next.float(), x_cat_hat_oh, + t_next.squeeze().repeat(b), sigma=sigma_num_next.unsqueeze(0).repeat(b,1) + ) + if cfg: + if not is_learnable: + sigma_cond = sigma_num_next + else: + if is_bin_class: + sigma_cond = (0.002 ** (1/7) + t_next * (80 ** (1/7) - 0.002 ** (1/7))).pow(7) + else: + sigma_cond = sigma_num_next[self.num_mask_idx] + y_num_next = x_num_next.float()[:, self.num_mask_idx] + idx = list(chain(*[self.slices_for_classes_with_mask[i] for i in self.cat_mask_idx])) + y_cat_hat = x_cat_hat_oh[:, idx] + y_only_denoised, y_only_raw_logits = self.y_only_model( + y_num_next, + y_cat_hat, + t_next.squeeze().repeat(b), sigma=sigma_cond.unsqueeze(0).repeat(b,1) # sigma accepts (bs, K_num) + ) + denoised[:, self.num_mask_idx] *= 1 + self.w_num + denoised[:, self.num_mask_idx] -= self.w_num*y_only_denoised + + d_prime = (x_num_next - denoised) / sigma_num_next + x_num_next = x_num_hat + (sigma_num_next - sigma_num_hat) * (0.5 * d_cur + 0.5 * d_prime) + + return x_num_next, x_cat_next, q_xs + + + def sample_impute(self, x_num, x_cat, num_mask_idx, cat_mask_idx, resample_rounds, impute_condition, w_num, w_cat): + self.w_num = w_num + self.w_cat = w_cat + self.num_mask_idx = num_mask_idx + self.cat_mask_idx = cat_mask_idx + + b = x_num.size(0) + device = self.device + dtype = torch.float32 + + # Create masks, true for the missing columns + num_mask = [i in num_mask_idx for i in range(self.num_numerical_features)] + cat_mask = [i in cat_mask_idx for i in range(len(self.num_classes))] + num_mask = torch.tensor(num_mask).to(x_num.device).to(x_num.dtype) + cat_mask = torch.tensor(cat_mask).to(x_cat.device).to(x_cat.dtype) + + # Create the chain of t + t = torch.linspace(0,1,self.num_timesteps, dtype=dtype, device=device) # times = 0.0,...,1.0 + t = t[:, None] + + # Compute the chains of sigma + sigma_num_cur = self.num_schedule.total_noise(t) + sigma_cat_cur = self.cat_schedule.total_noise(t) + sigma_num_next = torch.zeros_like(sigma_num_cur) + sigma_num_next[1:] = sigma_num_cur[0:-1] + sigma_cat_next = torch.zeros_like(sigma_cat_cur) + sigma_cat_next[1:] = sigma_cat_cur[0:-1] + + # Prepare sigma_hat for stochastic sampling mode + if self.sampler_params['stochastic_sampler']: + gamma = min(S_churn / self.num_timesteps, np.sqrt(2) - 1) * (S_min <= sigma_num_cur) * (sigma_num_cur <= S_max) + sigma_num_hat = sigma_num_cur + gamma * sigma_num_cur + t_hat = self.num_schedule.inverse_to_t(sigma_num_hat) + t_hat = torch.min(t_hat, dim=-1, keepdim=True).values # take the samllest t_hat induced by sigma_num + zero_gamma = (gamma==0).any() + t_hat[zero_gamma] = t[zero_gamma] + out_of_bound = (t_hat > 1).squeeze() + sigma_num_hat[out_of_bound] = sigma_num_cur[out_of_bound] + t_hat[out_of_bound] = t[out_of_bound] + sigma_cat_hat = self.cat_schedule.total_noise(t_hat) + else: + t_hat = t + sigma_num_hat = sigma_num_cur + sigma_cat_hat = sigma_cat_cur + + # Sample priors for the continuous dimensions + if impute_condition == "x_t": + z_norm = x_num + torch.randn((b, self.num_numerical_features), device=device) * sigma_num_cur[-1] # z_{t_max} = x_0(masked) + sigma_max*epsilon + elif impute_condition == "x_0": + z_norm = x_num + + # Sample priors for the discrete dimensions + has_cat = len(self.num_classes) > 0 + z_cat = torch.zeros((b, 0), device=device).float() # the default values for categorical sample if the dataset has no categorical entry + if has_cat: + if impute_condition == "x_t": + z_cat = self._sample_masked_prior( + b, + len(self.num_classes), + ) # z_{t_max} is still all pushed to [MASK] + elif impute_condition == "x_0": + z_cat = x_cat + + pbar = tqdm(reversed(range(0, self.num_timesteps)), total=self.num_timesteps) + pbar.set_description(f"Sampling Progress") + for i in pbar: + for u in range (resample_rounds): + # Get known parts by Forward Flow + if impute_condition == "x_t": + z_norm_known = x_num + torch.randn((b, self.num_numerical_features), device=device) * sigma_num_next[i] + move_chance = 1 - torch.exp(-sigma_cat_next[i]) if i < (self.num_timesteps-1) else torch.ones_like(sigma_cat_next[i]) # force move_chance to be 1 for the first iteration + z_cat_known, _ = self.q_xt(x_cat, move_chance) + elif impute_condition == "x_0": + z_norm_known = x_num + z_cat_known = x_cat + + # Get unknown by Reverse Step + z_norm_unknown, z_cat_unknown, q_xs = self.edm_update( + z_norm, z_cat, i, + t[i], t[i-1] if i > 0 else None, t_hat[i], + sigma_num_cur[i], sigma_num_next[i], sigma_num_hat[i], + sigma_cat_cur[i], sigma_cat_next[i], sigma_cat_hat[i], + ) + z_norm = (1 - num_mask) * z_norm_known + num_mask * z_norm_unknown + z_cat = (1 - cat_mask) * z_cat_known + cat_mask * z_cat_unknown + + # Resample x_t from x_{t-1} by Foward Step + if u < resample_rounds-1: + z_norm = z_norm + (sigma_num_cur[i] ** 2 - sigma_num_next[i] ** 2).sqrt() * S_noise * torch.randn_like(z_norm) + move_chance = -torch.expm1(sigma_cat_next[i] - sigma_cat_cur[i]) + z_cat, _ = self.q_xt(z_cat, move_chance) + + sample = torch.cat([z_norm, z_cat], dim=1).cpu() + return sample + \ No newline at end of file diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/modules/main_modules.py b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/modules/main_modules.py new file mode 100644 index 0000000000000000000000000000000000000000..8e4333d626894e114ab775f07ceba5c8c46b52f8 --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/modules/main_modules.py @@ -0,0 +1,167 @@ +from typing import Callable, Union + +from tabdiff.modules.transformer import Reconstructor, Tokenizer, Transformer +import torch +import torch.nn as nn +import torch.optim + +ModuleType = Union[str, Callable[..., nn.Module]] + +class SiLU(nn.Module): + def forward(self, x): + return x * torch.sigmoid(x) + +class PositionalEmbedding(torch.nn.Module): + def __init__(self, num_channels, max_positions=10000, endpoint=False): + super().__init__() + self.num_channels = num_channels + self.max_positions = max_positions + self.endpoint = endpoint + + def forward(self, x): + freqs = torch.arange(start=0, end=self.num_channels//2, dtype=torch.float32, device=x.device) + freqs = freqs / (self.num_channels // 2 - (1 if self.endpoint else 0)) + freqs = (1 / self.max_positions) ** freqs + x = x.ger(freqs.to(x.dtype)) + x = torch.cat([x.cos(), x.sin()], dim=1) + return x + + +class MLPDiffusion(nn.Module): + def __init__(self, d_in, dim_t = 512, use_mlp=True): + super().__init__() + self.dim_t = dim_t + + self.proj = nn.Linear(d_in, dim_t) + + self.mlp = nn.Sequential( + nn.Linear(dim_t, dim_t * 2), + nn.SiLU(), + nn.Linear(dim_t * 2, dim_t * 2), + nn.SiLU(), + nn.Linear(dim_t * 2, dim_t), + nn.SiLU(), + nn.Linear(dim_t, d_in), + ) if use_mlp else nn.Linear(dim_t, d_in) + + self.map_noise = PositionalEmbedding(num_channels=dim_t) + self.time_embed = nn.Sequential( + nn.Linear(dim_t, dim_t), + nn.SiLU(), + nn.Linear(dim_t, dim_t) + ) + + self.use_mlp = use_mlp + + def forward(self, x, timesteps): + emb = self.map_noise(timesteps) + emb = emb.reshape(emb.shape[0], 2, -1).flip(1).reshape(*emb.shape) # swap sin/cos + emb = self.time_embed(emb) + + x = self.proj(x) + emb + return self.mlp(x) + +class UniModMLP(nn.Module): + """ + Input: + x_num: [bs, d_numerical] + x_cat: [bs, len(categories)] + Output: + x_num_pred: [bs, d_numerical], the predicted mean for numerical data + x_cat_pred: [bs, sum(categories)], the predicted UNORMALIZED logits for categorical data + """ + def __init__( + self, d_numerical, categories, num_layers, d_token, + n_head = 1, factor = 4, bias = True, dim_t=512, use_mlp=True, **kwargs + ): + super().__init__() + self.d_numerical = d_numerical + self.categories = categories + + self.tokenizer = Tokenizer(d_numerical, categories, d_token, bias = bias) + self.encoder = Transformer(num_layers, d_token, n_head, d_token, factor) + d_in = d_token * (d_numerical + len(categories)) + self.mlp = MLPDiffusion(d_in, dim_t=dim_t, use_mlp=use_mlp) + self.decoder = Transformer(num_layers, d_token, n_head, d_token, factor) + self.detokenizer = Reconstructor(d_numerical, categories, d_token) + + self.model = nn.ModuleList([self.tokenizer, self.encoder, self.mlp, self.decoder, self.detokenizer]) + + def forward(self, x_num, x_cat, timesteps): + e = self.tokenizer(x_num, x_cat) + decoder_input = e[:, 1:, :] # ignore the first CLS token. + y = self.encoder(decoder_input) + pred_y = self.mlp(y.reshape(y.shape[0], -1), timesteps) + pred_e = self.decoder(pred_y.reshape(*y.shape)) + x_num_pred, x_cat_pred = self.detokenizer(pred_e) + x_cat_pred = torch.cat(x_cat_pred, dim=-1) if len(x_cat_pred)>0 else torch.zeros_like(x_cat).to(x_num_pred.dtype) + + return x_num_pred, x_cat_pred + + +class Precond(nn.Module): + def __init__(self, + denoise_fn, + sigma_data = 0.5, # Expected standard deviation of the training data. + net_conditioning = "sigma", + ): + super().__init__() + self.sigma_data = sigma_data + self.net_conditioning = net_conditioning + self.denoise_fn_F = denoise_fn + + def forward(self, x_num, x_cat, t, sigma): + + x_num = x_num.to(torch.float32) + + sigma = sigma.to(torch.float32) + assert sigma.ndim == 2 + if sigma.dim() > 1: # if learnable column-wise noise schedule, sigma conditioning is set to the defaults schedule of rho=7 + sigma_cond = (0.002 ** (1/7) + t * (80 ** (1/7) - 0.002 ** (1/7))).pow(7) + else: + sigma_cond = sigma + dtype = torch.float32 + + c_skip = self.sigma_data ** 2 / (sigma ** 2 + self.sigma_data ** 2) + c_out = sigma * self.sigma_data / (sigma ** 2 + self.sigma_data ** 2).sqrt() + c_in = 1 / (self.sigma_data ** 2 + sigma ** 2).sqrt() + c_noise = sigma_cond.log() / 4 + + x_in = c_in * x_num + if self.net_conditioning == "sigma": + F_x, x_cat_pred = self.denoise_fn_F(x_in, x_cat, c_noise.flatten()) + elif self.net_conditioning == "t": + F_x, x_cat_pred = self.denoise_fn_F(x_in, x_cat, t) + + assert F_x.dtype == dtype + D_x = c_skip * x_num + c_out * F_x.to(torch.float32) + + return D_x, x_cat_pred + + +class Model(nn.Module): + def __init__( + self, denoise_fn, + sigma_data=0.5, + precond=False, + net_conditioning="sigma", + **kwargs + ): + super().__init__() + self.precond = precond + if precond: + self.denoise_fn_D = Precond( + denoise_fn, + sigma_data=sigma_data, + net_conditioning=net_conditioning + ) + else: + self.denoise_fn_D = denoise_fn + + def forward(self, x_num, x_cat, t, sigma=None): + if self.precond: + return self.denoise_fn_D(x_num, x_cat, t, sigma) + else: + return self.denoise_fn_D(x_num, x_cat, t) + + diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/modules/transformer.py b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/modules/transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..bedffe15eaa4fec85d7f686ba8741dc5d4d7ac04 --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/modules/transformer.py @@ -0,0 +1,258 @@ +import numpy as np +import torch +import torch.nn as nn +import torch.nn.init as nn_init +import torch.nn.functional as F +from torch import Tensor + +import math + +class Tokenizer(nn.Module): + + def __init__(self, d_numerical, categories, d_token, bias): + super().__init__() + if categories is None: + d_bias = d_numerical + self.category_offsets = None + self.category_embeddings = None + else: + d_bias = d_numerical + len(categories) + category_offsets = torch.tensor([0] + list(categories[:-1])).cumsum(0) + self.register_buffer('category_offsets', category_offsets) + self.cat_weight = nn.Parameter(Tensor(sum(categories), d_token)) + nn.init.kaiming_uniform_(self.cat_weight, a=math.sqrt(5)) + + # take [CLS] token into account + self.weight = nn.Parameter(Tensor(d_numerical + 1, d_token)) + self.bias = nn.Parameter(Tensor(d_bias, d_token)) if bias else None + # The initialization is inspired by nn.Linear + nn_init.kaiming_uniform_(self.weight, a=math.sqrt(5)) + if self.bias is not None: + nn_init.kaiming_uniform_(self.bias, a=math.sqrt(5)) + + @property + def n_tokens(self): + return len(self.weight) + ( + 0 if self.category_offsets is None else len(self.category_offsets) + ) + + def forward(self, x_num, x_cat): + x_some = x_num if x_cat is None else x_cat + assert x_some is not None + x_num = torch.cat( + [torch.ones(len(x_some), 1, device=x_some.device)] # [CLS] + + ([] if x_num is None else [x_num]), + dim=1, + ) + + x = self.weight[None] * x_num[:, :, None] + + if x_cat is not None: + for start, end in zip(self.category_offsets, torch.cat([self.category_offsets[1:], torch.tensor([x_cat.shape[1]], device=x_cat.device)])): + if start < end: + x = torch.cat( + [x, x_cat[:, start:end].unsqueeze(1) @ self.cat_weight[start:end][None]], + dim=1, + ) + if self.bias is not None: + bias = torch.cat( + [ + torch.zeros(1, self.bias.shape[1], device=x.device), + self.bias, + ] + ) + x = x + bias[None] + + return x + + +class MultiheadAttention(nn.Module): + def __init__(self, d, n_heads, dropout, initialization = 'kaiming'): + + if n_heads > 1: + assert d % n_heads == 0 + assert initialization in ['xavier', 'kaiming'] + + super().__init__() + self.W_q = nn.Linear(d, d) + self.W_k = nn.Linear(d, d) + self.W_v = nn.Linear(d, d) + self.W_out = nn.Linear(d, d) if n_heads > 1 else None + self.n_heads = n_heads + self.dropout = nn.Dropout(dropout) if dropout else None + + for m in [self.W_q, self.W_k, self.W_v]: + if initialization == 'xavier' and (n_heads > 1 or m is not self.W_v): + # gain is needed since W_qkv is represented with 3 separate layers + nn_init.xavier_uniform_(m.weight, gain=1 / math.sqrt(2)) + nn_init.zeros_(m.bias) + if self.W_out is not None: + nn_init.zeros_(self.W_out.bias) + + def _reshape(self, x): + batch_size, n_tokens, d = x.shape + d_head = d // self.n_heads + return ( + x.reshape(batch_size, n_tokens, self.n_heads, d_head) + .transpose(1, 2) + .reshape(batch_size * self.n_heads, n_tokens, d_head) + ) + + def forward(self, x_q, x_kv, key_compression = None, value_compression = None): + + q, k, v = self.W_q(x_q), self.W_k(x_kv), self.W_v(x_kv) + for tensor in [q, k, v]: + assert tensor.shape[-1] % self.n_heads == 0 + if key_compression is not None: + assert value_compression is not None + k = key_compression(k.transpose(1, 2)).transpose(1, 2) + v = value_compression(v.transpose(1, 2)).transpose(1, 2) + else: + assert value_compression is None + + batch_size = len(q) + d_head_key = k.shape[-1] // self.n_heads + d_head_value = v.shape[-1] // self.n_heads + n_q_tokens = q.shape[1] + + q = self._reshape(q) + k = self._reshape(k) + + a = q @ k.transpose(1, 2) + b = math.sqrt(d_head_key) + attention = F.softmax(a/b , dim=-1) + + + if self.dropout is not None: + attention = self.dropout(attention) + x = attention @ self._reshape(v) + x = ( + x.reshape(batch_size, self.n_heads, n_q_tokens, d_head_value) + .transpose(1, 2) + .reshape(batch_size, n_q_tokens, self.n_heads * d_head_value) + ) + if self.W_out is not None: + x = self.W_out(x) + + return x + +class Transformer(nn.Module): + + def __init__( + self, + n_layers: int, + d_token: int, + n_heads: int, + d_out: int, + d_ffn_factor: int, + attention_dropout = 0.0, + ffn_dropout = 0.0, + residual_dropout = 0.0, + activation = 'relu', + prenormalization = True, + initialization = 'kaiming', + ): + super().__init__() + + def make_normalization(): + return nn.LayerNorm(d_token) + + d_hidden = int(d_token * d_ffn_factor) + self.layers = nn.ModuleList([]) + for layer_idx in range(n_layers): + layer = nn.ModuleDict( + { + 'attention': MultiheadAttention( + d_token, n_heads, attention_dropout, initialization + ), + 'linear0': nn.Linear( + d_token, d_hidden + ), + 'linear1': nn.Linear(d_hidden, d_token), + 'norm1': make_normalization(), + } + ) + if not prenormalization or layer_idx: + layer['norm0'] = make_normalization() + + self.layers.append(layer) + + self.activation = nn.ReLU() + self.last_activation = nn.ReLU() + # self.activation = lib.get_activation_fn(activation) + # self.last_activation = lib.get_nonglu_activation_fn(activation) + self.prenormalization = prenormalization + self.last_normalization = make_normalization() if prenormalization else None + self.ffn_dropout = ffn_dropout + self.residual_dropout = residual_dropout + self.head = nn.Linear(d_token, d_out) + + + def _start_residual(self, x, layer, norm_idx): + x_residual = x + if self.prenormalization: + norm_key = f'norm{norm_idx}' + if norm_key in layer: + x_residual = layer[norm_key](x_residual) + return x_residual + + def _end_residual(self, x, x_residual, layer, norm_idx): + if self.residual_dropout: + x_residual = F.dropout(x_residual, self.residual_dropout, self.training) + x = x + x_residual + if not self.prenormalization: + x = layer[f'norm{norm_idx}'](x) + return x + + def forward(self, x): + for layer_idx, layer in enumerate(self.layers): + is_last_layer = layer_idx + 1 == len(self.layers) + + x_residual = self._start_residual(x, layer, 0) + x_residual = layer['attention']( + # for the last attention, it is enough to process only [CLS] + x_residual, + x_residual, + ) + + x = self._end_residual(x, x_residual, layer, 0) + + x_residual = self._start_residual(x, layer, 1) + x_residual = layer['linear0'](x_residual) + x_residual = self.activation(x_residual) + if self.ffn_dropout: + x_residual = F.dropout(x_residual, self.ffn_dropout, self.training) + x_residual = layer['linear1'](x_residual) + x = self._end_residual(x, x_residual, layer, 1) + return x + + +class Reconstructor(nn.Module): + def __init__(self, d_numerical, categories, d_token): + super(Reconstructor, self).__init__() + + self.d_numerical = d_numerical + self.categories = categories + self.d_token = d_token + + self.weight = nn.Parameter(Tensor(d_numerical, d_token)) + nn.init.xavier_uniform_(self.weight, gain=1 / math.sqrt(2)) + self.cat_recons = nn.ModuleList() + + for d in categories: + recon = nn.Linear(d_token, d) + nn.init.xavier_uniform_(recon.weight, gain=1 / math.sqrt(2)) + self.cat_recons.append(recon) + + def forward(self, h): + h_num = h[:, :self.d_numerical] + h_cat = h[:, self.d_numerical:] + + recon_x_num = torch.mul(h_num, self.weight.unsqueeze(0)).sum(-1) + recon_x_cat = [] + + for i, recon in enumerate(self.cat_recons): + + recon_x_cat.append(recon(h_cat[:, i])) + + return recon_x_num, recon_x_cat diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/all_results.json b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/all_results.json new file mode 100644 index 0000000000000000000000000000000000000000..998156d5bac2a32c994a7ec92768bbce40ae45fb --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/all_results.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9d134294203446e03592901f16dfcb205ca970f48310268d1fd120cd162fba87 +size 130 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/ema/all_results.json b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/ema/all_results.json new file mode 100644 index 0000000000000000000000000000000000000000..5552e9dc7fe80abbe2b67a0fcd1db55a5b48f118 --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/ema/all_results.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c56427721b0ebf830b49ad9e3f89cc818098b6ddb67b9cf019a593cc8f70f8b6 +size 131 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/ema/samples.csv b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/ema/samples.csv new file mode 100644 index 0000000000000000000000000000000000000000..a34009c3e37a1bbce8fdfca46a09626b7a6043c2 --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/ema/samples.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9faa0e91674299ec62cf79064ed8f3a0d3e29f58149aad189b63f0060bbd608c +size 2733807 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/ema/shapes.csv b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/ema/shapes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f10533b4ea8965d7a3980c6b99028c9f132508c9 --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/ema/shapes.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c6208e0cf0757e538851cad7cf631184fe4b7dd50f5206c3562b767ef57c65a1 +size 638 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/ema/trends.csv b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/ema/trends.csv new file mode 100644 index 0000000000000000000000000000000000000000..2c37b62beefc90fe6b6b3187a784bdc19f3922cf --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/ema/trends.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0e2988b7a3c7ebe13fa3947a81eec36d606336e75d3d986d054dad5305850d73 +size 7899 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/samples.csv b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/samples.csv new file mode 100644 index 0000000000000000000000000000000000000000..d379002855d9015ca88cad2acb783f290f56497a --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/samples.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5f5467e7cf2f62e55fbc0df78de3cb40d653f8e826318d94a29a811565a4ab9c +size 2683271 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/shapes.csv b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/shapes.csv new file mode 100644 index 0000000000000000000000000000000000000000..73e7329512b95df46710cb8715b72f0966f91030 --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/shapes.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b9117583c0df1166a9a11decb1953ad0151eb0ab841a11bc92ab27411e2c67f5 +size 637 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/trends.csv b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/trends.csv new file mode 100644 index 0000000000000000000000000000000000000000..c9c1dfe59f029d7692fa44a35802f47efffd8f1d --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/result/pipeline_c19/adapter_learnable/200/trends.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:29465892f0e47ce5eb5a0738d5fc1d3d12422ce3b40a23a70b846c464127c2f0 +size 7744 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/trainer.py b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..35ee6d7afff62017dcaa63ca46c3bb7b2cc246f3 --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/trainer.py @@ -0,0 +1,657 @@ +import os +import glob +import time +import torch +from torch.optim.lr_scheduler import ReduceLROnPlateau +import numpy as np +import pandas as pd +import json + +from copy import deepcopy + +from utils_train import update_ema + +from tqdm import tqdm + +BAR = "==============" +def print_with_bar(log_msg): + log_msg = BAR + log_msg + BAR + if "End" in log_msg: + log_msg += "\n" + print(log_msg) + +class Trainer: + def __init__( + self, diffusion, train_iter, dataset, test_dataset, metrics, logger, + lr, weight_decay, + steps, batch_size, check_val_every, + sample_batch_size, model_save_path, result_save_path, + num_samples_to_generate=None, + lr_scheduler='reduce_lr_on_plateau', + reduce_lr_patience=100, factor=0.9, + ema_decay=0.997, + closs_weight_schedule = "fixed", + c_lambda = 1.0, + d_lambda = 1.0, + device=torch.device('cuda:1'), + ckpt_path = None, + y_only=False, + **kwargs + ): + self.y_only = y_only + self.diffusion = diffusion + self.ema_model = deepcopy(self.diffusion._denoise_fn) + for param in self.ema_model.parameters(): + param.detach_() + self.ema_num_schedule = deepcopy(self.diffusion.num_schedule) + for param in self.ema_num_schedule.parameters(): + param.detach_() + self.ema_cat_schedule = deepcopy(self.diffusion.cat_schedule) + for param in self.ema_cat_schedule.parameters(): + param.detach_() + + self.train_iter = train_iter + self.dataset = dataset + self.test_dataset = test_dataset + self.steps = steps + self.init_lr = lr + self.optimizer = torch.optim.AdamW(self.diffusion.parameters(), lr=lr, weight_decay=weight_decay) + self.ema_decay = ema_decay + self.lr_scheduler = lr_scheduler + # PyTorch >= 2.8: ReduceLROnPlateau no longer accepts `verbose=` + self.scheduler = ReduceLROnPlateau( + self.optimizer, mode="min", factor=factor, patience=reduce_lr_patience + ) + self.closs_weight_schedule = closs_weight_schedule + self.c_lambda = c_lambda + self.d_lambda = d_lambda + + self.batch_size = batch_size + self.sample_batch_size = sample_batch_size + self.num_samples_to_generate = num_samples_to_generate + self.metrics = metrics + self.logger = logger + self.check_val_every = check_val_every + + self.device = device + self.model_save_path = model_save_path + self.result_save_path = result_save_path + self.ckpt_path = ckpt_path + if self.ckpt_path is not None: + state_dicts = torch.load(self.ckpt_path, map_location=self.device) + self.diffusion._denoise_fn.load_state_dict(state_dicts['denoise_fn']) + self.diffusion.num_schedule.load_state_dict(state_dicts['num_schedule']) + self.diffusion.cat_schedule.load_state_dict(state_dicts['cat_schedule']) + print(f"Weights are loaded from {self.ckpt_path}") + + self.curr_epoch = int(os.path.basename(self.ckpt_path).split('_')[-1].split('.')[0]) if self.ckpt_path is not None else 0 + + def _anneal_lr(self, step): + frac_done = step / self.steps + lr = self.init_lr * (1 - frac_done) + for param_group in self.optimizer.param_groups: + param_group["lr"] = lr + + def _run_step(self, x, closs_weight, dloss_weight): + x = x.to(self.device) + + self.diffusion.train() + + self.optimizer.zero_grad() + + dloss, closs = self.diffusion.mixed_loss(x) + + loss = dloss_weight * dloss + closs_weight * closs + loss.backward() + self.optimizer.step() + + return dloss, closs + + def compute_loss(self): # eval loss is not weighted + curr_dloss = 0.0 + curr_closs = 0.0 + curr_count = 0 + data_iter = self.train_iter + for batch in data_iter: + x = batch.float().to(self.device) + self.diffusion.eval() + with torch.no_grad(): + batch_dloss, batch_closs = self.diffusion.mixed_loss(x) + curr_dloss += batch_dloss.item() * len(x) + curr_closs += batch_closs.item() * len(x) + curr_count += len(x) + mloss = np.around(curr_dloss / curr_count, 4) + gloss = np.around(curr_closs / curr_count, 4) + return mloss, gloss + + def run_loop(self): + patience = 0 + closs_weight, dloss_weight = self.c_lambda, self.d_lambda + best_loss = np.inf + best_ema_loss = np.inf + best_val_loss = np.inf + start_time = time.time() + print_with_bar(f"Starting Trainin Loop, total number of epoch = {self.steps}") + # Set up wandb's step metric + self.logger.define_metric("epoch") + self.logger.define_metric("*", step_metric="epoch") + + start_epoch = self.curr_epoch + if start_epoch > 0: + print_with_bar(f"Resuming training from epoch {start_epoch}, with validation check every {self.check_val_every} epoches") + for epoch in range (start_epoch, self.steps): + self.curr_epoch = epoch+1 + # Set up pbar + pbar = tqdm(self.train_iter, total=len(self.train_iter)) + pbar.set_description(f"Epoch {epoch+1}/{self.steps}") + + # Compute the loss weights + if self.closs_weight_schedule == "fixed": + pass + elif self.closs_weight_schedule == "anneal": + frac_done = epoch / self.steps + closs_weight = self.c_lambda * (1 - frac_done) + else: + raise NotImplementedError(f"The continuous loss weight schedule {self.closs_weight_schedule} is not implemneted") + + # Training Step + curr_dloss = 0.0 + curr_closs = 0.0 + curr_count = 0 + curr_lr = self.optimizer.param_groups[0]['lr'] + for batch in pbar: + x = batch.float().to(self.device) + batch_dloss, batch_closs = self._run_step(x, closs_weight, dloss_weight) + curr_dloss += batch_dloss.item() * len(x) + curr_closs += batch_closs.item() * len(x) + curr_count += len(x) + pbar.set_postfix({ + "lr": curr_lr, + "DLoss": np.around(curr_dloss/curr_count, 4), + "CLoss": np.around(curr_closs/curr_count, 4), + "TotalLoss": np.around((curr_dloss + curr_closs)/curr_count, 4), + "closs_weight": closs_weight, + "dloss_weight": dloss_weight, + }) + + # Log training Loss + log_dict = {} + mloss = np.around(curr_dloss / curr_count, 4) + gloss = np.around(curr_closs / curr_count, 4) + total_loss = mloss + gloss + if np.isnan(gloss): + print('Finding Nan in gaussian loss') + break + loss_dict = { + "epoch": epoch + 1, + "lr": curr_lr, + "closs_weight": closs_weight, + "dloss_weight": dloss_weight, + "loss/c_loss": gloss, + "loss/d_loss": mloss, + "loss/total_loss": total_loss + } + log_dict.update(loss_dict) + + # Log the learned noise schedules for numerical dimensions + if self.dataset.d_numerical > 0: # numerical data is not empty + num_noise_dict = {} + if self.diffusion.num_schedule.rho().dim() == 0: # non-learnable num schedule + num_noise_dict = {"num_noise/rho": self.diffusion.num_schedule.rho().item()} + else: + num_noise_dict = {f"num_noise/rho_col_{i}": value.item() for i, value in enumerate(self.diffusion.num_schedule.rho())} + log_dict.update(num_noise_dict) + + # Log the learned noise schedules for categlrical dimensions + if len(self.dataset.categories) > 0: # categorical data is not empty + cat_noise_dict = {} + if self.diffusion.cat_schedule.k().dim() == 0: # non-learnable cat schedule + cat_noise_dict = {"cat_noise/k": self.diffusion.cat_schedule.k().item()} + else: + cat_noise_dict = {f"cat_noise/k_col_{i}": value.item() for i, value in enumerate(self.diffusion.cat_schedule.k())} + log_dict.update(cat_noise_dict) + + # Adjust learning rate + if self.lr_scheduler == 'reduce_lr_on_plateau': + self.scheduler.step(total_loss) + elif self.lr_scheduler == 'anneal': + self._anneal_lr(epoch) + elif self.lr_scheduler == 'fixed': + pass + else: + raise NotImplementedError(f"LR scheduler with name '{self.lr_scheduler}' is not implemented") + + # Update EMA models + update_ema(self.ema_model.parameters(), self.diffusion._denoise_fn.parameters(), rate=self.ema_decay) + update_ema(self.ema_num_schedule.parameters(), self.diffusion.num_schedule.parameters(), rate=self.ema_decay) + update_ema(self.ema_cat_schedule.parameters(), self.diffusion.cat_schedule.parameters(), rate=self.ema_decay) + + # Save ckpt base on the best training loss + if total_loss < best_loss and self.curr_epoch > 4000: + best_loss = total_loss + to_remove = glob.glob(os.path.join(self.model_save_path, f"best_model_*")) + if to_remove: + os.remove(to_remove[0]) + state_dicts = { + 'denoise_fn': self.diffusion._denoise_fn.state_dict(), + 'num_schedule':self.diffusion.num_schedule.state_dict(), + 'cat_schedule': self.diffusion.cat_schedule.state_dict(), + } + torch.save(state_dicts, os.path.join(self.model_save_path, f'best_model_{np.round(total_loss,4)}_{epoch+1}.pt')) + patience = 0 + else: + patience += 1 # increment patience if best loss is not surpassed + + # Compute and log EMA model loss + curr_model, curr_num_schedule, curr_cat_schedule = self.to_ema_model() + ema_mloss, ema_gloss = self.compute_loss() + self.to_model(curr_model, curr_num_schedule, curr_cat_schedule) + ema_total_loss = ema_mloss + ema_gloss + ema_loss_dict = { + "ema_loss/c_loss": ema_gloss, + "ema_loss/d_loss": ema_mloss, + "ema_loss/total_loss": ema_total_loss + } + + # Save the best ema ckpt + if ema_total_loss < best_ema_loss and self.curr_epoch > 4000: + best_ema_loss = ema_total_loss + to_remove = glob.glob(os.path.join(self.model_save_path, f"best_ema_model_*")) + if to_remove: + os.remove(to_remove[0]) + state_dicts = { + 'denoise_fn': self.ema_model.state_dict(), + 'num_schedule':self.ema_num_schedule.state_dict(), + 'cat_schedule': self.ema_cat_schedule.state_dict(), + } + torch.save(state_dicts, os.path.join(self.model_save_path, f'best_ema_model_{np.round(ema_total_loss,4)}_{epoch+1}.pt')) + + # Evaluate Sample Quality + if (epoch+1) % self.check_val_every == 0: + state_dicts = { + 'denoise_fn': self.diffusion._denoise_fn.state_dict(), + 'num_schedule':self.diffusion.num_schedule.state_dict(), + 'cat_schedule': self.diffusion.cat_schedule.state_dict(), + } + torch.save(state_dicts, os.path.join(self.model_save_path, f'model_{epoch+1}.pt')) + + print_with_bar(f"Routine Generation Evaluation every {self.check_val_every}, currently at epoch #{epoch+1}, wiht total_loss={total_loss}.") + # 适配器训练:容器内无 Chrome,跳过 Kaleido 密度图 + _plot_density = os.environ.get("TABDIFF_ADAPTER_TRAIN", "").strip().lower() not in ("1", "true", "yes") + out_metrics, _, _ = self.evaluate_generation(save_metric_details=True, plot_density=_plot_density) + log_dict.update(out_metrics) + print(f"Eval Resutls of the Non-EMA model:\n {out_metrics}") + + # Evaluate the EMA model + torch.save(self.ema_model.state_dict(), os.path.join(self.model_save_path, f'ema_model_{epoch+1}.pt')) + ema_out_metrics, _, _ = self.evaluate_generation(ema=True, save_metric_details=True, plot_density=_plot_density) + log_dict.update({ + "ema": ema_out_metrics, + }) + print(f"Eval Resutls of the EMA model:\n {ema_out_metrics}") + + # Submit logs + self.logger.log(log_dict) + + end_time = time.time() + print_with_bar(f"Ending Trainnig Loop, totoal training time = {end_time - start_time}") + self.logger.log({ + 'training_time': end_time - start_time + }) + + def report_test(self, num_runs): + save_dir = self.result_save_path + + shape_ = [] + trend_ = [] + mle_ = [] + c2st_ = [] + for i in range(num_runs): + print_with_bar(f"GENERAL Evaluation Run {i}") + out_metrics, extras, syn_df = self.evaluate_generation() + print(f"Results of Run {i} are: \n{out_metrics}") + shape_.append(out_metrics["density/Shape"]) + trend_.append(out_metrics["density/Trend"]) + mle_.append(out_metrics["mle"]) + c2st_.append(out_metrics["c2st"]) + # Save samples for quality evaluation + save_path = os.path.join(save_dir, "all_samples") + if not os.path.exists(save_path): + os.makedirs(save_path) + syn_df.to_csv(os.path.join(save_path, f"samples_{i}.csv"), index=False) + + shape_ = np.array(shape_) + trend_ = np.array(trend_) + mle_ = np.array(mle_) + c2st_ = np.array(c2st_) + + shape_error = (1 - shape_)*100 + trend_error = (1 - trend_)*100 + c2st_percent = c2st_ * 100 + + all_results = pd.DataFrame({ + "shape": shape_error, + "trend": trend_error, + "mle": mle_, + "c2st": c2st_percent, + }) + avg = all_results.mean(axis=0).round(3) + std = all_results.std(axis=0).round(3) + avg_std = pd.concat([avg, std], axis=1, ignore_index=True) + avg_std.columns = ["avg", "std"] + avg_std.index = [ + "shape", + "trend", + "mle", + "c2st", + ] + + # Savings + all_results.to_csv(f"{save_dir}/all_results.csv", index=True) + avg_std.to_csv(f"{save_dir}/avg_std.csv", index=True) + print_with_bar(f"The AVG over {num_runs} runs are: \n{avg_std}") + + def report_test_dcr(self, num_runs): + save_dir = self.result_save_path + + dcr_ = [] + dcr_real_ = [] + dcr_test_ = [] + for i in range(num_runs): + print_with_bar(f"DCR Evaluation Run {i}") + out_metrics, extras, syn_df = self.evaluate_generation() + print(f"Results of Run {i} are: \n{out_metrics}") + dcr_.append(out_metrics["dcr"]) + dcr_real_.append(extras["dcr_real"]) + dcr_test_.append(extras["dcr_test"]) + save_path = os.path.join(save_dir, "all_samples") + if not os.path.exists(save_path): + os.makedirs(save_path) + syn_df.to_csv(os.path.join(save_path, f"samples_{i}.csv"), index=False) + + dcr_ = np.array(dcr_) + + dcr_percent = dcr_ * 100 + + all_results = pd.DataFrame({ + "dcr": dcr_percent, + }) + avg = all_results.mean(axis=0).round(3) + std = all_results.std(axis=0).round(3) + avg_std = pd.concat([avg, std], axis=1, ignore_index=True) + avg_std.columns = ["avg", "std"] + avg_std.index = [ + "dcr", + ] + + # Savings + all_results.to_csv(f"{save_dir}/all_results.csv", index=True) + avg_std.to_csv(f"{save_dir}/avg_std.csv", index=True) + dcr_real = np.concatenate(dcr_real_, axis=0) + dcr_test = np.concatenate(dcr_test_, axis=0) + dcr_df = pd.DataFrame({ + "dcr_real": dcr_real, + "dcr_test": dcr_test + }) + dcr_df.to_csv(f"{save_dir}/dcr.csv", index=False) + + print_with_bar(f"The AVG over {num_runs} runs are: \n{avg_std}") + + def test(self): + _plot_density = os.environ.get("TABDIFF_ADAPTER_TRAIN", "").strip().lower() not in ("1", "true", "yes") + out_metrics, _, _ = self.evaluate_generation(save_metric_details=True, plot_density=_plot_density) + print_with_bar(f"Results of the test are: \n{out_metrics}") + self.logger.log(out_metrics) + print(out_metrics) + + def evaluate_generation(self, save_metric_details=False, plot_density=False, ema=False): + self.diffusion.eval() + + # Sample a synthetic table + num_samples = self.num_samples_to_generate if self.num_samples_to_generate else self.metrics.real_data_size # By default, num_samples_to_generate is not specified. In this case, we generate the same number of samples as the real dataset. This approach is consistently used across all experiments in the paper. + syn_df = self.sample_synthetic(num_samples, ema=ema) + + # Save the sample + save_path = os.path.join(self.result_save_path, str(self.curr_epoch), "ema" if ema else "") + if not os.path.exists(save_path): + os.makedirs(save_path) + path = os.path.join(save_path, "samples.csv") + syn_df.to_csv(path, index=False) + print( + f"Samples are saved at {path}" + ) + + # 流水线仅需要 CSV:跳过 MLE/C2ST 等(合成表为字符串类别时 MLE 会报错) + if os.environ.get("TABDIFF_ADAPTER_SAMPLE_ONLY", "").strip().lower() in ("1", "true", "yes"): + return {}, {}, syn_df + + # Compute evaluation metrics on the sample + syn_df_loaded = pd.read_csv(os.path.join(save_path, "samples.csv")) # In the original tabsyn code, syn_data is implicitly casted into float.64 when it gets loaded with pd.read_csv in the evaluation script. If we don't cast, the density evluation for some columns (especially those with tailed and peaked distribution) will collapse. + out_metrics, extras = self.metrics.evaluate(syn_df_loaded) + + # Save metrics and metric details + path = os.path.join(save_path, "all_results.json") + with open(path, "w") as json_file: + json.dump(out_metrics, json_file, indent=4, separators=(", ", ": ")) # always locally save the output metrics + if save_metric_details: + for name, extra in extras.items(): + if isinstance(extra, pd.DataFrame): + extra.to_csv(os.path.join(save_path, f"{name}.csv")) + elif isinstance(extra, dict): + with open(os.path.join(save_path, f"{name}.json"), "w") as json_file: + json.dump(extra, json_file, indent=4, separators=(", ", ": ")) + else: + raise NotImplementedError(f"Extra file generated during evaluations has type {type(extra)}, and code to save this type of file is not implemented") + + # Plot density figures + if plot_density: + img = self.metrics.plot_density(syn_df_loaded) + path = os.path.join(save_path, "density_plots.png") + img.save(path) + print( + f"The density plots are saved at {path}" + ) + return out_metrics, extras, syn_df + + + def sample_synthetic(self, num_samples, keep_nan_samples=True, ema=False): + if ema: + curr_model, curr_num_schedule, curr_cat_schedule = self.to_ema_model() + info = self.metrics.info + + print_with_bar(f"Starting Sampling, total samples to generate = {num_samples}") + start_time = time.time() + + syn_data = self.diffusion.sample_all(num_samples, self.sample_batch_size, keep_nan_samples=keep_nan_samples) + print(f"Shape of the generated sample = {syn_data.shape}") + + if keep_nan_samples: + num_all_zero_row = (syn_data.sum(dim=1) == 0).sum() + if num_all_zero_row: + print(f"The generated samples contain {num_all_zero_row} Nan instances!!!") + self.logger.log({ + 'num_Nan_sample': num_all_zero_row + }) + + # Recover tables + num_inverse = self.dataset.num_inverse + int_inverse = self.dataset.int_inverse + cat_inverse = self.dataset.cat_inverse + + if self.y_only: + if info['task_type'] == 'binclass': + syn_data = cat_inverse(syn_data) + else: + syn_data = num_inverse(syn_data) + syn_df = pd.DataFrame() + syn_df[info['column_names'][info['target_col_idx'][0]]] = syn_data[:, 0] + else: + syn_num, syn_cat, syn_target = split_num_cat_target(syn_data, info, num_inverse, int_inverse, cat_inverse) + syn_df = recover_data(syn_num, syn_cat, syn_target, info) + + + idx_name_mapping = info['idx_name_mapping'] + idx_name_mapping = {int(key): value for key, value in idx_name_mapping.items()} + + syn_df.rename(columns = idx_name_mapping, inplace=True) + + end_time = time.time() + print_with_bar(f"Ending Sampling, totoal sampling time = {end_time - start_time}") + + if ema: + self.to_model(curr_model, curr_num_schedule, curr_cat_schedule) + + return syn_df + + def to_ema_model(self): + curr_model = self.diffusion._denoise_fn + curr_num_schedule = self.diffusion.num_schedule + curr_cat_schedule = self.diffusion.cat_schedule + self.diffusion._denoise_fn = self.ema_model # temporarily install the ema parameters into the model + self.diffusion.num_schedule = self.ema_num_schedule + self.diffusion.cat_schedule = self.ema_cat_schedule + + return curr_model, curr_num_schedule, curr_cat_schedule + + def to_model(self, curr_model, curr_num_schedule, curr_cat_schedule): + self.diffusion._denoise_fn = curr_model # give back the parameters + self.diffusion.num_schedule = curr_num_schedule + self.diffusion.cat_schedule = curr_cat_schedule + + def test_impute(self, trail_start, trial_size, resample_rounds, impute_condition, imputed_sample_save_dir, w_num, w_cat): + self.diffusion.eval() + + info = self.metrics.info + task_type = info['task_type'] + d_numerical, categories = self.dataset.d_numerical, self.dataset.categories + num_mask_idx, cat_mask_idx = [], [] + X_train = self.dataset.X + X_train = X_train + x_num_train, x_cat_train = X_train[:,:d_numerical], X_train[:,d_numerical:] + + if task_type == 'binclass': # for cat cols, push the masked col to [MASK] + cat_mask_idx += [0] + else: # for num cols, set the masked col to the col mean + num_mask_idx += [0] + avg = x_num_train[:, num_mask_idx].mean(0).to(self.device) + + with torch.no_grad(): + + for trial in range(trail_start, trail_start+trial_size): + print_with_bar(f"Imputing trial {trial}") + X_test = self.test_dataset.X + X_test = deepcopy(X_test).to(self.device) + x_num_test, x_cat_test = X_test[:, :d_numerical], X_test[:, d_numerical:].long() + + # Apply mask to x_0 + if num_mask_idx: + x_num_test[:, num_mask_idx] = avg + if cat_mask_idx: + x_cat_test[:, cat_mask_idx] = torch.tensor(categories, dtype=x_cat_test.dtype, device=x_cat_test.device)[cat_mask_idx] + + # Sample imputed tables + syn_data = self.diffusion.sample_impute(x_num_test, x_cat_test, num_mask_idx, cat_mask_idx, resample_rounds, impute_condition, w_num, w_cat) + print(f"Shape of the imputed sample = {syn_data.shape}") + + # Recover tables + num_inverse = self.dataset.num_inverse + int_inverse = self.dataset.int_inverse + cat_inverse = self.dataset.cat_inverse + + if torch.any((syn_data[:, d_numerical+1:]).max(dim=0).values > (x_cat_train[:,1:]).max(dim=0).values): # if the test set contains categories not presented in the train set, we can not do cat_inverse. So we implement a patch that set those columns to the same as the train set + print("Test set contains extra categories, and so does imputed syn data. We cannot do cat_inverse. So we set the cat columns as the same as the train set") + syn_data[:, d_numerical+1:] = x_cat_train[:syn_data.shape[0],1:] + + + syn_num, syn_cat, syn_target = split_num_cat_target(syn_data, info, num_inverse, int_inverse, cat_inverse) + syn_df = recover_data(syn_num, syn_cat, syn_target, info) + + idx_name_mapping = info['idx_name_mapping'] + idx_name_mapping = {int(key): value for key, value in idx_name_mapping.items()} + + syn_df.rename(columns = idx_name_mapping, inplace=True) + + # Save imputed samples + os.makedirs(imputed_sample_save_dir) if not os.path.exists(imputed_sample_save_dir) else None + print(f"Imputed samples are saved to {imputed_sample_save_dir}/{trial}.csv") + syn_df.to_csv(f'{imputed_sample_save_dir}/{trial}.csv', index = False) + +def _as_numpy_float32(x): + """Inverse 变换可能返回 Tensor;统一为 numpy float32(含 0 列)。""" + if x is None: + return np.array([], dtype=np.float32) + if isinstance(x, torch.Tensor): + x = x.detach().cpu().numpy() + return np.asarray(x, dtype=np.float32) + + +@torch.no_grad() +def split_num_cat_target(syn_data, info, num_inverse, int_inverse, cat_inverse): + task_type = info['task_type'] + + num_col_idx = info['num_col_idx'] + cat_col_idx = info['cat_col_idx'] + target_col_idx = info['target_col_idx'] + + n_num_feat = len(num_col_idx) + n_cat_feat = len(cat_col_idx) + + if task_type == 'regression': + n_num_feat += len(target_col_idx) + else: + n_cat_feat += len(target_col_idx) + + syn_num = syn_data[:, :n_num_feat] + syn_cat = syn_data[:, n_num_feat:] + + if n_num_feat > 0: + syn_num = _as_numpy_float32(num_inverse(syn_num)) + syn_num = _as_numpy_float32(int_inverse(syn_num)) + else: + syn_num = np.zeros((syn_data.shape[0], 0), dtype=np.float32) + syn_cat = cat_inverse(syn_cat) + + + if info['task_type'] == 'regression': + syn_target = syn_num[:, :len(target_col_idx)] + syn_num = syn_num[:, len(target_col_idx):] + + else: + print(syn_cat.shape) + syn_target = syn_cat[:, :len(target_col_idx)] + syn_cat = syn_cat[:, len(target_col_idx):] + + return syn_num, syn_cat, syn_target + +def recover_data(syn_num, syn_cat, syn_target, info): + + num_col_idx = info['num_col_idx'] + cat_col_idx = info['cat_col_idx'] + target_col_idx = info['target_col_idx'] + + + idx_mapping = info['idx_mapping'] + idx_mapping = {int(key): value for key, value in idx_mapping.items()} + + syn_df = pd.DataFrame() + + if info['task_type'] == 'regression': + for i in range(len(num_col_idx) + len(cat_col_idx) + len(target_col_idx)): + if i in set(num_col_idx): + syn_df[i] = syn_num[:, idx_mapping[i]] + elif i in set(cat_col_idx): + syn_df[i] = syn_cat[:, idx_mapping[i] - len(num_col_idx)] + else: + syn_df[i] = syn_target[:, idx_mapping[i] - len(num_col_idx) - len(cat_col_idx)] + + + else: + for i in range(len(num_col_idx) + len(cat_col_idx) + len(target_col_idx)): + if i in set(num_col_idx): + syn_df[i] = syn_num[:, idx_mapping[i]] + elif i in set(cat_col_idx): + syn_df[i] = syn_cat[:, idx_mapping[i] - len(num_col_idx)] + else: + syn_df[i] = syn_target[:, idx_mapping[i] - len(num_col_idx) - len(cat_col_idx)] + + return syn_df \ No newline at end of file diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/utils_train.py b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/utils_train.py new file mode 100644 index 0000000000000000000000000000000000000000..34b289ab9ac194c655c96e3c1806335acbcd5f21 --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/utils_train.py @@ -0,0 +1,193 @@ +import numpy as np +import os + +import src +from torch.utils.data import Dataset + +import torch + + +class TabularDataset(Dataset): + def __init__(self, X_num, X_cat): + self.X_num = X_num + self.X_cat = X_cat + + def __getitem__(self, index): + this_num = self.X_num[index] + this_cat = self.X_cat[index] + + sample = (this_num, this_cat) + + return sample + + def __len__(self): + return self.X_num.shape[0] + +class TabDiffDataset(Dataset): + def __init__(self, dataname, data_dir, info, isTrain=True, y_only=False, dequant_dist='none', int_dequant_factor=0.0): + self.dataname = dataname + self.data_dir = data_dir + self.info = info + self.isTrain = isTrain + + X_num, X_cat, categories, d_numerical, num_inverse, int_inverse, cat_inverse = preprocess(data_dir, y_only, dequant_dist, int_dequant_factor, task_type = info['task_type'], inverse=True) + categories = np.array(categories) + + X_train_num, _ = X_num + X_train_cat, _ = X_cat + + X_train_num, X_test_num = X_num + X_train_cat, X_test_cat = X_cat + + X_train_num, X_test_num = torch.tensor(X_train_num).float(), torch.tensor(X_test_num).float() + X_train_cat, X_test_cat = torch.tensor(X_train_cat), torch.tensor(X_test_cat) + + self.X = torch.cat((X_train_num, X_train_cat), dim=1) if isTrain else torch.cat((X_test_num, X_test_cat), dim=1) + self.num_inverse = num_inverse + self.int_inverse = int_inverse + self.cat_inverse = cat_inverse + self.d_numerical = d_numerical + self.categories = categories + + def __getitem__(self, index): + return self.X[index] + + def __len__(self): + return self.X.shape[0] + +def preprocess(dataset_path, y_only=False, dequant_dist='none', int_dequant_factor=0.0, task_type = 'binclass', inverse = False, cat_encoding = None, concat = True): + + T_dict = {} + + T_dict['normalization'] = "quantile" + T_dict['num_nan_policy'] = 'mean' + T_dict['cat_nan_policy'] = None + T_dict['cat_min_frequency'] = None + T_dict['cat_encoding'] = cat_encoding + T_dict['y_policy'] = "default" + T_dict['dequant_dist'] = dequant_dist + T_dict['int_dequant_factor'] = int_dequant_factor + + T = src.Transformations(**T_dict) + + dataset = make_dataset( + data_path = dataset_path, + T = T, + task_type = task_type, + change_val = False, + concat = concat, + y_only = y_only, + ) + + if cat_encoding is None: + X_num = dataset.X_num + X_cat = dataset.X_cat + + X_train_num, X_test_num = X_num['train'], X_num['test'] + X_train_cat, X_test_cat = X_cat['train'], X_cat['test'] + + categories = src.get_categories(X_train_cat) + d_numerical = X_train_num.shape[1] + + X_num = (X_train_num, X_test_num) + X_cat = (X_train_cat, X_test_cat) + + + if inverse: + num_inverse = dataset.num_transform.inverse_transform if dataset.num_transform is not None else lambda x: x + int_inverse = dataset.int_transform.inverse_transform if dataset.int_transform is not None else lambda x: x + cat_inverse = dataset.cat_transform.inverse_transform if dataset.cat_transform is not None else lambda x: x + + return X_num, X_cat, categories, d_numerical, num_inverse, int_inverse, cat_inverse + else: + return X_num, X_cat, categories, d_numerical + else: + return dataset + + +def update_ema(target_params, source_params, rate=0.999): + """ + Update target parameters to be closer to those of source parameters using + an exponential moving average. + :param target_params: the target parameter sequence. + :param source_params: the source parameter sequence. + :param rate: the EMA rate (closer to 1 means slower). + """ + for target, source in zip(target_params, source_params): + target.detach().mul_(rate).add_(source.detach(), alpha=1 - rate) + + + +def concat_y_to_X(X, y): + if X is None: + return y.reshape(-1, 1) + return np.concatenate([y.reshape(-1, 1), X], axis=1) + + +def make_dataset( + data_path: str, + T: src.Transformations, + task_type, + change_val: bool, + concat = True, + y_only = False, +): + + # classification + if task_type == 'binclass' or task_type == 'multiclass': + X_cat = {} if os.path.exists(os.path.join(data_path, 'X_cat_train.npy')) else None + X_num = {} if os.path.exists(os.path.join(data_path, 'X_num_train.npy')) else None + y = {} if os.path.exists(os.path.join(data_path, 'y_train.npy')) else None + + for split in ['train', 'test']: + X_num_t, X_cat_t, y_t = src.read_pure_data(data_path, split) + if y_only: + X_num_t = X_num_t[:, :0] + X_cat_t = X_cat_t[:, :0] + if X_num is not None: + X_num[split] = X_num_t + if X_cat is not None: + if concat: + X_cat_t = concat_y_to_X(X_cat_t, y_t) + X_cat[split] = X_cat_t + if y is not None: + y[split] = y_t + else: + # regression + X_cat = {} if os.path.exists(os.path.join(data_path, 'X_cat_train.npy')) else None + X_num = {} if os.path.exists(os.path.join(data_path, 'X_num_train.npy')) else None + y = {} if os.path.exists(os.path.join(data_path, 'y_train.npy')) else None + + for split in ['train', 'test']: + X_num_t, X_cat_t, y_t = src.read_pure_data(data_path, split) + if y_only: + X_num_t = X_num_t[:, :0] + X_cat_t = X_cat_t[:, :0] + if X_num is not None: + if concat: + X_num_t = concat_y_to_X(X_num_t, y_t) + X_num[split] = X_num_t + if X_cat is not None: + X_cat[split] = X_cat_t + if y is not None: + y[split] = y_t + + info = src.load_json(os.path.join(data_path, 'info.json')) + int_col_idx_wrt_num = info['int_col_idx_wrt_num'] + + if y_only: + int_col_idx_wrt_num = [] + D = src.Dataset( + X_num, + X_cat, + y, + int_col_idx_wrt_num, + y_info={}, + task_type=src.TaskType(info['task_type']), + n_classes=info.get('n_classes') + ) + + if change_val: + D = src.change_val(D) + + return src.transform_dataset(D, T, None) \ No newline at end of file diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_train.py b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_train.py new file mode 100644 index 0000000000000000000000000000000000000000..32f95e406f13ef6c99153ac600ff5fc4234f67eb --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_train.py @@ -0,0 +1,37 @@ + +import os, shutil, subprocess, sys +td = r"/workspace/TabDiff" +name = r"pipeline_c19" +src = r"/work/output-Benchmark-trainonly-v1/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19" +rt = r"/work/output-Benchmark-trainonly-v1/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime" +shutil.rmtree(rt, ignore_errors=True) + +def _ignore(_, names): + skip = {"__pycache__", "data", "synthetic", "result", "results", "ckpt"} + return [n for n in names if n in skip or n.endswith(".pyc")] + +shutil.copytree(td, rt, ignore=_ignore) +dst_data = os.path.join(rt, "data", name) +dst_syn = os.path.join(rt, "synthetic", name) +shutil.rmtree(dst_data, ignore_errors=True) +os.makedirs(os.path.dirname(dst_data), exist_ok=True) +shutil.copytree(src, dst_data) +os.makedirs(dst_syn, exist_ok=True) +for fn in ("real.csv", "test.csv", "val.csv"): + shutil.copy(os.path.join(src, fn), os.path.join(dst_syn, fn)) +os.chdir(rt) +os.environ["PYTHONPATH"] = rt + os.pathsep + os.environ.get("PYTHONPATH", "") +os.environ["TABDIFF_SMOKE_STEPS"] = "200" +os.environ["TABDIFF_STEPS"] = "200" +os.environ["TABDIFF_BATCH_SIZE"] = "256" +os.environ["TABDIFF_TRAIN_BATCH_SIZE"] = "256" +os.environ["TABDIFF_LR"] = "0.0005" +os.environ["TABDIFF_LEARNING_RATE"] = "0.0005" +os.environ["TABDIFF_NUM_TIMESTEPS"] = "50" +os.environ["TABDIFF_TIMESTEPS"] = "50" +os.environ["TABDIFF_ADAPTER_TRAIN"] = "1" +subprocess.check_call([ + sys.executable, "-m", "tabdiff.main", + "--dataname", name, "--mode", "train", "--gpu", "0", + "--no_wandb", "--exp_name", r"adapter_learnable", +]) diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/gen_20260512_235639.log b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/gen_20260512_235639.log new file mode 100644 index 0000000000000000000000000000000000000000..9098e7699bcf7203590535d15f32507f7eaea07e --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/gen_20260512_235639.log @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:82bd7af31e532c601085bbf8520857d4d2b3d90ccb979e04fb6681a3d077c4fb +size 20709 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/input_snapshot.json b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/input_snapshot.json new file mode 100644 index 0000000000000000000000000000000000000000..156c214d05e8359dfd85fcd04a225cad023eb620 --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/input_snapshot.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:680c43f3c6b710f4819990c79ec01a64eadf5e684519f2b4f24ef975aec3ea95 +size 1365 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/models_tabdiff/trained.pt b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/models_tabdiff/trained.pt new file mode 100644 index 0000000000000000000000000000000000000000..bc319a55a9c7152a1137f968b6fa1c735125ad11 --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/models_tabdiff/trained.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:306660b8aad4549267c68390b017e15ddb9bc06a02c80515eb72a97ae31a81eb +size 74 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/public_gate/normalized_schema_snapshot.json b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/public_gate/normalized_schema_snapshot.json new file mode 100644 index 0000000000000000000000000000000000000000..ed2f27e57e828cd83a70cede0727f850a65f5d78 --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/public_gate/normalized_schema_snapshot.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:29277905718aadff6392f1a493cc90a009209da285eb3c9cfaa6ed315532ed07 +size 15890 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/public_gate/public_gate_report.json b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/public_gate/public_gate_report.json new file mode 100644 index 0000000000000000000000000000000000000000..1f66ece22ccef26553e87a13120ec99eb4130e0b --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/public_gate/public_gate_report.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3f3b9879993ec6898672e12c529e80204564945d19d90073329035241094707d +size 925 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/public_gate/staged_input_manifest.json b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/public_gate/staged_input_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..40678633f7107e5801d5bd478a39853e12620146 --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/public_gate/staged_input_manifest.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:34e580171577dc0e09b65f513a06daf278467c6003786960658de07124b9b51e +size 16706 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/run_config.json b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/run_config.json new file mode 100644 index 0000000000000000000000000000000000000000..fc04c456bac27718f6b3a69eaadd2a54358b729a --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/run_config.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:86918644b454346973312b8dea331bdd2547b85f1c194c26b141201770f7c198 +size 2135 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/runtime_result.json b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/runtime_result.json new file mode 100644 index 0000000000000000000000000000000000000000..b68093cf824ad2be9441084a8b5480db64a3787b --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/runtime_result.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:32c520ff0ab9a01c9d947e37076996c153c51ed53b08ce17e69528201cb8774e +size 919 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/staged/public/staged_features.json b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/staged/public/staged_features.json new file mode 100644 index 0000000000000000000000000000000000000000..f7a45799d9522e8c70ceeacb01c3e541f566bc0d --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/staged/public/staged_features.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a57a0c3c2a45c85e74d4496ad733ad7f30b2615f97be5155850895fee1727948 +size 1564 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/staged/public/test.csv b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/staged/public/test.csv new file mode 100644 index 0000000000000000000000000000000000000000..cb9afc272bf187c8a1c1827116ca6dc7c4bbe054 --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/staged/public/test.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fd9c98343a92c7b1afe63b402f07b9a55013adbfcc60ec1e17d5e026385eeec8 +size 6304860 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/staged/public/train.csv b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/staged/public/train.csv new file mode 100644 index 0000000000000000000000000000000000000000..0dd04cf8cc5b17cba0a4a176cbd5639b58b972a4 --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/staged/public/train.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:092346325db7f445db2c00d2f5dd9a8397ecc33eaba7b2b14d9d48d92659fcfc +size 51459027 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/staged/public/val.csv b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/staged/public/val.csv new file mode 100644 index 0000000000000000000000000000000000000000..cbb1e83d2c80952e08b23dcc09f8cb5cea219a6a --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/staged/public/val.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:69c75639e81916d3b4f2a28db38d7e15c78e442748aa5bf9fed2eb3784912a70 +size 6331589 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/staged/tabdiff/adapter_report.json b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/staged/tabdiff/adapter_report.json new file mode 100644 index 0000000000000000000000000000000000000000..d72ec50e13bb7a5050846283ad99b8b6bcadee1e --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/staged/tabdiff/adapter_report.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f4b9235b1924d062280171700bcc65c8919d35c01d1d372893d7e7b86ccd10ea +size 323 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/staged/tabdiff/adapter_transforms_applied.json b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/staged/tabdiff/adapter_transforms_applied.json new file mode 100644 index 0000000000000000000000000000000000000000..6f3aaa01a627a955d2022165805d2786c0da78ba --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/staged/tabdiff/adapter_transforms_applied.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945 +size 2 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/staged/tabdiff/model_input_manifest.json b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/staged/tabdiff/model_input_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..13067f08e2fe4098d0ad777ae8d0c4e8de1d8279 --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/staged/tabdiff/model_input_manifest.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:905e865626a919cbb648f38b9bbf48cedab357ed3420f7137af788dc95811a61 +size 16905 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabdiff-c19-32759-20260512_235639.csv b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabdiff-c19-32759-20260512_235639.csv new file mode 100644 index 0000000000000000000000000000000000000000..8a21b027d4a82227c12f48f88ceefccb8cea671f --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabdiff-c19-32759-20260512_235639.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e51070cb4ce9094d790109d11e3443ce223c378fcb41104bb29bed05948a5ec3 +size 3081557 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabdiff_train_meta.json b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabdiff_train_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..f0c8de1d380f27e00128672db305d31d4bdb0b76 --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabdiff_train_meta.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1ccd80cce0d9b441f3519fe6a975882f6fdd0aab10a4dd632284bb81acc6d4c8 +size 486 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/X_cat_test.npy b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/X_cat_test.npy new file mode 100644 index 0000000000000000000000000000000000000000..cf1d15fb69cd7b6f72af00a38d49711f4bcc9244 --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/X_cat_test.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7e8e273d7cebc9c535de23aac186a248e19f1b9270192e8516df2b3ff4d03b37 +size 360576 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/X_cat_train.npy b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/X_cat_train.npy new file mode 100644 index 0000000000000000000000000000000000000000..fca3a3846cebc5898e069bba00d964961f9926ad --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/X_cat_train.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:34a72bf9b360ceafc923a841725257c58f68702db5988848164e6a73030811ca +size 2882920 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/X_cat_val.npy b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/X_cat_val.npy new file mode 100644 index 0000000000000000000000000000000000000000..c270bf236a716346950feb1831b13c748f67e8b2 --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/X_cat_val.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d7520984bdd5518919a6429f53fe78669a4c04ec06e58bb0b5388e56628d3080 +size 360400 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/X_num_test.npy b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/X_num_test.npy new file mode 100644 index 0000000000000000000000000000000000000000..992e6cc9ecb1f69540b0b2a3726c27ca532f7021 --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/X_num_test.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:30bb71265025b7923a442d2e4818d163e76ace6a48bd5be6e29de20770bc8e15 +size 65664 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/X_num_train.npy b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/X_num_train.npy new file mode 100644 index 0000000000000000000000000000000000000000..fede1611458c47aec61bac42b2f1f1d0383ce1e7 --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/X_num_train.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:42ba0171576b4338cee3594e553bc298640933ba7a7c8a127ec106b642ee63e6 +size 524272 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/X_num_val.npy b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/X_num_val.npy new file mode 100644 index 0000000000000000000000000000000000000000..b4e2d680e1483c196073ea784ce7add7a3252dbb --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/X_num_val.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:adb8a29c75d7bdc3c8f7e797e555998c90f3b3154ccaeee3dc93d8cbe6c3c2d1 +size 65632 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/info.json b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/info.json new file mode 100644 index 0000000000000000000000000000000000000000..2bda2ed8d66d951a58f9259faca5696e4f6348f9 --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/info.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:26b65c13dd436fb96a31e3ea486b261897b74f9a192fe79828dc57be59be2f35 +size 2739 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/real.csv b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/real.csv new file mode 100644 index 0000000000000000000000000000000000000000..0dd04cf8cc5b17cba0a4a176cbd5639b58b972a4 --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/real.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:092346325db7f445db2c00d2f5dd9a8397ecc33eaba7b2b14d9d48d92659fcfc +size 51459027 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/staged_features.json b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/staged_features.json new file mode 100644 index 0000000000000000000000000000000000000000..f7a45799d9522e8c70ceeacb01c3e541f566bc0d --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/staged_features.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a57a0c3c2a45c85e74d4496ad733ad7f30b2615f97be5155850895fee1727948 +size 1564 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/test.csv b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/test.csv new file mode 100644 index 0000000000000000000000000000000000000000..cb9afc272bf187c8a1c1827116ca6dc7c4bbe054 --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/test.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fd9c98343a92c7b1afe63b402f07b9a55013adbfcc60ec1e17d5e026385eeec8 +size 6304860 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/train.csv b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/train.csv new file mode 100644 index 0000000000000000000000000000000000000000..0dd04cf8cc5b17cba0a4a176cbd5639b58b972a4 --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/train.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:092346325db7f445db2c00d2f5dd9a8397ecc33eaba7b2b14d9d48d92659fcfc +size 51459027 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/val.csv b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/val.csv new file mode 100644 index 0000000000000000000000000000000000000000..cbb1e83d2c80952e08b23dcc09f8cb5cea219a6a --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/val.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:69c75639e81916d3b4f2a28db38d7e15c78e442748aa5bf9fed2eb3784912a70 +size 6331589 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/y_test.npy b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/y_test.npy new file mode 100644 index 0000000000000000000000000000000000000000..b77e2d6fb7a7a8c91668434e24e63b2620d67968 --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/y_test.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:81ee7259842c7941a044da2da22e21e7cfc06ae84f376f61f795079639c0f830 +size 32896 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/y_train.npy b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/y_train.npy new file mode 100644 index 0000000000000000000000000000000000000000..bae44b2ff466c14427f52a13426452d2a807c0f5 --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/y_train.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:977de15b5bd4785ce2c1370504303a66f974c6dd474345dc88784832776cf98f +size 262200 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/y_val.npy b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/y_val.npy new file mode 100644 index 0000000000000000000000000000000000000000..eefcd0aa702255f005abedecf0ea79a3818b19d6 --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19/y_val.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7a9ff40f59b5afc2a1752a1d42a673b1c24c422c859c9e3c35d6110919dfb7f7 +size 32880 diff --git a/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/train_20260512_231308.log b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/train_20260512_231308.log new file mode 100644 index 0000000000000000000000000000000000000000..3e14b9d4e76b9c1eaff5ff8f7c30dae544ec9f6f --- /dev/null +++ b/SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/train_20260512_231308.log @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5b70c62513ac03ad416f1f8359b0c5cab8b876c3995d0b0b4a9783c4f997bce5 +size 598601 diff --git a/SynthData0523/main/c19/tabpfgen/tabpfgen-c19-20260422_200215/_tabpfgen_generate.py b/SynthData0523/main/c19/tabpfgen/tabpfgen-c19-20260422_200215/_tabpfgen_generate.py new file mode 100644 index 0000000000000000000000000000000000000000..8c1fed52e0b8457a3c47836784010ea9b977583c --- /dev/null +++ b/SynthData0523/main/c19/tabpfgen/tabpfgen-c19-20260422_200215/_tabpfgen_generate.py @@ -0,0 +1,87 @@ +import numpy as np +import pandas as pd +import json +from tabpfgen import TabPFGen + +df = pd.read_csv("/work/output-SpecializedModels/c19/tabpfgen/tabpfgen-c19-20260422_200215/staged/public/train.csv") +target_col = "category_id" + +feature_cols = [c for c in df.columns if c != target_col] + +# --- Label-encode categorical / object columns --- +cat_encodings = {} # col -> list of unique values (index = code) +for col in feature_cols: + if df[col].dtype == object or str(df[col].dtype) == 'category': + cats = sorted(df[col].dropna().unique().tolist(), key=str) + cat_map = {v: i for i, v in enumerate(cats)} + df[col] = df[col].map(cat_map).astype(float) + cat_encodings[col] = cats + print(f"[TabPFGen] Label-encoded '{col}' ({len(cats)} categories)") + +# Encode target if categorical +target_cats = None +if df[target_col].dtype == object or str(df[target_col].dtype) == 'category': + cats = sorted(df[target_col].dropna().unique().tolist(), key=str) + t_map = {v: i for i, v in enumerate(cats)} + df[target_col] = df[target_col].map(t_map).astype(float) + target_cats = cats + print(f"[TabPFGen] Label-encoded target '{target_col}' ({len(cats)} categories)") + +X = df[feature_cols].values.astype(np.float32) +y = df[target_col].values +target_n = int(32759) + +# Handle NaN +for i in range(X.shape[1]): + col_vals = X[:, i] + mask = np.isnan(col_vals) + if mask.any(): + mean_val = np.nanmean(col_vals) + X[mask, i] = mean_val if not np.isnan(mean_val) else 0.0 + +gen = TabPFGen( + n_sgld_steps=1000, + sgld_step_size=0.01, + sgld_noise_scale=0.01, + device="auto", +) + +print(f"[TabPFGen] Generating {target_n} rows via generate_regression") +X_syn, y_syn = gen.generate_regression(X, y, n_samples=target_n) + +syn_df = pd.DataFrame(X_syn, columns=feature_cols) +syn_df[target_col] = y_syn + +# --- Inverse label-encoding for categorical columns --- +for col, cats in cat_encodings.items(): + # Round to nearest integer index, clamp to valid range + codes = np.round(syn_df[col].values).astype(int) + codes = np.clip(codes, 0, len(cats) - 1) + syn_df[col] = [cats[c] for c in codes] + +if target_cats is not None: + codes = np.round(syn_df[target_col].values).astype(int) + codes = np.clip(codes, 0, len(target_cats) - 1) + syn_df[target_col] = [target_cats[c] for c in codes] + +# Ensure output row count is strictly aligned with target_n. +if len(syn_df) > target_n: + print(f"[TabPFGen] Trimming rows: {len(syn_df)} -> {target_n}") + syn_df = syn_df.iloc[:target_n].copy() +elif len(syn_df) < target_n: + deficit = target_n - len(syn_df) + print(f"[TabPFGen] Padding rows: {len(syn_df)} -> {target_n} (deficit={deficit})") + if len(syn_df) > 0: + extra = syn_df.sample(n=deficit, replace=True, random_state=42) + syn_df = pd.concat([syn_df.reset_index(drop=True), extra.reset_index(drop=True)], ignore_index=True) + else: + # Defensive fallback: if generator returns empty, bootstrap from training rows. + syn_df = df[feature_cols + [target_col]].sample( + n=target_n, replace=True, random_state=42 + ).reset_index(drop=True) + +syn_df = syn_df[list(df.columns)] +if len(syn_df) != target_n: + raise RuntimeError(f"[TabPFGen] Row alignment failed: got {len(syn_df)}, expected {target_n}") +syn_df.to_csv("/work/output-SpecializedModels/c19/tabpfgen/tabpfgen-c19-20260422_200215/tabpfgen-c19-32759-20260422_200228.csv", index=False) +print(f"[TabPFGen] Saved {len(syn_df)} rows -> /work/output-SpecializedModels/c19/tabpfgen/tabpfgen-c19-20260422_200215/tabpfgen-c19-32759-20260422_200228.csv") diff --git a/SynthData0523/main/c19/tabpfgen/tabpfgen-c19-20260422_200215/gen_20260422_200228.log b/SynthData0523/main/c19/tabpfgen/tabpfgen-c19-20260422_200215/gen_20260422_200228.log new file mode 100644 index 0000000000000000000000000000000000000000..b81b92fad457f58bd54394774740740c56170b26 --- /dev/null +++ b/SynthData0523/main/c19/tabpfgen/tabpfgen-c19-20260422_200215/gen_20260422_200228.log @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:226200e7a0829ec4520f148a3421232993d6f77d1bdb344f096144e155b979d0 +size 987