├── tablediffusion ├── __init__.py ├── config │ ├── __init__.py │ └── configs.py ├── metrics │ ├── __init__.py │ └── metrics.py ├── vis │ ├── __init__.py │ └── visualisations.py ├── utilities │ ├── __init__.py │ ├── privacy_utils.py │ ├── data_utils.py │ ├── utils.py │ └── saint_utils.py └── models │ ├── __init__.py │ ├── architectures.py │ ├── dp_wgan.py │ ├── pate_gan.py │ ├── saint_ae.py │ ├── dp_auto_gan.py │ ├── dp_attention_gan.py │ ├── table_diffusion.py │ └── dp_attention_vae.py ├── .gitignore ├── pyproject.toml ├── README.md ├── examples └── example_training_run.ipynb └── LICENSE /tablediffusion/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tablediffusion/config/__init__.py: -------------------------------------------------------------------------------- 1 | from config.configs import datasets 2 | -------------------------------------------------------------------------------- /tablediffusion/metrics/__init__.py: -------------------------------------------------------------------------------- 1 | from metrics.metrics import (alpha_beta_auth, compute_marginal_distances, 2 | pmse_ratio, sra, wasserstein_randomization) 3 | 4 | __all__ = [ 5 | "compute_marginal_distances", 6 | "pmse_ratio", 7 | "sra", 8 | "wasserstein_randomization", 9 | "alpha_beta_auth", 10 | ] 11 | -------------------------------------------------------------------------------- /tablediffusion/vis/__init__.py: -------------------------------------------------------------------------------- 1 | from vis.visualisations import (compare_marginal_scores, visualise_marginals, 2 | visualise_metrics, visualise_pca, 3 | visualise_violins) 4 | 5 | __all__ = [ 6 | "compare_marginal_scores", 7 | "visualise_marginals", 8 | "visualise_metrics", 9 | "visualise_pca", 10 | "visualise_violins", 11 | ] 12 | -------------------------------------------------------------------------------- /tablediffusion/utilities/__init__.py: -------------------------------------------------------------------------------- 1 | from utilities.data_utils import (DataProcessor, calc_norm_dict, 2 | count_parameters, load_and_prep_data) 3 | from utilities.utils import (gather_object_params, run_synthesisers, 4 | set_random_seed, weights_init) 5 | 6 | __all__ = [ 7 | "DataProcessor", 8 | "load_and_prep_data", 9 | "calc_norm_dict", 10 | "count_parameters", 11 | "weights_init", 12 | "gather_object_params", 13 | "set_random_seed", 14 | "run_synthesisers", 15 | ] 16 | -------------------------------------------------------------------------------- /tablediffusion/models/__init__.py: -------------------------------------------------------------------------------- 1 | from models.dp_attention_gan import DPattentionGAN_Synthesiser 2 | from models.dp_attention_vae import DPattentionVAE_Synthesiser 3 | from models.dp_auto_gan import DPautoGAN_Synthesiser 4 | from models.dp_wgan import WGAN_Synthesiser 5 | from models.pate_gan import PATEGAN_Synthesiser 6 | from models.saint_ae import SAINT_AE 7 | from models.table_diffusion import TableDiffusion_Synthesiser 8 | 9 | __all__ = [ 10 | "DPattentionVAE_Synthesiser", 11 | "DPattentionGAN_Synthesiser", 12 | "DPautoGAN_Synthesiser", 13 | "WGAN_Synthesiser", 14 | "PATEGAN_Synthesiser", 15 | "SAINT_AE", 16 | "TableDiffusion_Synthesiser", 17 | ] 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Config files 2 | .python-version 3 | .code 4 | .cursor 5 | .buildt 6 | 7 | # Environment variables file 8 | .env 9 | 10 | # Experiment runs 11 | runs/ 12 | mlruns/ 13 | 14 | # Compressed directories 15 | *.zip 16 | *.gz 17 | *.tar 18 | 19 | # Profiling reports 20 | *.lprof 21 | # Coverage reports 22 | .coverage 23 | 24 | # File for fiddling with code 25 | fiddling.* 26 | 27 | # Mypy caches 28 | .mypy_cache 29 | 30 | # VS Code settings 31 | .vscode 32 | 33 | # Pipfiles 34 | Pipfile* 35 | 36 | # Images 37 | *.png 38 | *.jpg 39 | *.jpeg 40 | 41 | # Compiled Python files 42 | *.pyc 43 | 44 | # ipython checkpoints 45 | .ipynb_checkpoints 46 | 47 | # Folder view configuration files 48 | .DS_Store 49 | Desktop.ini 50 | 51 | # Thumbnail cache files 52 | ._* 53 | Thumbs.db 54 | 55 | # Files that might appear on external disks 56 | .Spotlight-V100 57 | .Trashes 58 | 59 | # Log files 60 | *.log 61 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "TableDiffusion" 3 | version = "1.0" 4 | description = "Differentially-private generative models for sensitive tabular data." 5 | authors = ["Gianluca Truda "] 6 | readme = "README.md" 7 | packages = [{include = "tablediffusion"}] 8 | 9 | [tool.poetry.dependencies] 10 | python = ">=3.10,<3.11" 11 | opacus = "1.4.0" 12 | ctgan = "0.7.2" 13 | torch = ">=1.10.0,<2.0" 14 | mlflow = "^2.3.2" 15 | pandas = "<2.0" 16 | astropy = "^5.3" 17 | matplotlib = "^3.7.1" 18 | pillow = "^9.5.0" 19 | cycler = "^0.11.0" 20 | kiwisolver = "^1.4.4" 21 | pyemd = "^1.0.0" 22 | tqdm = "^4.65.0" 23 | sweetviz = "^2.1.4" 24 | optuna = "^3.1.1" 25 | einops = "^0.6.1" 26 | seaborn = "^0.12.2" 27 | mpl-scatter-density = "^0.7" 28 | prettytable = "^3.7.0" 29 | python-dotenv = "^1.0.0" 30 | jupyterlab = "^4.0.0" 31 | ipython-autotime = "^0.3.1" 32 | plotly = "^5.14.1" 33 | 34 | [tool.poetry.group.dev.dependencies] 35 | black = "*" 36 | flake8 = "*" 37 | isort = "*" 38 | mypy = "*" 39 | ipdb = "^0.13.13" 40 | 41 | [build-system] 42 | requires = ["poetry-core"] 43 | build-backend = "poetry.core.masonry.api" -------------------------------------------------------------------------------- /tablediffusion/config/configs.py: -------------------------------------------------------------------------------- 1 | datasets = { 2 | "uci_adult": { 3 | "path": "UCI_adult/adult.csv", 4 | "sep": ",", 5 | "drop_cols": ["fnlwgt", "education"], 6 | "data_types": [ 7 | ("age", "positive int"), 8 | ("workclass", "categorical"), 9 | ("education-num", "positive int"), 10 | ("marital-status", "categorical"), 11 | ("occupation", "categorical"), 12 | ("relationship", "categorical"), 13 | ("race", "categorical"), 14 | ("sex", "categorical binary"), 15 | ("capital-gain", "positive float"), 16 | ("capital-loss", "positive float"), 17 | ("hours-per-week", "positive int"), 18 | ("native-country", "categorical"), 19 | ("salary", "categorical binary"), 20 | ], 21 | }, 22 | "kaggle_cardio": { 23 | "path": "kaggle_cardio_disease/cardio_train.csv", 24 | "sep": ";", 25 | "drop_cols": ["id"], 26 | "data_types": [ 27 | ("age", "positive int"), 28 | ("gender", "categorical"), 29 | ("height", "positive int"), 30 | ("weight", "positive int"), 31 | ("ap_hi", "positive int"), 32 | ("ap_lo", "positive int"), 33 | ("cholesterol", "categorical"), 34 | ("gluc", "categorical"), 35 | ("smoke", "categorical"), 36 | ("alco", "categorical"), 37 | ("active", "categorical"), 38 | ("cardio", "categorical"), 39 | ], 40 | }, 41 | } 42 | -------------------------------------------------------------------------------- /tablediffusion/utilities/privacy_utils.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copied from https://github.com/opendp/smartnoise-sdk/tree/main/sdk/opendp/smartnoise/synthesizers/pytorch/nn 3 | """ 4 | 5 | import math 6 | 7 | import numpy as np 8 | import torch 9 | 10 | 11 | def pate(data, teachers, lap_scale, device="cpu"): 12 | """PATE implementation for GANs.""" 13 | num_teachers = len(teachers) 14 | labels = torch.Tensor(num_teachers, data.shape[0]).type(torch.int64).to(device) 15 | for i in range(num_teachers): 16 | output = teachers[i](data) 17 | pred = (output > 0.5).type(torch.Tensor).squeeze().to(device) 18 | labels[i] = pred 19 | 20 | votes = torch.sum(labels, dim=0).unsqueeze(1).type(torch.DoubleTensor).to(device) 21 | noise = torch.from_numpy(np.random.laplace(loc=0, scale=1 / lap_scale, size=votes.size())).to( 22 | device 23 | ) 24 | noisy_votes = votes + noise 25 | noisy_labels = (noisy_votes > num_teachers / 2).type(torch.DoubleTensor).to(device) 26 | 27 | return noisy_labels, votes 28 | 29 | 30 | def moments_acc(num_teachers, votes, lap_scale, l_list, device="cpu"): 31 | # TODO docstring 32 | q = (2 + lap_scale * torch.abs(2 * votes - num_teachers)) / ( 33 | 4 * torch.exp(lap_scale * torch.abs(2 * votes - num_teachers)) 34 | ).to(device) 35 | 36 | alpha = [] 37 | for l_val in l_list: 38 | a = 2 * lap_scale**2 * l_val * (l_val + 1) 39 | t_one = (1 - q) * torch.pow((1 - q) / (1 - math.exp(2 * lap_scale) * q), l_val) 40 | t_two = q * torch.exp(2 * lap_scale * l_val) 41 | t = t_one + t_two 42 | alpha.append(torch.clamp(t, max=a).sum()) 43 | 44 | return torch.DoubleTensor(alpha).to(device) 45 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TableDiffusion 2 | [![arxivbadge](https://img.shields.io/badge/arXiv-2308.14784-green)](https://arxiv.org/abs/2308.14784) 3 | [![githubbadge](https://img.shields.io/badge/Github-TableDiffusion-black)](https://github.com/gianlucatruda/TableDiffusion) 4 | [![blogbadge](https://img.shields.io/badge/gianluca.ai-projects-blue)](https://gianluca.ai/table-diffusion) 5 | 6 | This is the supporting code for the paper [Generating tabular datasets under differential privacy](https://arxiv.org/abs/2308.14784). 7 | 8 | Please check out a quick overview on [my blog](http://gianluca.ai/table-diffusion). 9 | 10 | TableDiffusion is a project focused on providing differentially-private generative models for sensitive tabular data. The goal is to enable the synthesis of data that maintains the statistical properties of the original dataset while ensuring the privacy of individuals' information. 11 | 12 | The most notable model from this work is `TableDiffusion`, the first differentially-private diffusion model for tabular data. See [tablediffusion/models/table_diffusion.py](tablediffusion/models/table_diffusion.py) 13 | 14 | > :warning: **Disclaimer**: This codebase is intended for research purposes only and is not ready for production use. The current implementation may not preserve privacy guarantees due to seed and sampler settings that are not suitable for a production environment. 15 | 16 | 17 | ## Paper explanation on YouTube 18 | 19 | [https://youtu.be/2QRrGWoXOb4](https://youtu.be/2QRrGWoXOb4) 20 | 21 | [![Paper presentation on YouTube](https://img.youtube.com/vi/2QRrGWoXOb4/0.jpg)](https://www.youtube.com/watch?v=2QRrGWoXOb4) 22 | 23 | 24 | ## Citing this work 25 | 26 | Truda, Gianluca. "Generating tabular datasets under differential privacy." arXiv preprint arXiv:2308.14784 (2023). 27 | 28 | ``` 29 | @article{truda2023generating, 30 | title={Generating tabular datasets under differential privacy}, 31 | author={Truda, Gianluca}, 32 | journal={arXiv preprint arXiv:2308.14784}, 33 | year={2023} 34 | } 35 | ``` 36 | -------------------------------------------------------------------------------- /tablediffusion/models/architectures.py: -------------------------------------------------------------------------------- 1 | """ 2 | Shared network classes for Generator, Discriminator, etc. 3 | """ 4 | 5 | import torch 6 | from torch import nn 7 | 8 | 9 | class Discriminator(nn.Module): 10 | """Based on the CTGAN implementation at 11 | https://github.com/sdv-dev/CTGAN/blob/master/ctgan/synthesizers/ctgan.py 12 | """ 13 | 14 | def __init__(self, input_dim, dis_dims=(256, 256), pack=1): 15 | super().__init__() 16 | dim = input_dim * pack 17 | self.pack = pack 18 | self.packdim = dim 19 | seq = [] 20 | for item in list(dis_dims): 21 | seq += [nn.Linear(dim, item), nn.LeakyReLU(0.2), nn.Dropout(0.5)] 22 | dim = item 23 | 24 | seq += [nn.Linear(dim, 1)] 25 | seq += [nn.Sigmoid()] 26 | self.seq = nn.Sequential(*seq) 27 | 28 | def forward(self, x): 29 | # assert input.size()[0] % self.pack == 0 30 | return self.seq(x.view(-1, self.packdim)) 31 | 32 | 33 | class Residual(nn.Module): 34 | """Residual layer""" 35 | 36 | def __init__(self, i, o): 37 | super().__init__() 38 | self.fc = nn.Linear(i, o) 39 | # self.bn = nn.BatchNorm1d(o) 40 | self.bn = nn.GroupNorm(1, o) # Use privacy-safe groupnorm over batchnorm 41 | self.relu = nn.ReLU() 42 | 43 | def forward(self, x): 44 | out = self.fc(x) 45 | out = self.bn(out) 46 | out = self.relu(out) 47 | return torch.cat([out, x], dim=1) 48 | 49 | 50 | class Generator(nn.Module): 51 | """Based on the CTGAN implementation at 52 | https://github.com/sdv-dev/CTGAN/blob/master/ctgan/synthesizers/ctgan.py 53 | """ 54 | 55 | def __init__(self, embedding_dim, data_dim, gen_dims=(256, 256)): 56 | super().__init__() 57 | dim = embedding_dim 58 | seq = [] 59 | for item in list(gen_dims): 60 | seq += [Residual(dim, item)] 61 | dim += item 62 | seq.append(nn.Linear(dim, data_dim)) 63 | self.seq = nn.Sequential(*seq) 64 | 65 | def forward(self, x): 66 | return self.seq(x) 67 | 68 | 69 | class Encoder(nn.Module): 70 | """Encoder for the TVAESynthesizer. 71 | 72 | Args: 73 | data_dim (int): 74 | Dimensions of the data. 75 | compress_dims (tuple or list of ints): 76 | Size of each hidden layer. 77 | embedding_dim (int): 78 | Size of the output vector. 79 | """ 80 | 81 | def __init__(self, data_dim, compress_dims, embedding_dim): 82 | super().__init__() 83 | dim = data_dim 84 | seq = [] 85 | for item in list(compress_dims): 86 | seq += [nn.Linear(dim, item), nn.ReLU()] 87 | dim = item 88 | 89 | self.seq = nn.Sequential(*seq) 90 | self.fc1 = nn.Linear(dim, embedding_dim) 91 | self.fc2 = nn.Linear(dim, embedding_dim) 92 | 93 | def forward(self, input_): 94 | """Encode the passed `input_`.""" 95 | feature = self.seq(input_) 96 | mu = self.fc1(feature) 97 | logvar = self.fc2(feature) 98 | std = torch.exp(0.5 * logvar) 99 | return mu, std, logvar 100 | 101 | 102 | class Decoder(nn.Module): 103 | """Decoder for the TVAESynthesizer. 104 | 105 | Args: 106 | embedding_dim (int): 107 | Size of the input vector. 108 | decompress_dims (tuple or list of ints): 109 | Size of each hidden layer. 110 | data_dim (int): 111 | Dimensions of the data. 112 | """ 113 | 114 | def __init__(self, embedding_dim, decompress_dims, data_dim): 115 | super(Decoder, self).__init__() 116 | dim = embedding_dim 117 | seq = [] 118 | for item in list(decompress_dims): 119 | seq += [nn.Linear(dim, item), nn.ReLU()] 120 | dim = item 121 | 122 | seq.append(nn.Linear(dim, data_dim)) 123 | self.seq = nn.Sequential(*seq) 124 | self.sigma = nn.Parameter(torch.ones(data_dim) * 0.1) 125 | 126 | def forward(self, input_): 127 | """Decode the passed `input_`.""" 128 | return self.seq(input_), self.sigma 129 | -------------------------------------------------------------------------------- /tablediffusion/utilities/data_utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | from pathlib import Path 3 | 4 | import numpy as np 5 | import pandas as pd 6 | from config import datasets 7 | from prettytable import PrettyTable 8 | from sklearn.preprocessing import LabelBinarizer, MinMaxScaler 9 | 10 | 11 | def load_and_prep_data(dataset="uci_adult", datadir="../data", verbose=False): 12 | """Loads the specified dataset. Returns X, X_tx, processor""" 13 | 14 | if dataset not in datasets.keys(): 15 | raise ValueError(f"'{dataset}' is not a valid dataset.") 16 | 17 | datadir = Path(datadir) 18 | if not os.path.exists(datadir): 19 | raise ValueError(f"'{datadir}' not found.") 20 | 21 | # load parameters for specified dataset 22 | data_params = datasets[dataset] 23 | 24 | # Load the dataset 25 | path = Path(datadir) / data_params["path"] 26 | X = pd.read_csv(path, sep=data_params["sep"]).drop(data_params["drop_cols"], axis=1) 27 | if verbose: 28 | print(f"Loaded {dataset} dataset {X.shape} from {path}") 29 | 30 | # Transform dataset 31 | if verbose: 32 | print("Transforming dataset...") 33 | processor = DataProcessor(data_params["data_types"]).fit(X) 34 | X_tx = processor.transform(X.values) 35 | if verbose: 36 | print(f"Data is now {X_tx.shape}") 37 | 38 | # Transform the pandas columns into the correct data types 39 | for col, dtype in data_params["data_types"]: 40 | if dtype == "categorical": 41 | X[col] = X[col].astype("object") 42 | elif dtype == "numerical": 43 | X[col] = X[col].astype("float") 44 | if verbose: 45 | print(X.value_counts()) 46 | 47 | return X, X_tx, processor 48 | 49 | 50 | def calc_norm_dict(model, ord=1, errors="ignore", no_biases=True): 51 | """Calculate the norm of order `ord` for weights and gradients in 52 | each layer of model, returned as a dictionary. 53 | """ 54 | _norm_dict = {} 55 | _mod_name = model.__class__.__name__ 56 | for name, parameter in model.named_parameters(): 57 | if not parameter.requires_grad: 58 | continue 59 | if no_biases and "bias" in name: 60 | continue 61 | try: 62 | _norm_dict[f"{_mod_name}.{name}.weight_norm"] = parameter.data.norm(ord).item() 63 | _norm_dict[f"{_mod_name}.{name}.grad_norm"] = parameter.grad.norm(ord).item() 64 | except Exception as e: 65 | if errors != "ignore": 66 | raise e 67 | 68 | return _norm_dict 69 | 70 | 71 | def count_parameters(model, verbose=False): 72 | """Count learnable parameters in a torch model. 73 | Modified from https: // stackoverflow.com/a/62508086 74 | """ 75 | 76 | table = PrettyTable(["Modules", "Parameters"]) 77 | total_params = 0 78 | for name, parameter in model.named_parameters(): 79 | if not parameter.requires_grad: 80 | continue 81 | param = parameter.numel() 82 | table.add_row([name, param]) 83 | total_params += param 84 | if verbose: 85 | print(table) 86 | print(f"Total Trainable Params: {total_params}") 87 | return total_params 88 | 89 | 90 | class DataProcessor: 91 | """ 92 | Extended from: 93 | https://github.com/DPautoGAN/DPautoGAN/blob/master/uci/uci.ipynb 94 | """ 95 | 96 | def __init__(self, datatypes): 97 | self.datatypes = datatypes 98 | 99 | def fit(self, df: pd.DataFrame): 100 | matrix = df.values 101 | 102 | preprocessors, cutoffs = [], [] 103 | for i, (_, datatype) in enumerate(self.datatypes): 104 | preprocessed_col = matrix[:, i].reshape(-1, 1) 105 | 106 | if "categorical" in datatype: 107 | preprocessor = LabelBinarizer() 108 | else: 109 | preprocessor = MinMaxScaler() 110 | 111 | preprocessed_col = preprocessor.fit_transform(preprocessed_col) 112 | cutoffs.append(preprocessed_col.shape[1]) 113 | preprocessors.append(preprocessor) 114 | 115 | self.cutoffs = cutoffs 116 | self.preprocessors = preprocessors 117 | self.col_names = [c for (c, _) in self.datatypes] 118 | 119 | return self 120 | 121 | def transform(self, data) -> np.ndarray: 122 | if isinstance(data, pd.DataFrame): 123 | data = data.values 124 | 125 | preprocessed_cols = [] 126 | 127 | for i, _ in enumerate(self.datatypes): 128 | preprocessed_col = data[:, i].reshape(-1, 1) 129 | preprocessed_col = self.preprocessors[i].transform(preprocessed_col) 130 | preprocessed_cols.append(preprocessed_col) 131 | 132 | return np.concatenate(preprocessed_cols, axis=1) 133 | 134 | def fit_transform(self, df: pd.DataFrame) -> np.ndarray: 135 | self.fit(df) 136 | return self.transform(df) 137 | 138 | def inverse_transform(self, data) -> pd.DataFrame: 139 | if isinstance(data, pd.DataFrame): 140 | data = data.values 141 | 142 | postprocessed_cols = [] 143 | 144 | j = 0 145 | for i, (_, datatype) in enumerate(self.datatypes): 146 | postprocessed_col = self.preprocessors[i].inverse_transform( 147 | data[:, j : j + self.cutoffs[i]] 148 | ) 149 | 150 | if "categorical" in datatype: 151 | postprocessed_col = postprocessed_col.reshape(-1, 1) 152 | else: 153 | if "positive" in datatype: 154 | postprocessed_col = postprocessed_col.clip(min=0) 155 | 156 | if "int" in datatype: 157 | postprocessed_col = postprocessed_col.round() 158 | 159 | postprocessed_cols.append(postprocessed_col) 160 | 161 | j += self.cutoffs[i] 162 | 163 | return pd.DataFrame( 164 | np.concatenate(postprocessed_cols, axis=1), columns=self.col_names 165 | ).apply(pd.to_numeric, errors="ignore") 166 | -------------------------------------------------------------------------------- /tablediffusion/utilities/utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | import random 3 | from pathlib import Path 4 | 5 | import git 6 | import mlflow 7 | import numpy as np 8 | import pandas as pd 9 | import torch 10 | from mlflow.tracking import MlflowClient 11 | from torch import nn 12 | from tqdm import tqdm 13 | from utilities import load_and_prep_data 14 | 15 | 16 | def weights_init(m): 17 | # TODO docstring 18 | if isinstance(m, nn.Linear): 19 | nn.init.xavier_uniform_(m.weight) 20 | 21 | 22 | def gather_object_params(obj, prefix="", clip=249): 23 | # TODO docstring 24 | return { 25 | prefix + k: str(v)[:clip] if len(str(v)) > clip else v for k, v in obj.__dict__.items() 26 | } 27 | 28 | 29 | def set_random_seed(seed=None): 30 | """Sets randomisation seed for math, np, torch.""" 31 | 32 | # Generate random seed if none specified 33 | if seed is None: 34 | seed = np.random.randint(10000) 35 | 36 | # Apply the random seed 37 | random.seed(seed) 38 | np.random.seed(seed) 39 | torch.manual_seed(seed) 40 | 41 | 42 | def run_synthesisers( 43 | datasets, 44 | synthesisers, 45 | exp_name, 46 | exp_id, 47 | datadir, 48 | repeats=3, 49 | repodir="./", 50 | epsilon_values=[1.0], 51 | generate_fakes=True, 52 | fake_sample_path=None, 53 | fake_data_path=None, 54 | with_benchmark=False, 55 | ctgan_epochs=30, 56 | cuda=True, 57 | metaseed=42, 58 | ): 59 | # TODO docstring 60 | 61 | datadir = Path(datadir) 62 | if not os.path.exists(datadir): 63 | raise RuntimeError(f"{datadir} does not exist") 64 | 65 | # Make any directories that will be needed if they don't exist 66 | if fake_data_path is not None and not os.path.exists(fake_data_path): 67 | os.makedirs(fake_data_path) 68 | if fake_sample_path is not None and not os.path.exists(fake_sample_path): 69 | os.makedirs(fake_sample_path) 70 | 71 | if cuda: 72 | cuda = bool(torch.cuda.is_available()) 73 | print(f"CUDA status: {cuda}") 74 | 75 | # Generate random seeds for each repeat from `metaseed` 76 | np.random.seed(metaseed) 77 | _seeds = np.random.randint(10000, size=repeats) 78 | 79 | repo = git.Repo(repodir) 80 | githash = str(repo.head.object.hexsha) 81 | gitmessage = str(repo.head.object.message) 82 | gitbranch = str(repo.active_branch) 83 | git_remote_url = str(repo.remotes.origin.url) 84 | 85 | client = MlflowClient() 86 | client.set_experiment_tag( 87 | exp_id, "mlflow.note.content", f"{gitbranch}:{githash[:6]}:{gitmessage}" 88 | ) 89 | 90 | for repeat in tqdm(range(1, repeats + 1), desc="Repeats", leave=True, colour="red"): 91 | 92 | # Determine random seed for the repeat (from metaseed) 93 | _seed = _seeds[repeat - 1] 94 | set_random_seed(_seed) 95 | 96 | for dataset, data_params in datasets.items(): 97 | 98 | # Load and transform dataset (privately?) 99 | path = datadir / data_params["path"] 100 | X, _X, processor = load_and_prep_data(dataset=dataset, datadir=datadir, verbose=False) 101 | disc_cols = [c for c, dtype in data_params["data_types"] if "categorical" in dtype] 102 | print(f"Loaded {dataset} dataset {X.shape} from {path}") 103 | 104 | if with_benchmark and fake_data_path is not None: 105 | print("Benchmarking with CTGAN...") 106 | from ctgan.synthesizers import CTGAN as CTGANSynthesizer 107 | 108 | ctgan = CTGANSynthesizer(epochs=ctgan_epochs, cuda=cuda) 109 | ctgan.fit(train_data=X, discrete_columns=disc_cols) 110 | X_fake_benchmark = ctgan.sample(X.shape[0]) 111 | print("Saving fake data...") 112 | pd.DataFrame(X_fake_benchmark).to_csv( 113 | Path(fake_data_path) / f"fake_{dataset}_CTGAN_Synthesiser_0.0_{repeat}.csv", 114 | index=False, 115 | ) 116 | 117 | for eps in tqdm(epsilon_values, desc="Epsilon", leave=True, colour="green"): 118 | 119 | for _synth, (synth, init_params, fit_params, extra_params) in tqdm( 120 | synthesisers.items(), desc="Synths" 121 | ): 122 | 123 | raw_data = extra_params.get("use_raw_data", False) 124 | 125 | run_name = f"{exp_name}_{dataset}_{_synth}_{eps}_{repeat}" 126 | 127 | with mlflow.start_run(run_name=run_name, experiment_id=exp_id): 128 | 129 | mlflow.set_tags( 130 | { 131 | "mlflow.source.git.commit": githash, 132 | "mlflow.source.git.branch": gitbranch, 133 | "mlflow.source.git.repoURL": git_remote_url, 134 | "mlflow.note.content": f"{gitbranch}:{githash[:6]}:{gitmessage}", 135 | "synthesiser": _synth, 136 | "repeat": f"{repeat}/{repeats}", 137 | "random_seed.run": _seed, 138 | "random_seed.meta": metaseed, 139 | "random_seed.seeds": _seeds, 140 | } 141 | ) 142 | 143 | mlflow.log_params( 144 | { 145 | "gpu_properties": str(torch.cuda.get_device_properties(0)) 146 | if cuda 147 | else "cpu", 148 | "dataset.dataset_name": str(dataset), 149 | "dataset.shape_raw": X.shape, 150 | "dataset.shape_transformed": _X.shape, 151 | "dataset.drop_cols": list(data_params["drop_cols"]), 152 | "dataset.disc_cols": list(disc_cols), 153 | "init_params": init_params, 154 | "fit_params": fit_params, 155 | "extra_params": extra_params, 156 | } 157 | ) 158 | 159 | print(f"Training {_synth} on {dataset} with epsilon={eps}...") 160 | 161 | try: 162 | # Re-initialise the model and customise budget 163 | model = synth(cuda=cuda, epsilon_target=eps, **init_params) 164 | 165 | # Fit the synth on the dataset 166 | if raw_data: 167 | model = model.fit( 168 | X.copy(), epsilon=eps, discrete_columns=disc_cols, **fit_params 169 | ) 170 | else: 171 | model = model.fit(_X.copy(), epsilon=eps, **fit_params) 172 | 173 | mlflow.log_metrics( 174 | {"epsilon": model._eps, "elapsed_batches": model._elapsed_batches}, 175 | step=model._elapsed_batches, 176 | ) 177 | 178 | if generate_fakes: 179 | # Generate fake dataset 180 | print("Generating fake data...") 181 | X_fake = pd.DataFrame(model.sample(_X.shape[0])) 182 | 183 | if not raw_data: 184 | # Reverse the transformation 185 | X_fake = pd.DataFrame( 186 | processor.inverse_transform(X_fake.values), 187 | columns=X.columns, 188 | ) 189 | 190 | # Log samples and stats for fake data to MLflow 191 | pd.set_option("display.max_columns", 200) 192 | mlflow.log_text( 193 | str(X_fake.describe(include="all")), 194 | f"fake_stats_{dataset}_{_synth}_{eps}.txt", 195 | ) 196 | pd.set_option("display.max_columns", None) 197 | if fake_sample_path is not None: 198 | _sample_path = f"{fake_sample_path}/fake_sample_{dataset}_{_synth}_{eps}_{repeat}.txt" 199 | X_fake.sample(30).to_csv(_sample_path, index=False) 200 | mlflow.log_artifact(_sample_path, "samples") 201 | 202 | if fake_data_path is not None: 203 | # Save fake dataset 204 | print("Saving fake data...") 205 | X_fake.to_csv( 206 | Path(fake_data_path) 207 | / f"fake_{dataset}_{_synth}_{eps}_{repeat}.csv", 208 | index=False, 209 | ) 210 | 211 | except Exception as e: 212 | mlflow.set_tag("error", f"{e}\t{e.args}") 213 | raise e 214 | -------------------------------------------------------------------------------- /tablediffusion/models/dp_wgan.py: -------------------------------------------------------------------------------- 1 | """ 2 | Based on WGAN GP implementation from 3 | https://github.com/eriklindernoren/PyTorch-GAN/blob/master/implementations/wgan_gp/wgan_gp.py 4 | """ 5 | 6 | import mlflow 7 | import numpy as np 8 | import torch 9 | from models.architectures import Discriminator, Generator 10 | from opacus import PrivacyEngine 11 | from torch.autograd import Variable 12 | from torch.utils.data import DataLoader, Dataset 13 | from utilities import * 14 | 15 | 16 | class MyDataset(Dataset): 17 | def __init__(self, data): 18 | self.data = data 19 | 20 | def return_data(self): 21 | return self.data 22 | 23 | def __len__(self): 24 | return self.data.shape[0] 25 | 26 | def __getitem__(self, idx): 27 | if torch.is_tensor(idx): 28 | idx = idx.tolist() 29 | 30 | X = self.data[idx, :] 31 | return torch.as_tensor(X, dtype=torch.float64) 32 | 33 | 34 | class WGAN_Synthesiser: 35 | def __init__( 36 | self, 37 | batch_size=64, 38 | gen_lr=2e-4, 39 | dis_lr=2e-4, 40 | b1=0.5, 41 | b2=0.999, 42 | latent_dim=100, 43 | gen_dims=(256, 256), 44 | dis_dims=(256, 256), 45 | n_critic=5, 46 | max_grad_norm=1.0, 47 | epsilon_target=5, 48 | epoch_target=200, 49 | delta=1e-5, 50 | mlflow_logging=True, 51 | cuda=True, 52 | ): 53 | 54 | # Setting up GPU (if available and specified) 55 | if cuda: 56 | assert torch.cuda.is_available() 57 | self.cuda = cuda 58 | self.device = torch.device("cuda:0" if torch.cuda.is_available() and cuda else "cpu") 59 | 60 | # Hyperparameters 61 | self.batch_size = batch_size 62 | self.gen_lr = gen_lr 63 | self.dis_lr = dis_lr 64 | self.b1 = b1 65 | self.b2 = b2 66 | self.latent_dim = latent_dim 67 | self.gen_dims = gen_dims 68 | self.dis_dims = dis_dims 69 | self.n_critic = n_critic 70 | self.max_grad_norm = max_grad_norm 71 | self.epoch_target = epoch_target 72 | 73 | # Setting privacy budget 74 | self.epsilon_target = epsilon_target 75 | self._delta = delta 76 | 77 | # Logging to MLflow 78 | self.mlflow_logging = mlflow_logging 79 | if self.mlflow_logging: 80 | _param_dict = gather_object_params(self, prefix="init.") 81 | mlflow.log_params(_param_dict) 82 | 83 | # Initialise training variables 84 | self._elapsed_batches = 0 85 | self._elapsed_epochs = 0 86 | self._epsilon = epsilon_target 87 | self._eps = 0 88 | 89 | def fit(self, train_data, n_epochs=10, epsilon=100, verbose=True): 90 | 91 | self._epsilon = epsilon 92 | self.data_dim = train_data.shape[-1] 93 | self.data_n = train_data.shape[0] 94 | 95 | if not isinstance(train_data, DataLoader): 96 | train_data = DataLoader( 97 | MyDataset(train_data), batch_size=self.batch_size, drop_last=True 98 | ) 99 | 100 | Tensor = torch.cuda.FloatTensor if self.cuda else torch.FloatTensor 101 | 102 | # Check if training for first time or continuing (don't reinitialise) 103 | if self._elapsed_batches == 0: 104 | 105 | # Initialize generator and discriminator 106 | self.G = Generator(self.latent_dim, self.data_dim, gen_dims=self.gen_dims).to( 107 | self.device 108 | ) 109 | self.D = Discriminator(self.data_dim, dis_dims=self.dis_dims).to(self.device) 110 | 111 | self._nparams_g = count_parameters(self.G) 112 | self._nparams_d = count_parameters(self.D) 113 | 114 | if self.mlflow_logging: 115 | mlflow.log_params( 116 | { 117 | "nparams.G": self._nparams_g, 118 | "nparams.D": self._nparams_d, 119 | "nparams.total": self._nparams_g + self._nparams_d, 120 | } 121 | ) 122 | _model_desc = str(self.G) + "\n" + str(self.D) 123 | mlflow.log_text(_model_desc, "model_desription.txt") 124 | 125 | # Initialise optimisers 126 | self.optim_G = torch.optim.Adam( 127 | self.G.parameters(), lr=self.gen_lr, betas=(self.b1, self.b2) 128 | ) 129 | self.optim_D = torch.optim.Adam( 130 | self.D.parameters(), lr=self.dis_lr, betas=(self.b1, self.b2) 131 | ) 132 | 133 | self.privacy_engine = PrivacyEngine(accountant="rdp", secure_mode=False) 134 | self.D, self.optim_D, train_data = self.privacy_engine.make_private_with_epsilon( 135 | module=self.D, 136 | optimizer=self.optim_D, 137 | data_loader=train_data, 138 | target_epsilon=self.epsilon_target, 139 | target_delta=self._delta, 140 | epochs=self.epoch_target, 141 | max_grad_norm=self.max_grad_norm, 142 | poisson_sampling=True, 143 | # alphas=[1 + x / 10.0 for x in range(1, 100)] + list(range(12, 64)), 144 | ) 145 | 146 | # Log privacy engine and optimiser parameters 147 | if self.mlflow_logging: 148 | _param_dict = gather_object_params(self.privacy_engine, prefix="privacy_engine_D.") 149 | mlflow.log_params(_param_dict) 150 | _param_dict = gather_object_params(self.optim_D, prefix="optim_D.") 151 | mlflow.log_params(_param_dict) 152 | 153 | # Enforce training mode 154 | self.G.train() 155 | self.D.train() 156 | 157 | for epoch in range(n_epochs): 158 | self._elapsed_epochs += 1 159 | for i, X in enumerate(train_data): 160 | self._eps = self.privacy_engine.get_epsilon(self._delta) 161 | if self._eps >= self._epsilon: 162 | print(f"Privacy budget reached in epoch {epoch}") 163 | return self 164 | 165 | self._elapsed_batches += 1 166 | 167 | # Configure input 168 | real_X = Variable(X.type(Tensor)) 169 | 170 | # --------------------- 171 | # Train Discriminator 172 | # --------------------- 173 | 174 | self.optim_D.zero_grad() 175 | 176 | # Sample noise as generator input 177 | z = Variable(Tensor(np.random.normal(0, 1, (X.shape[0], self.latent_dim)))) 178 | 179 | # Generate a batch of samples 180 | fake_X = self.G(z) 181 | 182 | # Real samples 183 | real_validity = self.D(real_X) 184 | # Fake samples 185 | fake_validity = self.D(fake_X) 186 | 187 | # Adversarial loss 188 | d_loss = -torch.mean(real_validity) + torch.mean(fake_validity) 189 | 190 | d_loss.backward() 191 | self.optim_D.step() 192 | 193 | # ----------------- 194 | # Train Generator 195 | # ----------------- 196 | self.optim_G.zero_grad() 197 | # Train the generator every n_critic steps 198 | if i % self.n_critic == 0: 199 | 200 | # Generate a batch of images 201 | fake_X = self.G(z) 202 | # Loss measures generator's ability to fool the discriminator 203 | # Train on fake images 204 | fake_validity = self.D(fake_X) 205 | g_loss = -torch.mean(fake_validity) 206 | 207 | g_loss.backward() 208 | self.optim_G.step() 209 | 210 | if i % 300 == 0 and verbose: 211 | print( 212 | ( 213 | f"[Epoch {epoch}/{n_epochs}] " 214 | f"[Batch {i}/{len(train_data)}] " 215 | f"[D loss: {d_loss.item():.4f}] " 216 | f"[G loss: {g_loss.item():.4f}]" 217 | ) 218 | ) 219 | print(f"Epsilon: {self._eps:.3f}") 220 | 221 | if i % 20 == 0 and self.mlflow_logging: 222 | mlflow.log_metrics( 223 | { 224 | "elapsed_batches": self._elapsed_batches, 225 | "elapsed_epochs": self._elapsed_epochs, 226 | "train_loss.G": g_loss.item(), 227 | "train_loss.D": d_loss.item(), 228 | "used_epsilon.D": self._eps, 229 | "used_epsilon.total": self._eps, 230 | "validity.fake": fake_validity.mean().item(), 231 | "validity.real": real_validity.mean().item(), 232 | }, 233 | step=self._elapsed_batches, 234 | ) 235 | # Weight and Grad norms for G and D 236 | _g_norm_dict = calc_norm_dict(self.G) 237 | mlflow.log_metrics(_g_norm_dict, step=self._elapsed_batches) 238 | _d_norm_dict = calc_norm_dict(self.D) 239 | mlflow.log_metrics(_d_norm_dict, step=self._elapsed_batches) 240 | # Diversity of fakes from G and real data 241 | mlflow.log_metrics( 242 | { 243 | "X_fake.norm": fake_X.norm().item(), 244 | "X_real.norm": real_X.norm().item(), 245 | }, 246 | step=self._elapsed_batches, 247 | ) 248 | 249 | return self 250 | 251 | def sample(self, n=None): 252 | self.G.eval() 253 | n = self.batch_size if n is None else n 254 | Tensor = torch.cuda.FloatTensor if self.cuda else torch.FloatTensor 255 | with torch.no_grad(): 256 | # Sample noise as generator input 257 | z = Variable(Tensor(np.random.normal(0, 1, (n, self.latent_dim)))) 258 | 259 | output = self.G(z).detach().cpu() 260 | self.G.train() 261 | 262 | return output 263 | -------------------------------------------------------------------------------- /tablediffusion/metrics/metrics.py: -------------------------------------------------------------------------------- 1 | import warnings 2 | from collections import Counter, defaultdict 3 | 4 | import numpy as np 5 | import pandas as pd 6 | from pyemd import emd_samples 7 | from scipy.stats import chisquare, ks_2samp 8 | from sklearn.linear_model import LogisticRegression 9 | from sklearn.model_selection import train_test_split 10 | from sklearn.neighbors import NearestNeighbors 11 | 12 | 13 | def _get_frequencies(real, synthetic): 14 | """Get percentual frequencies for each possible real categorical value. 15 | 16 | Based on https://github.com/sdv-dev/SDMetrics/blob/926bc8c276a7fc9dbc700d8f4a26947300343c7e/sdmetrics/utils.py#L40 17 | 18 | Given two iterators containing categorical data, this transforms it into 19 | observed/expected frequencies which can be used for statistical tests. It 20 | adds a regularization term to handle cases where the synthetic data contains 21 | values that don't exist in the real data. 22 | """ 23 | f_obs, f_exp = [], [] 24 | real, synthetic = defaultdict(float, Counter(real)), defaultdict(float, Counter(synthetic)) 25 | 26 | # Calculate the sums outside the loop for efficiency. 27 | real_total, synthetic_total = sum(real.values()), sum(synthetic.values()) 28 | 29 | for value in synthetic: 30 | real[value] += 1e-9 # Regularization to prevent NaN. 31 | 32 | for value in real: 33 | f_obs.append(synthetic[value] / synthetic_total) 34 | f_exp.append(real[value] / real_total) 35 | 36 | return f_obs, f_exp 37 | 38 | 39 | def compute_marginal_distances(real_dataset: pd.DataFrame, fake_dataset: pd.DataFrame, data_types): 40 | # TODO docstring 41 | scores = {} 42 | for _, (col, var_type) in enumerate(data_types): 43 | if "categorical" in var_type or "int" in var_type: 44 | # Inverted Chi-squared test (0.0 is best, 1.0 is worst) 45 | _fakes = fake_dataset[col] 46 | if "int" in var_type: 47 | _fakes.round(0) 48 | freq_obs, freq_exp = _get_frequencies(real_dataset[col], _fakes) 49 | if len(freq_obs) == len(freq_exp) == 1: 50 | pvalue = 1.0 51 | else: 52 | _, pvalue = chisquare(freq_obs, freq_exp) 53 | result = 1 - pvalue 54 | 55 | elif "float" in var_type: 56 | # Kolmogorov-Smirnov distance (0.0 is best, 1.0 is worst) 57 | statistic, _ = ks_2samp(real_dataset[col].fillna(0), fake_dataset[col].fillna(0)) 58 | result = statistic 59 | else: 60 | warnings.warn(f"'{col}' is not a recognised type ({var_type}), ignoring...") 61 | 62 | scores[col] = result 63 | 64 | return pd.Series(scores) 65 | 66 | 67 | def pmse_ratio(data, synthetic_data): 68 | """ 69 | In order to determine how similar the synthetic and real data are 70 | to each other (general quality of synthetic) we can train a 71 | discriminator to attempt to distinguish between real and 72 | synthetic. The poorer the performance of the discriminator, the 73 | more similar the two datasets are. 74 | From "Really Useful Synthetic Data 75 | A Framework To Evaluate The Quality Of 76 | Differentially Private Synthetic Data" 77 | https://arxiv.org/pdf/2004.07740.pdf 78 | :param data: Original data 79 | :type data: pandas DataFrame 80 | :param synthetic_data: Synthetic data we are analyzing 81 | :type synthetic_data: pandas DataFrame 82 | :return: ratio (pmse score) 83 | :rtype: float 84 | """ 85 | n1 = data.shape[0] 86 | n2 = synthetic_data.shape[0] 87 | comb = ( 88 | pd.concat([data, synthetic_data], axis=0, keys=[0, 1]) 89 | .reset_index(level=[0]) 90 | .rename(columns={"level_0": "indicator"}) 91 | ) 92 | X_comb = comb.drop("indicator", axis=1) 93 | y_comb = comb["indicator"] 94 | X_train, X_test, y_train, y_test = train_test_split( 95 | X_comb, y_comb, test_size=0.33, random_state=42 96 | ) 97 | clf = LogisticRegression(random_state=0, max_iter=1000).fit(X_train, y_train) 98 | score = clf.predict_proba(X_comb)[:, 1] 99 | observed_utility = sum((score - n2 / (n1 + n2)) ** 2) / (n1 + n2) 100 | expected_utility = clf.coef_.shape[1] * (n1 / (n1 + n2)) ** 2 * (n2 / (n1 + n2)) / (n1 + n2) 101 | return observed_utility / expected_utility 102 | 103 | 104 | def sra(real, synth): 105 | """ 106 | SRA can be thought of as the (empirical) probability of a 107 | comparison on the synthetic data being ”correct” (i.e. the same as 108 | the comparison would be on the real data). 109 | From "Measuring the quality of Synthetic data for use in competitions" 110 | https://arxiv.org/pdf/1806.11345.pdf 111 | (NOTE: SRA requires at least 2 accuracies per list to work) 112 | :param real: list of accuracies on models of real data 113 | :type real: list of floats 114 | :param synth: list of accuracies on models of synthetic data 115 | :type synth: list of floats 116 | :return: sra score 117 | :rtype: float 118 | """ 119 | k = len(real) 120 | sum_I = 0 121 | for i in range(k): 122 | R_vals = np.array([real[i] - rj if i != k else None for k, rj in enumerate(real)]) 123 | S_vals = np.array([synth[i] - sj if i != k else None for k, sj in enumerate(synth)]) 124 | I = R_vals[R_vals != np.array(None)] * S_vals[S_vals != np.array(None)] 125 | I[I >= 0] = 1 126 | I[I < 0] = 0 127 | sum_I += I 128 | return np.sum((1 / (k * (k - 1))) * sum_I) 129 | 130 | 131 | def wasserstein_randomization(d1_large, d2_large, iters=10, downsample_size=100): 132 | """ 133 | Combine synthetic and real data into two sets and randomly 134 | divide the data into two new random sets. Check the wasserstein 135 | distance (earth movers distance) between these two new muddled sets. 136 | Use the measured wasserstein distance to compute the ratio between 137 | it and the median of the null distribution (earth movers distance on 138 | original set). A ratio of 0 would indicate that the two marginal 139 | distributions are identical. 140 | From "REALLY USEFUL SYNTHETIC DATA 141 | A FRAMEWORK TO EVALUATE THE QUALITY OF 142 | DIFFERENTIALLY PRIVATE SYNTHETIC DATA" 143 | https://arxiv.org/pdf/2004.07740.pdf 144 | NOTE: We return the mean here. However, its best 145 | probably to analyze the distribution of the wasserstein score 146 | :param d1_large: real data 147 | :type d1_large: pandas DataFrame 148 | :param d2_large: fake data 149 | :type d2_large: pandas DataFrame 150 | :param iters: how many iterations to run the randomization 151 | :type iters: int 152 | :param downsample_size: we downsample the original datasets due 153 | to memory constraints 154 | :type downsample_size: int 155 | :return: wasserstein randomization mean 156 | :rtype: float 157 | """ 158 | # pip install pyemd 159 | # https://github.com/wmayner/pyemd 160 | 161 | assert len(d1_large) == len(d2_large) 162 | d1 = d1_large.sample(n=downsample_size) 163 | d2 = d2_large.sample(n=downsample_size) 164 | l_1 = len(d1) 165 | d3 = np.concatenate((d1, d2)) 166 | distances = [] 167 | for _ in range(iters): 168 | np.random.shuffle(d3) 169 | n_1, n_2 = d3[:l_1], d3[l_1:] 170 | # TODO: Readdress the constraints of PyEMD 171 | # For now, decrease bin size drastically for 172 | # more efficient computation 173 | # try: 174 | # # PyEMD is sometimes memory intensive 175 | # # Let's reduce bins if so 176 | # dist = emd_samples(n_1, n_2, bins='auto') 177 | # except MemoryError: 178 | dist = emd_samples(n_1, n_2, bins=10) 179 | distances.append(dist) 180 | 181 | # Safety check, to see if there are any valid 182 | # measurements 183 | return np.mean(np.array(distances)) if distances else -1 184 | 185 | 186 | def alpha_beta_auth(df_X, df_X_syn, emb_center=None): 187 | """ 188 | Evaluates the alpha-precision, beta-recall, and authenticity scores. 189 | 190 | The class evaluates the synthetic data using a tuple of three metrics: 191 | alpha-precision, beta-recall, and authenticity. 192 | Note that these metrics can be evaluated for each synthetic data point (which are useful for auditing and 193 | post-processing). Here we average the scores to reflect the overall quality of the data. 194 | The formal definitions can be found in the reference below: 195 | 196 | Alaa, Ahmed, Boris Van Breugel, Evgeny S. Saveliev, and Mihaela van der Schaar. "How faithful is your synthetic 197 | data? sample-level metrics for evaluating and auditing generative models." 198 | In International Conference on Machine Learning, pp. 290-306. PMLR, 2022. 199 | """ 200 | 201 | X = df_X.values 202 | X_syn = df_X_syn.values 203 | assert len(X) == len(X_syn) 204 | 205 | emb_center = np.mean(X, axis=0) 206 | 207 | n_steps = 30 208 | alphas = np.linspace(0, 1, n_steps) 209 | 210 | Radii = np.quantile(np.sqrt(np.sum((X - emb_center) ** 2, axis=1)), alphas) 211 | 212 | synth_center = np.mean(X_syn, axis=0) 213 | 214 | alpha_precision_curve = [] 215 | beta_coverage_curve = [] 216 | 217 | synth_to_center = np.sqrt(np.sum((X_syn - emb_center) ** 2, axis=1)) 218 | 219 | nbrs_real = NearestNeighbors(n_neighbors=2, n_jobs=-1, p=2).fit(X) 220 | real_to_real, _ = nbrs_real.kneighbors(X) 221 | 222 | nbrs_synth = NearestNeighbors(n_neighbors=1, n_jobs=-1, p=2).fit(X_syn) 223 | real_to_synth, real_to_synth_args = nbrs_synth.kneighbors(X) 224 | 225 | # Let us find closest real point to any real point, excluding itself (therefore 1 instead of 0) 226 | real_to_real = real_to_real[:, 1].squeeze() 227 | real_to_synth = real_to_synth.squeeze() 228 | real_to_synth_args = real_to_synth_args.squeeze() 229 | 230 | real_synth_closest = X_syn[real_to_synth_args] 231 | 232 | real_synth_closest_d = np.sqrt(np.sum((real_synth_closest - synth_center) ** 2, axis=1)) 233 | closest_synth_Radii = np.quantile(real_synth_closest_d, alphas) 234 | 235 | for k in range(len(Radii)): 236 | precision_audit_mask = synth_to_center <= Radii[k] 237 | alpha_precision = np.mean(precision_audit_mask) 238 | 239 | beta_coverage = np.mean( 240 | ((real_to_synth <= real_to_real) * (real_synth_closest_d <= closest_synth_Radii[k])) 241 | ) 242 | 243 | alpha_precision_curve.append(alpha_precision) 244 | beta_coverage_curve.append(beta_coverage) 245 | 246 | # See which one is bigger 247 | 248 | authen = real_to_real[real_to_synth_args] < real_to_synth 249 | authenticity = np.mean(authen) 250 | 251 | Delta_precision_alpha = 1 - 2 * np.sum( 252 | np.abs(np.array(alphas) - np.array(alpha_precision_curve)) 253 | ) * (alphas[1] - alphas[0]) 254 | Delta_coverage_beta = 1 - 2 * np.sum( 255 | np.abs(np.array(alphas) - np.array(beta_coverage_curve)) 256 | ) * (alphas[1] - alphas[0]) 257 | 258 | return ( 259 | Delta_precision_alpha, 260 | Delta_coverage_beta, 261 | authenticity, 262 | ) 263 | -------------------------------------------------------------------------------- /tablediffusion/vis/visualisations.py: -------------------------------------------------------------------------------- 1 | import warnings 2 | 3 | import mpl_scatter_density 4 | import numpy as np 5 | import pandas as pd 6 | import seaborn as sns 7 | from astropy.visualization import LogStretch 8 | from astropy.visualization.mpl_normalize import ImageNormalize 9 | from matplotlib import pyplot as plt 10 | from sklearn.decomposition import PCA 11 | from sklearn.preprocessing import StandardScaler 12 | 13 | sns.set_context("paper") 14 | 15 | 16 | def compare_marginal_scores(data: pd.DataFrame): 17 | """Lineplots of marginal scores across features for each synth. 18 | 19 | One subplot for each epsilon level (extracted from synth name). 20 | Averages over repeats. 21 | """ 22 | 23 | # Transpose and relable dataframe 24 | _data = data.T[1:].reset_index() 25 | col_names = ["synth"] 26 | col_names.extend(data["feature"]) 27 | _data.columns = col_names 28 | 29 | # Extract repeat suffix from synth name 30 | _data["epsilon"] = _data["synth"].apply(lambda s: s.split("_")[-2]) 31 | _data["epsilon"] = pd.to_numeric(_data["epsilon"]) 32 | _data["synth"] = _data["synth"].apply(lambda s: "_".join(s.split("_")[:-2])) 33 | 34 | # Convert other columns to numeric 35 | _data[col_names[1:]] = _data[col_names[1:]].apply(pd.to_numeric) 36 | 37 | # Plot the results 38 | n_eps_vals = _data["epsilon"].nunique() 39 | fig, axes = plt.subplots(n_eps_vals, 1, figsize=(9, 9)) 40 | for i, eps in enumerate(_data["epsilon"].unique()): 41 | 42 | _data[_data["epsilon"] == eps].drop("epsilon", axis=1).groupby(["synth"]).agg( 43 | "mean" 44 | ).T.plot( 45 | kind="line", 46 | ax=axes[i] if n_eps_vals > 1 else axes, 47 | rot=90, 48 | sharex=True, 49 | marker="x", 50 | title=f"Epsilon={eps}", 51 | ) 52 | ax = axes[i] if n_eps_vals > 1 else axes 53 | ax.set_xticks(range(len(col_names) - 1)) 54 | ax.set_xticklabels(col_names[1:]) 55 | ax.set_ylabel("Marginal distance") 56 | ax.set_xlabel("Feature") 57 | 58 | return fig 59 | 60 | 61 | def visualise_metrics( 62 | data: pd.DataFrame, use_log=False, benchmark_synth="CTGAN_Synthesiser", emph_synth=None 63 | ): 64 | """ 65 | Plot final metrics across synths and datasets. 66 | """ 67 | 68 | sns.set_context("talk") 69 | 70 | # Get names of metrics and datasets 71 | metrics = list(data.columns) 72 | for c in ["dataset", "epsilon", "synth"]: 73 | metrics.remove(c) 74 | datasets = data["dataset"].unique() 75 | 76 | # Only work with a copy of the data to prevent side-effects 77 | _data = data.copy() 78 | _data["epsilon"] = pd.to_numeric(_data["epsilon"]) 79 | _data = _data.sort_values(by=["dataset", "synth", "epsilon"], ascending=True) 80 | 81 | # Create a set of subplots (M x D) for M metrics and D datasets 82 | fig, axes = plt.subplots( 83 | len(metrics), len(datasets), figsize=(8 * len(datasets), 4 * len(metrics)) 84 | ) 85 | 86 | # Define handles and labels list for the legend 87 | handles, labels = [], [] 88 | 89 | # Set the color palette 90 | colors = sns.color_palette("husl", len(_data["synth"].unique())) 91 | 92 | for j, dataset in enumerate(datasets): 93 | for i, metric in enumerate(metrics): 94 | ax = axes[i, j] if len(metrics) > 1 else axes[j] 95 | for k, synth in enumerate(_data["synth"].unique()): 96 | _subset = _data[(_data["dataset"] == dataset) & (_data["synth"] == synth)] 97 | _subset = ( 98 | _subset.drop(["dataset", "synth"], axis=1) 99 | .groupby("epsilon") 100 | .agg(["mean", "std"]) 101 | .reset_index() 102 | ) 103 | 104 | emphasise = emph_synth is not None and emph_synth in synth 105 | 106 | if synth == benchmark_synth: 107 | line = ax.axhline( 108 | _subset[(metric, "mean")].values.mean(), 109 | label=f"{synth} (no DP)", 110 | color="black", 111 | linestyle="--", 112 | linewidth=2.0, 113 | alpha=0.4, 114 | ) 115 | handles.append(line) 116 | labels.append(f"{synth} (no DP)") 117 | continue 118 | 119 | error_container, _, _ = ax.errorbar( 120 | _subset["epsilon"], 121 | _subset[(metric, "mean")], 122 | yerr=_subset[(metric, "std")], 123 | marker=".", 124 | capsize=4, 125 | label=synth + r" $\pm\sigma$", 126 | barsabove=True, 127 | # Make the lines thicker 128 | linewidth=1.5 if emphasise else 1, 129 | elinewidth=0.8, 130 | color=colors[k], 131 | alpha=1.0 if emphasise else 0.7, 132 | ) 133 | 134 | handles.append(error_container) 135 | labels.append(synth + r" $\pm\sigma$") 136 | 137 | ax.set_ylabel(metric) 138 | ax.set_title(dataset) 139 | 140 | if use_log: 141 | ax.set_xscale("log") 142 | 143 | ax.set_xlabel("epsilon") 144 | 145 | # Convert handles and labels into dictionaries to remove duplicates, then back into lists 146 | unique = dict(zip(labels, handles)) 147 | labels = list(unique.keys()) 148 | handles = list(unique.values()) 149 | 150 | # Add the legend to the figure 151 | fig.legend( 152 | handles, 153 | labels, 154 | loc="lower center", 155 | ncol=len(_data["synth"].unique()) // 2, 156 | bbox_to_anchor=(0.5, -0.40 + 0.1 * len(metrics)), 157 | fontsize=16, 158 | ) 159 | 160 | return fig 161 | 162 | 163 | def visualise_marginals(real_dataset: pd.DataFrame, fake_dataset: pd.DataFrame, data_types): 164 | """ 165 | Plots histograms to compare marginal distributions of real vs fake datasets. 166 | """ 167 | plt.cla() 168 | plt.clf() 169 | _, ax = plt.subplots(2, len(data_types), figsize=(32, 8)) 170 | 171 | for i, (col, var_type) in enumerate(data_types): 172 | axes = ax[:, i] 173 | # if col == "capital-gain": 174 | # import ipdb; ipdb.set_trace() 175 | if "int" in var_type or "float" in var_type: 176 | colour = "#1a63a5" 177 | 178 | # Calculate bin width using Freedman-Diaconis rule 179 | iqr = np.subtract(*np.percentile(real_dataset[col].dropna(), [75, 25])) 180 | bin_width = 2 * iqr * len(real_dataset[col].dropna()) ** (-1 / 3) if iqr != 0 else 1 181 | bins = min(int((real_dataset[col].max() - real_dataset[col].min()) / bin_width), 50) 182 | 183 | real_dataset[col].plot( 184 | kind="hist", 185 | ax=axes[0], 186 | color=colour, 187 | sharex=False, 188 | sharey=True, 189 | title=f"{col} real", 190 | bins=bins, 191 | density=True, 192 | ) 193 | fake_dataset[col].plot( 194 | kind="hist", 195 | ax=axes[1], 196 | color=colour, 197 | sharex=False, 198 | sharey=True, 199 | title=f"{col} fake", 200 | bins=bins, 201 | density=True, 202 | ) 203 | 204 | # Overlay KDE 205 | sns.kdeplot(real_dataset[col], ax=axes[0], color="black", warn_singular=False) 206 | sns.kdeplot(fake_dataset[col], ax=axes[1], color="black", warn_singular=False) 207 | 208 | elif "categorical" in var_type: 209 | colour = "#12bf3f" 210 | 211 | # Get categories and their frequencies 212 | real_counts = real_dataset[col].value_counts(normalize=True) 213 | fake_counts = fake_dataset[col].value_counts(normalize=True) 214 | 215 | # Ensure fake_counts includes all categories present in real_counts 216 | fake_counts = fake_counts.reindex(real_counts.index, fill_value=0) 217 | 218 | # Sort categories by their labels 219 | real_counts = real_counts.sort_index() 220 | fake_counts = fake_counts.sort_index() 221 | 222 | real_counts.plot( 223 | kind="bar", 224 | ax=axes[0], 225 | color=colour, 226 | sharex=True, 227 | sharey=True, 228 | title=f"{col} real", 229 | ) 230 | fake_counts.plot( 231 | kind="bar", 232 | ax=axes[1], 233 | color=colour, 234 | sharex=True, 235 | sharey=True, 236 | title=f"{col} fake", 237 | ) 238 | 239 | # Set X-axis limits to include all data, but have same range 240 | xmin = min(axes[0].get_xlim()[0], axes[1].get_xlim()[0]) 241 | xmax = max(axes[0].get_xlim()[1], axes[1].get_xlim()[1]) 242 | axes[0].set_xlim(xmin, xmax) 243 | axes[1].set_xlim(xmin, xmax) 244 | 245 | # Disable y-axis tick labels 246 | axes[0].axes.yaxis.set_ticklabels([]) 247 | axes[1].axes.yaxis.set_ticklabels([]) 248 | 249 | return ax 250 | 251 | 252 | def visualise_violins(real_dataset: pd.DataFrame, fake_dataset: pd.DataFrame): 253 | """ 254 | Visualisation code for split violin plots 255 | """ 256 | 257 | # Set up scaler for features and fit on real data 258 | scaler = StandardScaler().fit(real_dataset.values) 259 | 260 | # Make a copy of fake and label with new column 261 | data = fake_dataset.copy() 262 | data["veracity"] = "Fake" 263 | 264 | # Add the real data and label as real 265 | data = pd.concat([data, real_dataset], axis=0) 266 | data["veracity"].fillna("Real", inplace=True) 267 | data.reset_index(drop=True, inplace=True) 268 | 269 | # Scale all the data (real and fake in one dataframe) 270 | colnames = list(fake_dataset.columns) 271 | _ver = data["veracity"] 272 | data = pd.DataFrame(scaler.transform(data[colnames].values), columns=colnames) 273 | data["veracity"] = _ver 274 | data = data.melt( 275 | id_vars=["veracity"], value_vars=colnames, var_name="feature", value_name="feature_value" 276 | ) 277 | 278 | # Plot violins across features, splitting real and fake 279 | plt.cla() 280 | plt.clf() 281 | return sns.violinplot( 282 | x="feature_value", 283 | y="feature", 284 | hue="veracity", 285 | data=data, 286 | split=True, 287 | figsize=(16, 9), 288 | sharex=False, 289 | ) 290 | 291 | 292 | def visualise_pca(real_dataset, fake_dataset=None, mult=1.2, legend=False): 293 | """ 294 | Visualisation code for PCA 295 | Passing in only real dataset generates plot of real data. 296 | Passing in real and fake datasets generates plot of fake data. 297 | """ 298 | pca = PCA(n_components=2) 299 | _real = pca.fit_transform(real_dataset) 300 | _xlim, _ylim = ( 301 | (mult * _real[:, 0].min(), mult * _real[:, 0].max()), 302 | (mult * _real[:, 1].min(), mult * _real[:, 1].max()), 303 | ) 304 | _data = _real 305 | if fake_dataset is not None: 306 | _data = pca.transform(fake_dataset) 307 | 308 | plt.cla() 309 | plt.clf() 310 | 311 | # Ignore warnings from scatter_density code 312 | with warnings.catch_warnings(): 313 | warnings.simplefilter("ignore") 314 | 315 | norm = ImageNormalize(vmin=0.0, vmax=500, stretch=LogStretch()) 316 | fig = plt.figure() 317 | ax = fig.add_subplot(1, 1, 1, projection="scatter_density") 318 | density = ax.scatter_density(_data[:, 0], _data[:, 1], cmap=plt.cm.hot, norm=norm) 319 | 320 | if legend: 321 | fig.colorbar(density, label="Number of points per pixel") 322 | plt.xlim(_xlim) 323 | plt.ylim(_ylim) 324 | 325 | return ax 326 | -------------------------------------------------------------------------------- /tablediffusion/models/pate_gan.py: -------------------------------------------------------------------------------- 1 | """ 2 | Based on PATE-GAN implementations from 3 | https://github.com/opendp/smartnoise-sdk/blob/f51f7ff9819b5f1fb6764e46d0611c7f85b8f9eb/synth/snsynth/pytorch/nn/pategan.py 4 | """ 5 | 6 | import math 7 | 8 | import mlflow 9 | import numpy as np 10 | import pandas as pd 11 | import torch 12 | from models.architectures import Discriminator, Generator 13 | from torch import nn, optim 14 | from torch.utils.data import DataLoader, TensorDataset 15 | from utilities import * 16 | from utilities.privacy_utils import moments_acc, pate 17 | 18 | 19 | class PATEGAN_Synthesiser: 20 | def __init__( 21 | self, 22 | batch_size=64, 23 | gen_lr=2e-4, 24 | dis_lr=2e-4, 25 | latent_dim=100, 26 | gen_dims=(256, 256), 27 | dis_dims=(256, 256), 28 | num_teachers=20, 29 | teacher_iters=5, 30 | student_iters=5, 31 | epsilon_target=5, 32 | epoch_target=200, 33 | delta=1e-5, 34 | mlflow_logging=True, 35 | cuda=True, 36 | ): 37 | 38 | # Setting up GPU (if available and specified) 39 | if cuda: 40 | assert torch.cuda.is_available() 41 | self.cuda = cuda 42 | self.device = torch.device("cuda:0" if torch.cuda.is_available() and cuda else "cpu") 43 | 44 | # Hyperparameters 45 | self.batch_size = batch_size 46 | self.gen_lr = gen_lr 47 | self.dis_lr = dis_lr 48 | self.latent_dim = latent_dim 49 | self.gen_dims = gen_dims 50 | self.dis_dims = dis_dims 51 | self.num_teachers = num_teachers 52 | self.teacher_iters = teacher_iters 53 | self.student_iters = student_iters 54 | self.epoch_target = epoch_target 55 | 56 | # Setting privacy budget 57 | self.epsilon_target = epsilon_target 58 | self._delta = delta 59 | 60 | # Logging to MLflow 61 | self.mlflow_logging = mlflow_logging 62 | if self.mlflow_logging: 63 | _param_dict = gather_object_params(self, prefix="init.") 64 | mlflow.log_params(_param_dict) 65 | 66 | # Initialise training variables 67 | self._elapsed_batches = 0 68 | self._elapsed_epochs = 0 69 | self._epsilon = epsilon_target 70 | self._eps = 0 71 | 72 | def fit(self, data, n_epochs=10, epsilon=100, noise_multiplier=1e-3): 73 | 74 | self._epsilon = epsilon 75 | 76 | if isinstance(data, pd.DataFrame): 77 | for col in data.columns: 78 | data[col] = pd.to_numeric(data[col], errors="ignore") 79 | data = data.to_numpy() 80 | elif not isinstance(data, np.ndarray): 81 | raise ValueError("Data must be a numpy array or pandas dataframe") 82 | 83 | self.data_dim = data.shape[-1] 84 | 85 | # Check if training for first time or continuing (don't reinitialise) 86 | if self._elapsed_batches == 0: 87 | 88 | self._epsilon = epsilon 89 | self._alphas = torch.tensor([0.0 for _ in range(100)]) 90 | self._l_list = 1 + torch.tensor(range(100)) 91 | 92 | self.G = ( 93 | Generator(self.latent_dim, self.data_dim, gen_dims=self.gen_dims) 94 | .double() 95 | .to(self.device) 96 | ) 97 | self.G.apply(weights_init) 98 | 99 | self.D = Discriminator(self.data_dim, dis_dims=self.dis_dims).double().to(self.device) 100 | self.D.apply(weights_init) 101 | 102 | self.teacher_disc = [ 103 | Discriminator(self.data_dim).double().to(self.device) 104 | for _ in range(self.num_teachers) 105 | ] 106 | for i in range(self.num_teachers): 107 | self.teacher_disc[i].apply(weights_init) 108 | 109 | self._nparams_g = count_parameters(self.G) 110 | self._nparams_d = count_parameters(self.D) 111 | self._nparams_teacher_d = count_parameters(self.teacher_disc[0]) 112 | 113 | if self.mlflow_logging: 114 | mlflow.log_params( 115 | { 116 | "nparams.G": self._nparams_g, 117 | "nparams.D": self._nparams_d, 118 | "nparams.teacher_D": self._nparams_teacher_d, 119 | "nparams.total": self._nparams_teacher_d * self.num_teachers 120 | + self._nparams_g 121 | + self._nparams_d, 122 | } 123 | ) 124 | _model_desc = str(self.G) + "\n" + str(self.D) + "\n" + str(self.teacher_disc[0]) 125 | mlflow.log_text(_model_desc, "model_desription.txt") 126 | 127 | self.optimiser_g = optim.Adam(self.G.parameters(), lr=self.gen_lr) 128 | self.optimiser_s = optim.Adam(self.D.parameters(), lr=self.dis_lr) 129 | self.optimiser_t = [ 130 | optim.Adam(self.teacher_disc[i].parameters(), lr=1e-4) 131 | for i in range(self.num_teachers) 132 | ] 133 | 134 | # Log optimiser parameters 135 | if self.mlflow_logging: 136 | _param_dict = gather_object_params(self.optimiser_g, prefix="optim_G.") 137 | mlflow.log_params(_param_dict) 138 | _param_dict = gather_object_params(self.optimiser_t[0], prefix="optim_D.") 139 | mlflow.log_params(_param_dict) 140 | 141 | criterion = nn.BCELoss() 142 | 143 | data_partitions = np.array_split(data, self.num_teachers) 144 | tensor_partitions = [ 145 | TensorDataset(torch.from_numpy(data.astype("double")).to(self.device)) 146 | for data in data_partitions 147 | ] 148 | 149 | loader = [ 150 | DataLoader( 151 | tensor_partitions[teacher_id], 152 | batch_size=self.batch_size, 153 | shuffle=True, 154 | ) 155 | for teacher_id in range(self.num_teachers) 156 | ] 157 | for epoch in range(n_epochs): 158 | if float(self._eps) >= self._epsilon: 159 | print(f"Privacy budget reached in epoch {epoch} ({self._eps})") 160 | return self 161 | 162 | self._elapsed_epochs += 1 163 | 164 | # train teacher discriminators 165 | for _ in range(self.teacher_iters): 166 | self._elapsed_batches += 1 167 | teacher_losses_real, teacher_losses_fake = [], [] 168 | for i in range(self.num_teachers): 169 | real_data = None 170 | for _, _data in enumerate(loader[i], 0): 171 | real_data = _data[0].to(self.device) 172 | break 173 | 174 | self.optimiser_t[i].zero_grad() 175 | 176 | # train with real data 177 | label_real = torch.full( 178 | (real_data.shape[0],), 1, dtype=torch.float, device=self.device 179 | ) 180 | output = self.teacher_disc[i](real_data) 181 | loss_t_real = criterion(output.squeeze(), label_real.double()) 182 | loss_t_real.backward() 183 | teacher_losses_real.append(loss_t_real.item()) 184 | 185 | # train with fake data 186 | noise = torch.rand(self.batch_size, self.latent_dim, device=self.device) 187 | label_fake = torch.full( 188 | (self.batch_size,), 0, dtype=torch.float, device=self.device 189 | ) 190 | fake_data = self.G(noise.double()) 191 | output = self.teacher_disc[i](fake_data) 192 | loss_t_fake = criterion(output.squeeze(), label_fake.double()) 193 | loss_t_fake.backward() 194 | teacher_losses_fake.append(loss_t_fake.item()) 195 | 196 | self.optimiser_t[i].step() 197 | 198 | if self.mlflow_logging: 199 | mlflow.log_metrics( 200 | { 201 | "elapsed_batches": self._elapsed_batches, 202 | "elapsed_epochs": self._elapsed_epochs, 203 | "train_loss.teachers.real": np.mean(teacher_losses_real), 204 | "train_loss.teachers.fake": np.mean(teacher_losses_fake), 205 | }, 206 | step=self._elapsed_batches, 207 | ) 208 | 209 | # train student discriminator 210 | for _ in range(self.student_iters): 211 | self._elapsed_batches += 1 212 | noise = torch.rand(self.batch_size, self.latent_dim, device=self.device) 213 | fake_data = self.G(noise.double()) 214 | predictions, votes = pate(fake_data, self.teacher_disc, noise_multiplier) 215 | output = self.D(fake_data.detach()) 216 | 217 | # update moments accountant 218 | self._alphas = self._alphas + moments_acc( 219 | self.num_teachers, votes, noise_multiplier, self._l_list 220 | ) 221 | 222 | loss_s = criterion(output.squeeze(), predictions.to(self.device).squeeze()) 223 | self.optimiser_s.zero_grad() 224 | loss_s.backward() 225 | self.optimiser_s.step() 226 | 227 | if self.mlflow_logging: 228 | mlflow.log_metrics( 229 | {"elapsed_batches": self._elapsed_batches, "train_loss.D": loss_s.item()}, 230 | step=self._elapsed_batches, 231 | ) 232 | # Weight and Grad norms 233 | _d_norm_dict = calc_norm_dict(self.D) 234 | mlflow.log_metrics(_d_norm_dict, step=self._elapsed_batches) 235 | 236 | self._eps = ( 237 | min((self._alphas - math.log(self._delta)) / self._l_list).detach() 238 | ).item() 239 | 240 | if self.mlflow_logging: 241 | mlflow.log_metrics({"used_epsilon.total": self._eps}, step=self._elapsed_batches) 242 | 243 | if float(self._eps) >= self._epsilon: 244 | print(f"Privacy budget reached before training G in epoch {epoch} ({self._eps})") 245 | return self 246 | 247 | # train generator 248 | self.G.train() 249 | label_g = torch.full((self.batch_size,), 1, dtype=torch.float, device=self.device) 250 | noise = torch.rand(self.batch_size, self.latent_dim, device=self.device) 251 | fake_data = self.G(noise.double()) 252 | fake_validity = self.D(fake_data) 253 | loss_g = criterion(fake_validity.squeeze(), label_g.double()) 254 | self.optimiser_g.zero_grad() 255 | loss_g.backward() 256 | self.optimiser_g.step() 257 | 258 | if self.mlflow_logging: 259 | mlflow.log_metrics( 260 | { 261 | "elapsed_batches": self._elapsed_batches, 262 | "train_loss.G": loss_g.item(), 263 | "used_epsilon.total": self._eps, 264 | "validity.fake": fake_validity.mean().item(), 265 | }, 266 | step=self._elapsed_batches, 267 | ) 268 | # Weight and Grad norms 269 | _g_norm_dict = calc_norm_dict(self.G) 270 | mlflow.log_metrics(_g_norm_dict, step=self._elapsed_batches) 271 | # Diversity of fakes from G and real data 272 | mlflow.log_metrics( 273 | { 274 | "X_fake.norm": fake_data.norm().item(), 275 | "X_real.norm": real_data.norm().item(), 276 | }, 277 | step=self._elapsed_batches, 278 | ) 279 | 280 | return self 281 | 282 | def sample(self, n=None): 283 | 284 | self.G.eval() 285 | n = self.batch_size if n is None else n 286 | steps = n // self.batch_size + 1 287 | data = [] 288 | 289 | for _ in range(steps): 290 | noise = torch.randn(self.batch_size, self.latent_dim, device=self.device) 291 | noise = noise.view(-1, self.latent_dim) 292 | 293 | fake_data = self.G(noise.double()) 294 | data.append(fake_data.detach().cpu().numpy()) 295 | 296 | data = np.concatenate(data, axis=0) 297 | data = data[:n] 298 | self.G.train() 299 | 300 | return data 301 | -------------------------------------------------------------------------------- /tablediffusion/models/saint_ae.py: -------------------------------------------------------------------------------- 1 | """ 2 | Adapted from https://github.com/somepago/saint 3 | """ 4 | 5 | from typing import Tuple 6 | 7 | import numpy as np 8 | import pandas as pd 9 | import torch 10 | import torch.nn.functional as F 11 | from sklearn.preprocessing import LabelEncoder 12 | from torch import nn 13 | from utilities.saint_utils import (RowColTransformer, Transformer, 14 | embed_data_mask, mdn_loss, sep_MLP, 15 | simple_MLP) 16 | 17 | 18 | class SAINT_AE(nn.Module): 19 | def __init__( 20 | self, 21 | *, 22 | categories, 23 | num_continuous, 24 | dim_head=16, 25 | mlp_hidden_mults=(4, 2), 26 | num_special_tokens=0, 27 | attn_dropout=0.0, 28 | ff_dropout=0.0, 29 | cont_embeddings="MLP", 30 | dim=32, 31 | transformer_depth=1, 32 | attention_heads=4, 33 | attentiontype="colrow", 34 | final_mlp_style="sep", 35 | mdn=False, 36 | mdn_heads=3, 37 | ): 38 | super().__init__() 39 | self.mdn = mdn 40 | self.mdn_heads = mdn_heads if self.mdn else 0 41 | assert all(map(lambda n: n > 0, categories)), "number of each category must be positive" 42 | 43 | # categories related calculations 44 | self.num_categories = len(categories) 45 | self.num_unique_categories = sum(categories) 46 | 47 | # create category embeddings table 48 | 49 | self.num_special_tokens = num_special_tokens 50 | self.total_tokens = self.num_unique_categories + num_special_tokens 51 | 52 | # for automatically offsetting unique category ids to the correct position in the categories embedding table 53 | 54 | categories_offset = F.pad(torch.tensor(list(categories)), (1, 0), value=num_special_tokens) 55 | categories_offset = categories_offset.cumsum(dim=-1)[:-1] 56 | 57 | self.register_buffer("categories_offset", categories_offset) 58 | 59 | self.norm = nn.LayerNorm(num_continuous) 60 | self.num_continuous = num_continuous 61 | self.dim = dim 62 | self.cont_embeddings = cont_embeddings 63 | self.attentiontype = attentiontype 64 | self.final_mlp_style = final_mlp_style 65 | 66 | if self.cont_embeddings == "MLP": 67 | self.simple_MLP = nn.ModuleList( 68 | [simple_MLP([1, 100, self.dim]) for _ in range(self.num_continuous)] 69 | ) 70 | input_size = (dim * self.num_categories) + (dim * num_continuous) 71 | nfeats = self.num_categories + num_continuous 72 | elif self.cont_embeddings == "pos_singleMLP": 73 | self.simple_MLP = nn.ModuleList([simple_MLP([1, 100, self.dim]) for _ in range(1)]) 74 | input_size = (dim * self.num_categories) + (dim * num_continuous) 75 | nfeats = self.num_categories + num_continuous 76 | else: 77 | print("Continous features are not passed through attention") 78 | input_size = (dim * self.num_categories) + num_continuous 79 | nfeats = self.num_categories 80 | 81 | # transformer 82 | if attentiontype == "col": 83 | self.transformer = Transformer( 84 | num_tokens=self.total_tokens, 85 | dim=dim, 86 | depth=transformer_depth, 87 | heads=attention_heads, 88 | dim_head=dim_head, 89 | attn_dropout=attn_dropout, 90 | ff_dropout=ff_dropout, 91 | ) 92 | elif attentiontype in ["row", "colrow"]: 93 | self.transformer = RowColTransformer( 94 | num_tokens=self.total_tokens, 95 | dim=dim, 96 | nfeats=nfeats, 97 | depth=transformer_depth, 98 | heads=attention_heads, 99 | dim_head=dim_head, 100 | attn_dropout=attn_dropout, 101 | ff_dropout=ff_dropout, 102 | style=attentiontype, 103 | ) 104 | 105 | # l = input_size // 8 106 | # hidden_dimensions = list(map(lambda t: l * t, mlp_hidden_mults)) 107 | 108 | self.embeds = nn.Embedding(self.total_tokens, self.dim) # .to(self.device) 109 | 110 | # cat_mask_offset = F.pad( 111 | # torch.Tensor(self.num_categories).fill_(2).type(torch.int8), (1, 0), value=0 112 | # ) 113 | # cat_mask_offset = cat_mask_offset.cumsum(dim=-1)[:-1] 114 | 115 | # con_mask_offset = F.pad( 116 | # torch.Tensor(self.num_continuous).fill_(2).type(torch.int8), (1, 0), value=0 117 | # ) 118 | # con_mask_offset = con_mask_offset.cumsum(dim=-1)[:-1] 119 | 120 | # self.register_buffer("cat_mask_offset", cat_mask_offset) 121 | # self.register_buffer("con_mask_offset", con_mask_offset) 122 | 123 | # self.mask_embeds_cat = nn.Embedding(self.num_categories * 2, self.dim) 124 | # self.mask_embeds_cont = nn.Embedding(self.num_continuous * 2, self.dim) 125 | # self.single_mask = nn.Embedding(2, self.dim) 126 | # self.pos_encodings = nn.Embedding(self.num_categories + self.num_continuous, self.dim) 127 | 128 | self.mlp1 = sep_MLP(dim, self.num_categories - 1, categories[1:]) 129 | self.mlp2 = sep_MLP( 130 | dim, 131 | self.num_continuous, 132 | np.ones(self.num_continuous).astype(int), 133 | mdn_heads=self.mdn_heads, 134 | ) 135 | 136 | def encode(self, x_categ, x_cont): 137 | 138 | x = self.transformer(x_categ, x_cont) 139 | 140 | # Only pass CLS token forward 141 | x = x[:, 0, :] 142 | # x = torch.tanh(x) 143 | 144 | return x 145 | 146 | def decode(self, x): 147 | 148 | cat_outs = self.mlp1(x) 149 | con_outs = self.mlp2(x) 150 | 151 | return cat_outs, con_outs 152 | 153 | def forward(self, x_categ, x_cont): 154 | 155 | x = self.encode(x_categ, x_cont) 156 | cat_outs, con_outs = self.decode(x) 157 | 158 | return cat_outs, con_outs 159 | 160 | def inv_transform(self, x): 161 | 162 | cat_outs, con_outs = self.decode(x) 163 | 164 | cats, cons = [], [] 165 | with torch.no_grad(): 166 | for cat in cat_outs: 167 | cat = cat.detach() 168 | cats.append(torch.argmax(nn.functional.softmax(cat, dim=1), dim=1)) 169 | for con in con_outs: 170 | if self.mdn: 171 | pi, mu, sigma = con[0].detach(), con[1].detach(), con[2].detach() 172 | mixture = torch.normal(mu, sigma) 173 | k = torch.multinomial(pi, 1, replacement=True).squeeze() 174 | cons.append(mixture.view(pi.shape)[range(k.size(0)), k]) 175 | else: 176 | con = con.detach() 177 | # naive rounding to nearest .1 178 | cons.append(torch.round(con * 10) / 10) 179 | return cats, cons 180 | 181 | 182 | def embed_and_mask(data: Tuple, model: SAINT_AE, device="cpu", keep_cls=False): 183 | 184 | # Parse the batch tuple into components 185 | x_categ, x_cont, cat_mask, con_mask = ( 186 | data[0].to(device), 187 | data[1].to(device), 188 | data[2].to(device), 189 | data[3].to(device), 190 | ) 191 | """ 192 | `x_categ` is the the categorical data (batch_size x cat_cols+1) 193 | `x_cont` has continuous data (batch_size x cont_cols) 194 | `cat_mask` is an array of ones same shape as x_categ and an additional column(corresponding to CLS token) set to 0s (batch_size, cat_cols+1) 195 | `con_mask` is an array of ones same shape as x_cont (batch_size, cont_cols) 196 | """ 197 | 198 | # Prepare categorical and continunous embeddings 199 | _, x_categ_enc_2, x_cont_enc_2 = embed_data_mask(x_categ, x_cont, cat_mask, con_mask, model) 200 | 201 | if not keep_cls: 202 | # Trim CLS token off categorical targets 203 | x_categ = x_categ[:, 1:] 204 | 205 | return x_categ, x_cont, x_categ_enc_2, x_cont_enc_2 206 | 207 | 208 | def train_on_batch( 209 | data: Tuple, 210 | model: SAINT_AE, 211 | criterion_cat=nn.CrossEntropyLoss(), 212 | criterion_cont=nn.MSELoss(), 213 | mdn=False, 214 | device="cpu", 215 | ): 216 | """Train SAINT Autoencoder on a batch, returning losses.""" 217 | 218 | # Apply first embedding and masking 219 | x_categ, x_cont, x_categ_enc_2, x_cont_enc_2 = embed_and_mask(data, model=model, device=device) 220 | 221 | # Forward pass (embed and decode) 222 | cat_outs, con_outs = model(x_categ_enc_2, x_cont_enc_2) 223 | 224 | # Reconstruction loss (l_cat for Categorical l_cont for Continuous) 225 | l_cat, l_cont = 0, 0 226 | 227 | # Number of categories 228 | n_cat = x_categ.shape[-1] 229 | 230 | # Categorical reconstruction loss 231 | for j in range(n_cat): 232 | # TODO make this faster? 233 | x_probs = torch.full(cat_outs[j].shape, 0.01).to(device) 234 | for _i in range(cat_outs[j].shape[0]): 235 | x_probs[_i, x_categ[_i, j]] = 0.99 236 | l_cat += criterion_cat(cat_outs[j], x_probs) 237 | 238 | # Continuous reconstruction loss 239 | if len(con_outs) > 0: 240 | if mdn: 241 | # MDN loss 242 | for _i, con in enumerate(con_outs): 243 | pi, mu, sigma = con 244 | l_mdn = mdn_loss(x_cont[:, _i], pi, mu, sigma) 245 | l_cont += l_mdn 246 | else: 247 | con_outs = torch.cat(con_outs, dim=1) 248 | # Sqrt makes into RMSE loss 249 | l_cont = torch.sqrt(criterion_cont(con_outs, x_cont)) 250 | 251 | return l_cat, l_cont 252 | 253 | 254 | def parse_mixed_dataset(train_data, discrete_columns): 255 | 256 | data_dim = train_data.shape[-1] 257 | data_n = train_data.shape[0] 258 | dset_shape = train_data.shape 259 | colnames = train_data.columns 260 | disc_cols = list(discrete_columns) 261 | cat_idxs = [i for i, c in enumerate(colnames) if c in disc_cols] 262 | 263 | # The cardinality of each categorical feature 264 | cat_dims = [train_data.iloc[:, i].nunique() for i in cat_idxs] 265 | # Appending 1 for CLS token, this is later used to generate embeddings. 266 | cat_dims = np.append(np.array([1]), np.array(cat_dims)).astype(int) 267 | 268 | con_idxs = [i for i, _ in enumerate(colnames) if i not in cat_idxs] 269 | 270 | # Encode categoricals 271 | cat_label_encs = [] 272 | for i in cat_idxs: 273 | l_enc = LabelEncoder() 274 | train_data.iloc[:, i] = l_enc.fit_transform(train_data.values[:, i]) 275 | # store labels for inverse transform 276 | cat_label_encs.append(l_enc) 277 | 278 | # TODO I don't think this is needed 279 | # train_mean = train_data.values[:, con_idxs].mean() 280 | # train_std = train_data.values[:, con_idxs].std() 281 | # continuous_mean_std = np.array([train_mean, train_std]).astype(np.float32) 282 | 283 | return ( 284 | data_dim, 285 | data_n, 286 | dset_shape, 287 | colnames, 288 | disc_cols, 289 | cat_idxs, 290 | cat_dims, 291 | con_idxs, 292 | cat_label_encs, 293 | ) 294 | 295 | 296 | def pseudo_sample(model, dataloader, cat_idxs, con_idxs, n, device=None): 297 | 298 | model.eval() 299 | saved_latent = None 300 | with torch.no_grad(): 301 | cat_samples, con_samples = [[] for _ in cat_idxs], [[] for _ in con_idxs] 302 | for i, data in enumerate(dataloader, 0): 303 | if i * dataloader.batch_size >= n: 304 | break 305 | 306 | # Forward pass the data through the SAINT encoder 307 | x_categ, x_cont, x_categ_enc_2, x_cont_enc_2 = embed_and_mask( 308 | data, model, device=device, keep_cls=False 309 | ) 310 | 311 | # Forward pass the latents through the decoder MLPS 312 | x_hat = model.encode(x_categ_enc_2, x_cont_enc_2) 313 | if saved_latent is None: 314 | saved_latent = x_hat.detach().cpu() 315 | cat_tx, con_tx = model.inv_transform(x_hat) 316 | 317 | # Append to running output 318 | for j, d in enumerate(cat_tx): 319 | cat_samples[j].extend(list(d.cpu().flatten().numpy())) 320 | for j, d in enumerate(con_tx): 321 | con_samples[j].extend(list(d.cpu().flatten().numpy())) 322 | 323 | return cat_samples, con_samples, saved_latent 324 | 325 | 326 | def samples_to_df(cat_samples, con_samples, cat_idxs, colnames, cat_label_encs, datatypes=None): 327 | 328 | n_feats = len(cat_samples) + len(con_samples) 329 | assert n_feats == len(colnames) 330 | 331 | # convert labels back to strings 332 | cat_samples = [cat_label_encs[i].inverse_transform(c) for i, c in enumerate(cat_samples)] 333 | 334 | cols = [] 335 | for i in range(n_feats): 336 | if i in cat_idxs: 337 | col = cat_samples[0] 338 | cat_samples = cat_samples[1:] 339 | else: 340 | col = con_samples[0] 341 | con_samples = con_samples[1:] 342 | cols.append(col) 343 | 344 | df = pd.DataFrame(cols).T 345 | df.columns = colnames 346 | df = df.apply(pd.to_numeric, errors="ignore") 347 | 348 | if datatypes is not None: 349 | # Non-parametric post-processing 350 | for c, kind in datatypes: 351 | # If non-neg then clip values to zero 352 | if "positive" in kind: 353 | df[c] = df[c].apply(lambda x: max(0.0, x)) 354 | # If integer, then round to units 355 | if "int" in kind: 356 | df[c] = df[c].round().astype("int64") 357 | # If float then round to 3dp 358 | if "float" in kind: 359 | df[c] = df[c].round(3).astype("float64") 360 | 361 | return df 362 | -------------------------------------------------------------------------------- /tablediffusion/utilities/saint_utils.py: -------------------------------------------------------------------------------- 1 | """ 2 | Supporting code for SAINT-based models. 3 | Adapted from https://github.com/somepago/saint 4 | """ 5 | 6 | import numpy as np 7 | import torch 8 | import torch.nn.functional as F 9 | from einops import rearrange 10 | from torch import einsum, nn 11 | from torch.distributions.normal import Normal 12 | from torch.utils.data import Dataset 13 | 14 | 15 | class Residual(nn.Module): 16 | def __init__(self, fn): 17 | super().__init__() 18 | self.fn = fn 19 | 20 | def forward(self, x, **kwargs): 21 | return self.fn(x, **kwargs) + x 22 | 23 | 24 | class PreNorm(nn.Module): 25 | def __init__(self, dim, fn): 26 | super().__init__() 27 | self.norm = nn.LayerNorm(dim) 28 | self.fn = fn 29 | 30 | def forward(self, x, **kwargs): 31 | return self.fn(self.norm(x), **kwargs) 32 | 33 | 34 | class GEGLU(nn.Module): 35 | def forward(self, x): 36 | x, gates = x.chunk(2, dim=-1) 37 | return x * F.gelu(gates) 38 | 39 | 40 | class FeedForward(nn.Module): 41 | def __init__(self, dim, mult=4, dropout=0.0): 42 | super().__init__() 43 | self.net = nn.Sequential( 44 | nn.Linear(dim, dim * mult * 2), 45 | GEGLU(), 46 | nn.Dropout(dropout), 47 | nn.Linear(dim * mult, dim), 48 | ) 49 | 50 | def forward(self, x, **kwargs): 51 | return self.net(x) 52 | 53 | 54 | class Attention(nn.Module): 55 | def __init__(self, dim, heads=8, dim_head=16, dropout=0.0): 56 | super().__init__() 57 | inner_dim = dim_head * heads 58 | self.heads = heads 59 | self.scale = dim_head**-0.5 60 | 61 | self.to_qkv = nn.Linear(dim, inner_dim * 3, bias=False) 62 | self.to_out = nn.Linear(inner_dim, dim) 63 | 64 | self.dropout = nn.Dropout(dropout) 65 | 66 | def forward(self, x): 67 | h = self.heads 68 | q, k, v = self.to_qkv(x).chunk(3, dim=-1) 69 | q, k, v = map(lambda t: rearrange(t, "b n (h d) -> b h n d", h=h), (q, k, v)) 70 | sim = einsum("b h i d, b h j d -> b h i j", q, k) * self.scale 71 | attn = sim.softmax(dim=-1) 72 | out = einsum("b h i j, b h j d -> b h i d", attn, v) 73 | out = rearrange(out, "b h n d -> b n (h d)", h=h) 74 | return self.to_out(out) 75 | 76 | 77 | class RowColTransformer(nn.Module): 78 | def __init__( 79 | self, 80 | num_tokens, 81 | dim, 82 | nfeats, 83 | depth, 84 | heads, 85 | dim_head, 86 | attn_dropout, 87 | ff_dropout, 88 | style="col", 89 | ): 90 | super().__init__() 91 | self.embeds = nn.Embedding(num_tokens, dim) 92 | self.layers = nn.ModuleList([]) 93 | self.mask_embed = nn.Embedding(nfeats, dim) 94 | self.style = style 95 | for _ in range(depth): 96 | if self.style == "colrow": 97 | self.layers.append( 98 | nn.ModuleList( 99 | [ 100 | PreNorm( 101 | dim, 102 | Residual( 103 | Attention( 104 | dim, heads=heads, dim_head=dim_head, dropout=attn_dropout 105 | ) 106 | ), 107 | ), 108 | PreNorm(dim, Residual(FeedForward(dim, dropout=ff_dropout))), 109 | PreNorm( 110 | dim * nfeats, 111 | Residual( 112 | Attention( 113 | dim * nfeats, 114 | heads=heads, 115 | dim_head=64, 116 | dropout=attn_dropout, 117 | ) 118 | ), 119 | ), 120 | PreNorm( 121 | dim * nfeats, 122 | Residual(FeedForward(dim * nfeats, dropout=ff_dropout)), 123 | ), 124 | ] 125 | ) 126 | ) 127 | else: 128 | self.layers.append( 129 | nn.ModuleList( 130 | [ 131 | PreNorm( 132 | dim * nfeats, 133 | Residual( 134 | Attention( 135 | dim * nfeats, 136 | heads=heads, 137 | dim_head=64, 138 | dropout=attn_dropout, 139 | ) 140 | ), 141 | ), 142 | PreNorm( 143 | dim * nfeats, 144 | Residual(FeedForward(dim * nfeats, dropout=ff_dropout)), 145 | ), 146 | ] 147 | ) 148 | ) 149 | 150 | def forward(self, x, x_cont=None, mask=None): 151 | if x_cont is not None: 152 | x = torch.cat((x, x_cont), dim=1) 153 | _, n, _ = x.shape 154 | if self.style == "colrow": 155 | for attn1, ff1, attn2, ff2 in self.layers: 156 | x = attn1(x) 157 | x = ff1(x) 158 | x = rearrange(x, "b n d -> 1 b (n d)") 159 | x = attn2(x) 160 | x = ff2(x) 161 | x = rearrange(x, "1 b (n d) -> b n d", n=n) 162 | else: 163 | for attn1, ff1 in self.layers: 164 | x = rearrange(x, "b n d -> 1 b (n d)") 165 | x = attn1(x) 166 | x = ff1(x) 167 | x = rearrange(x, "1 b (n d) -> b n d", n=n) 168 | return x 169 | 170 | 171 | class Transformer(nn.Module): 172 | def __init__(self, num_tokens, dim, depth, heads, dim_head, attn_dropout, ff_dropout): 173 | super().__init__() 174 | self.layers = nn.ModuleList([]) 175 | 176 | for _ in range(depth): 177 | self.layers.append( 178 | nn.ModuleList( 179 | [ 180 | PreNorm( 181 | dim, 182 | Residual( 183 | Attention( 184 | dim, heads=heads, dim_head=dim_head, dropout=attn_dropout 185 | ) 186 | ), 187 | ), 188 | PreNorm(dim, Residual(FeedForward(dim, dropout=ff_dropout))), 189 | ] 190 | ) 191 | ) 192 | 193 | def forward(self, x, x_cont=None): 194 | if x_cont is not None: 195 | x = torch.cat((x, x_cont), dim=1) 196 | for attn, ff in self.layers: 197 | x = attn(x) 198 | x = ff(x) 199 | return x 200 | 201 | 202 | class MLP(nn.Module): 203 | def __init__(self, dims, act=None): 204 | super().__init__() 205 | dims_pairs = list(zip(dims[:-1], dims[1:])) 206 | layers = [] 207 | for ind, (dim_in, dim_out) in enumerate(dims_pairs): 208 | is_last = ind >= (len(dims) - 1) 209 | linear = nn.Linear(dim_in, dim_out) 210 | layers.append(linear) 211 | 212 | if is_last: 213 | continue 214 | if act is not None: 215 | layers.append(act) 216 | 217 | self.mlp = nn.Sequential(*layers) 218 | 219 | def forward(self, x): 220 | return self.mlp(x) 221 | 222 | 223 | class simple_MLP(nn.Module): 224 | def __init__(self, dims, act=None): 225 | super(simple_MLP, self).__init__() 226 | self.layers = nn.Sequential( 227 | nn.Linear(dims[0], dims[1]), nn.ReLU(), nn.Linear(dims[1], dims[2]) 228 | ) 229 | if act is not None: 230 | self.layers.add_module(act()) 231 | 232 | def forward(self, x): 233 | if len(x.shape) == 1: 234 | x = x.view(x.size(0), -1) 235 | x = self.layers(x) 236 | return x 237 | 238 | 239 | class sep_MLP(nn.Module): 240 | def __init__(self, dim, len_feats, categories, mdn_heads=0): 241 | super(sep_MLP, self).__init__() 242 | self.len_feats = len_feats 243 | self.mdn = mdn_heads > 0 244 | self.mdn_heads = mdn_heads 245 | self.layers = nn.ModuleList([]) 246 | if self.mdn: 247 | self.mdns = nn.ModuleList([]) 248 | for i in range(len_feats): 249 | if self.mdn: 250 | self.layers.append(simple_MLP([dim, 5 * dim, 16])) 251 | self.mdns.append(MixtureDensityNetwork(16, categories[i], self.mdn_heads)) 252 | else: 253 | self.layers.append(simple_MLP([dim, 5 * dim, categories[i]])) 254 | 255 | def forward(self, x): 256 | y_pred = [] 257 | for i in range(self.len_feats): 258 | pred = self.layers[i](x) 259 | if self.mdn: 260 | pred = self.mdns[i](pred) 261 | y_pred.append(pred) 262 | return y_pred 263 | 264 | 265 | class MixtureDensityNetwork(nn.Module): 266 | """ 267 | Mixture density network (Bishop, 1994). 268 | Adapted from https://github.com/pdogr/pytorch-MDN 269 | 270 | Parameters 271 | ---------- 272 | dim_in; dimensionality of the input 273 | dim_out: int; dimensionality of the output 274 | num_latent: int; number of components in the mixture model 275 | 276 | Output 277 | ---------- 278 | (pi,mu,sigma) 279 | pi (batch_size x num_latent) is prior 280 | mu (batch_size x dim_out x num_latent) is mean of each Gaussian 281 | sigma (batch_size x dim_out x num_latent) is standard deviation of each Gaussian 282 | """ 283 | 284 | def __init__(self, dim_in, dim_out, num_latent): 285 | super(MixtureDensityNetwork, self).__init__() 286 | self.dim_in = dim_in 287 | self.num_latent = num_latent 288 | self.dim_out = dim_out 289 | self.pi_h = nn.Linear(dim_in, num_latent) 290 | self.mu_h = nn.Linear(dim_in, dim_out * num_latent) 291 | self.sigma_h = nn.Linear(dim_in, dim_out * num_latent) 292 | 293 | def forward(self, x): 294 | x = torch.tanh(x) 295 | 296 | pi = self.pi_h(x) 297 | pi = F.softmax(pi, dim=-1) 298 | 299 | mu = self.mu_h(x) 300 | mu = mu.view(-1, self.dim_out, self.num_latent) 301 | 302 | sigma = torch.exp(self.sigma_h(x)) 303 | sigma = sigma.view(-1, self.dim_out, self.num_latent) 304 | 305 | return pi, mu, sigma 306 | 307 | 308 | def mdn_loss(y, pi, mu, sigma): 309 | """Mixture Density Net loss 310 | Adapted from https://github.com/DuaneNielsen/mixturedensity 311 | """ 312 | _y = y if len(y.shape) == 2 else y.view(-1, 1) 313 | 314 | mixture = Normal(mu, sigma) 315 | log_prob = mixture.log_prob(_y) 316 | weighted_log_prob = log_prob + torch.log(pi) 317 | log_prob_loss = -torch.sum(weighted_log_prob, dim=1) 318 | return torch.mean(log_prob_loss) 319 | 320 | 321 | class DataSetCatCon(Dataset): 322 | def __init__(self, X, cat_cols, continuous_mean_std=None): 323 | 324 | # Don't modify the original dataset 325 | _X = X.copy() 326 | 327 | cat_cols = list(cat_cols) 328 | X_mask = np.ones_like(X.values, dtype=int) 329 | _X = _X.values 330 | self.length = int(_X.shape[0]) 331 | con_cols = list(set(np.arange(_X.shape[1])) - set(cat_cols)) 332 | self.X1 = _X[:, cat_cols].copy().astype(np.int64) # categorical columns 333 | self.X2 = _X[:, con_cols].copy().astype(np.float32) # numerical columns 334 | self.X1_mask = X_mask[:, cat_cols].copy().astype(np.int64) # categorical columns 335 | self.X2_mask = X_mask[:, con_cols].copy().astype(np.int64) # numerical columns 336 | 337 | null_dim = _X[:, 0] 338 | self.cls = np.zeros_like(null_dim, dtype=int) 339 | self.cls = self.cls[..., np.newaxis] 340 | self.cls_mask = np.ones_like(null_dim, dtype=int) 341 | self.cls_mask = self.cls_mask[..., np.newaxis] 342 | 343 | if continuous_mean_std is not None: 344 | mean, std = continuous_mean_std 345 | self.X2 = (self.X2 - mean) / std 346 | 347 | def __len__(self): 348 | return self.length 349 | 350 | def __getitem__(self, idx): 351 | # X1 has categorical data, X2 has continuous 352 | # print(self.cls.shape, self.cls_mask.shape, self.X1.shape, self.X2.shape) 353 | return ( 354 | np.concatenate((self.cls[idx], self.X1[idx])), 355 | self.X2[idx], 356 | np.concatenate((self.cls_mask[idx], self.X1_mask[idx])), 357 | self.X2_mask[idx], 358 | ) 359 | 360 | 361 | def embed_data_mask(x_categ, x_cont, cat_mask, con_mask, model): 362 | # TODO understand what this does and how 363 | device = x_cont.device 364 | # How does this offsetting work? Why? 365 | x_categ = x_categ + model.categories_offset.type_as(x_categ) 366 | x_categ_enc = model.embeds(x_categ) 367 | n1, n2 = x_cont.shape 368 | _, n3 = x_categ.shape 369 | if model.cont_embeddings == "MLP": 370 | # Embeds each continuous feature into a 32-dim latent space 371 | x_cont_enc = torch.empty(n1, n2, model.dim) 372 | for i in range(model.num_continuous): 373 | x_cont_enc[:, i, :] = model.simple_MLP[i](x_cont[:, i]) 374 | else: 375 | raise Exception("This case should not work!") 376 | 377 | x_cont_enc = x_cont_enc.to(device) 378 | 379 | return x_categ, x_categ_enc, x_cont_enc 380 | 381 | 382 | def parse_mixed_dataset(*args, **kwargs): 383 | return None 384 | -------------------------------------------------------------------------------- /tablediffusion/models/dp_auto_gan.py: -------------------------------------------------------------------------------- 1 | """ 2 | Based on DP-auto-GAN implementation from 3 | https://github.com/DPautoGAN/DPautoGAN 4 | """ 5 | 6 | import mlflow 7 | import numpy as np 8 | import torch 9 | from models.architectures import Discriminator, Generator 10 | from opacus import PrivacyEngine 11 | from torch import nn 12 | from torch.autograd import Variable 13 | from torch.utils.data import DataLoader, Dataset 14 | from utilities import * 15 | 16 | 17 | class MyDataset(Dataset): 18 | def __init__(self, data): 19 | self.data = data 20 | 21 | def return_data(self): 22 | return self.data 23 | 24 | def __len__(self): 25 | return self.data.shape[0] 26 | 27 | def __getitem__(self, idx): 28 | if torch.is_tensor(idx): 29 | idx = idx.tolist() 30 | 31 | X = self.data[idx, :] 32 | return torch.as_tensor(X, dtype=torch.float64) 33 | 34 | 35 | class Autoencoder(nn.Module): 36 | def __init__(self, example_dim, compression_dim, binary=True, device="cpu"): 37 | super().__init__() 38 | 39 | self.compression_dim = compression_dim 40 | 41 | self.encoder = nn.Sequential( 42 | nn.Linear(example_dim, (example_dim + compression_dim) // 2), 43 | nn.Tanh() if binary else nn.LeakyReLU(0.2), 44 | nn.Linear((example_dim + compression_dim) // 2, compression_dim), 45 | nn.Tanh() if binary else nn.LeakyReLU(0.2), 46 | ).to(device) 47 | 48 | self.decoder = nn.Sequential( 49 | nn.Linear(compression_dim, (example_dim + compression_dim) // 2), 50 | nn.Tanh() if binary else nn.LeakyReLU(0.2), 51 | nn.Linear((example_dim + compression_dim) // 2, example_dim), 52 | nn.Sigmoid(), 53 | ).to(device) 54 | 55 | def forward(self, x): 56 | return self.decoder(self.encoder(x)) 57 | 58 | def get_encoder(self): 59 | return self.encoder 60 | 61 | def get_decoder(self): 62 | return self.decoder 63 | 64 | def get_compression_dim(self): 65 | return self.compression_dim 66 | 67 | 68 | class DPautoGAN_Synthesiser: 69 | def __init__( 70 | self, 71 | batch_size=64, 72 | gen_lr=2e-4, 73 | dis_lr=2e-4, 74 | ae_lr=0.005, 75 | latent_dim=100, 76 | gen_dims=(256, 256), 77 | dis_dims=(256, 256), 78 | ae_compress_dim=15, 79 | epsilon_target=5, 80 | max_grad_norm=1.0, 81 | ae_eps_frac=0.3, 82 | epoch_target=200, 83 | delta=1e-5, 84 | mlflow_logging=True, 85 | cuda=True, 86 | ): 87 | 88 | # Setting up GPU (if available and specified) 89 | if cuda: 90 | assert torch.cuda.is_available() 91 | self.cuda = cuda 92 | self.device = torch.device("cuda:0" if torch.cuda.is_available() and cuda else "cpu") 93 | 94 | # Hyperparameters 95 | self.batch_size = batch_size 96 | self.gen_lr = gen_lr 97 | self.dis_lr = dis_lr 98 | self.ae_lr = ae_lr 99 | self.latent_dim = latent_dim 100 | self.gen_dims = gen_dims 101 | self.dis_dims = dis_dims 102 | self.ae_compress_dim = ae_compress_dim 103 | self.max_grad_norm = max_grad_norm 104 | self.ae_eps_frac = ae_eps_frac 105 | self.epoch_target = epoch_target 106 | 107 | # Setting privacy budget 108 | self.epsilon_target = epsilon_target 109 | self._delta = delta 110 | 111 | # Logging to MLflow 112 | self.mlflow_logging = mlflow_logging 113 | if self.mlflow_logging: 114 | _param_dict = gather_object_params(self, prefix="init.") 115 | mlflow.log_params(_param_dict) 116 | 117 | # Initialise training variables 118 | self._elapsed_batches = 0 119 | self._elapsed_epochs = 0 120 | self._epsilon = epsilon_target 121 | self._eps = 0 122 | 123 | def fit(self, train_data, n_epochs=10, epsilon=100): 124 | 125 | self._epsilon = epsilon 126 | 127 | Tensor = torch.cuda.FloatTensor if self.cuda else torch.FloatTensor 128 | self.data_dim = train_data.shape[-1] 129 | self.data_n = train_data.shape[0] 130 | 131 | if not isinstance(train_data, DataLoader): 132 | train_data = DataLoader(MyDataset(train_data), batch_size=self.batch_size) 133 | 134 | # Check if training for first time or continuing (don't reinitialise) 135 | if self._elapsed_batches == 0: 136 | 137 | self.AE = Autoencoder( 138 | example_dim=self.data_dim, 139 | compression_dim=self.ae_compress_dim, 140 | binary=False, 141 | device=self.device, 142 | ) 143 | self.decoder = self.AE.decoder 144 | 145 | self.G = Generator( 146 | self.latent_dim, self.AE.get_compression_dim(), gen_dims=self.gen_dims 147 | ).to(self.device) 148 | self.D = Discriminator(self.data_dim, dis_dims=self.dis_dims).to(self.device) 149 | 150 | self._nparams_ae = count_parameters(self.AE) 151 | self._nparams_g = count_parameters(self.G) 152 | self._nparams_d = count_parameters(self.D) 153 | 154 | if self.mlflow_logging: 155 | mlflow.log_params( 156 | { 157 | "nparams.AE": self._nparams_ae, 158 | "nparams.G": self._nparams_g, 159 | "nparams.D": self._nparams_d, 160 | "nparams.total": self._nparams_ae + self._nparams_g + self._nparams_d, 161 | } 162 | ) 163 | _model_desc = str(self.AE) + "\n" + str(self.G) + "\n" + str(self.D) 164 | mlflow.log_text(_model_desc, "model_desription.txt") 165 | 166 | self.optim_enc = torch.optim.Adam( 167 | params=self.AE.get_encoder().parameters(), 168 | lr=self.ae_lr, 169 | betas=(0.9, 0.999), 170 | weight_decay=0, 171 | ) 172 | 173 | self.optim_dec = torch.optim.Adam( 174 | params=self.AE.get_decoder().parameters(), 175 | lr=self.ae_lr, 176 | betas=(0.9, 0.999), 177 | weight_decay=0, 178 | ) 179 | 180 | self.privacy_engine_AE = PrivacyEngine(accountant="rdp", secure_mode=False) 181 | ( 182 | self.AE.decoder, 183 | self.optim_dec, 184 | train_data, 185 | ) = self.privacy_engine_AE.make_private_with_epsilon( 186 | module=self.AE.get_decoder(), 187 | optimizer=self.optim_dec, 188 | data_loader=train_data, 189 | target_epsilon=self.ae_eps_frac * self.epsilon_target, 190 | target_delta=self._delta, 191 | epochs=1, 192 | max_grad_norm=self.max_grad_norm, 193 | poisson_sampling=False, 194 | ) 195 | 196 | # Log privacy engine and optimiser parameters 197 | if self.mlflow_logging: 198 | _param_dict = gather_object_params( 199 | self.privacy_engine_AE, prefix="privacy_engine_AE." 200 | ) 201 | mlflow.log_params(_param_dict) 202 | _param_dict = gather_object_params(self.optim_dec, prefix="optim_dec.") 203 | mlflow.log_params(_param_dict) 204 | 205 | self.optim_G = torch.optim.RMSprop( 206 | params=self.G.parameters(), lr=self.gen_lr, alpha=0.99, weight_decay=0 207 | ) 208 | 209 | self.optim_D = torch.optim.RMSprop( 210 | params=self.D.parameters(), lr=self.dis_lr, alpha=0.99, weight_decay=0 211 | ) 212 | 213 | self.privacy_engine_D = PrivacyEngine(accountant="rdp", secure_mode=False) 214 | self.D, self.optim_D, train_data = self.privacy_engine_D.make_private_with_epsilon( 215 | module=self.D, 216 | optimizer=self.optim_D, 217 | data_loader=train_data, 218 | target_epsilon=self.epsilon_target * (1 / self.ae_eps_frac), 219 | target_delta=self._delta, 220 | epochs=n_epochs, 221 | max_grad_norm=self.max_grad_norm, 222 | poisson_sampling=False, 223 | ) 224 | 225 | # Log privacy engine and optimiser parameters 226 | if self.mlflow_logging: 227 | _param_dict = gather_object_params( 228 | self.privacy_engine_D, prefix="privacy_engine_D." 229 | ) 230 | mlflow.log_params(_param_dict) 231 | _param_dict = gather_object_params(self.optim_D, prefix="optim_D.") 232 | mlflow.log_params(_param_dict) 233 | 234 | self.ae_criterion = nn.BCELoss() 235 | 236 | # AE pretraining 237 | self._elapsed_batches += 1 238 | for i, X in enumerate(train_data): 239 | self._eps_ae = self.privacy_engine_AE.get_epsilon(self._delta) 240 | if self._eps_ae >= self._epsilon: 241 | print(f"Privacy budget reached in pre-training ({self._eps_ae})") 242 | return self 243 | 244 | self._elapsed_batches += 1 245 | self.optim_enc.zero_grad() 246 | self.optim_dec.zero_grad() 247 | real_X = Variable(X.type(Tensor)) 248 | output = self.AE(real_X) 249 | loss = self.ae_criterion(output, real_X) 250 | loss.backward() 251 | self.optim_enc.step() 252 | self.optim_dec.step() 253 | 254 | if i % 300 == 0: 255 | print(f"AE loss: {loss.item():.4f}") 256 | 257 | if i % 20 == 0 and self.mlflow_logging: 258 | mlflow.log_metrics( 259 | { 260 | "elapsed_batches": self._elapsed_batches, 261 | "train_loss.AE": loss.item(), 262 | "used_epsilon.AE": self._eps_ae, 263 | "used_epsilon.D": 0.0, 264 | "used_epsilon.total": self._eps_ae, 265 | }, 266 | step=self._elapsed_batches, 267 | ) 268 | 269 | self._eps_ae = self.privacy_engine_AE.get_epsilon(self._delta) 270 | print(f"AE pretrain used {self._eps_ae} epsilon of budget") 271 | 272 | # Ensure that models are in training mode 273 | self.G.train() 274 | self.decoder.train() 275 | 276 | # GAN training 277 | for epoch in range(n_epochs): 278 | self._elapsed_epochs += 1 279 | for i, X in enumerate(train_data): 280 | _eps = self.privacy_engine_D.get_epsilon(self._delta) 281 | 282 | self._eps = _eps + self._eps_ae 283 | if self._eps >= self._epsilon: 284 | print(f"Privacy budget reached in epoch {epoch}") 285 | return self 286 | 287 | self._elapsed_batches += 1 288 | 289 | real_X = Variable(X.type(Tensor)) 290 | 291 | # Train Discriminator 292 | self.optim_D.zero_grad() 293 | z = torch.randn(real_X.size(0), self.latent_dim, device=self.device) 294 | # This D(G(z)) seems like the wrong approach, but it's what the original author does here: https://github.com/DPautoGAN/DPautoGAN/blob/master/uci/uci.ipynb 295 | fake = self.decoder(self.G(z)).detach() 296 | real_validity = self.D(real_X) 297 | fake_validity = self.D(fake) 298 | d_loss = -torch.mean(real_validity) + torch.mean(fake_validity) 299 | d_loss.backward() 300 | self.optim_D.step() 301 | 302 | # Train Generator 303 | z = torch.randn(X.size(0), self.latent_dim, device=self.device) 304 | fake = self.decoder(self.G(z)) 305 | self.optim_G.zero_grad() 306 | g_loss = -torch.mean(self.D(fake)) 307 | g_loss.backward() 308 | self.optim_G.step() 309 | 310 | if i % 50 == 0 and self.mlflow_logging: 311 | mlflow.log_metrics( 312 | { 313 | "elapsed_batches": self._elapsed_batches, 314 | "elapsed_epochs": self._elapsed_epochs, 315 | "train_loss.G": g_loss.item(), 316 | "train_loss.D": d_loss.item(), 317 | "used_epsilon.D": _eps, 318 | "used_epsilon.total": self._eps, 319 | "validity.fake": fake_validity.mean().item(), 320 | "validity.real": real_validity.mean().item(), 321 | }, 322 | step=self._elapsed_batches, 323 | ) 324 | # Weight and Grad norms for G and D 325 | _g_norm_dict = calc_norm_dict(self.G) 326 | mlflow.log_metrics(_g_norm_dict, step=self._elapsed_batches) 327 | _d_norm_dict = calc_norm_dict(self.D) 328 | mlflow.log_metrics(_d_norm_dict, step=self._elapsed_batches) 329 | # Diversity of fakes from G and real data 330 | mlflow.log_metrics( 331 | { 332 | "X_fake.norm": fake.norm().item(), 333 | "X_real.norm": real_X.norm().item(), 334 | }, 335 | step=self._elapsed_batches, 336 | ) 337 | 338 | print( 339 | ( 340 | f"{epoch}\t[D loss: {d_loss.item()}]\t" 341 | f"[G loss: {g_loss.item()}]\t" 342 | f"Eps:{self._eps:.3f}" 343 | ) 344 | ) 345 | 346 | return self 347 | 348 | def sample(self, n=None): 349 | 350 | # Set evaluation mode 351 | self.G.eval() 352 | self.decoder.eval() 353 | n = self.batch_size if n is None else n 354 | Tensor = torch.cuda.FloatTensor if self.cuda else torch.FloatTensor 355 | with torch.no_grad(): 356 | # Sample noise as generator input 357 | z = Variable(Tensor(np.random.normal(0, 1, (n, self.latent_dim)))) 358 | 359 | out = self.decoder(self.G(z)) 360 | self.G.train() 361 | self.decoder.train() 362 | 363 | return out.detach().cpu() 364 | -------------------------------------------------------------------------------- /tablediffusion/models/dp_attention_gan.py: -------------------------------------------------------------------------------- 1 | """ 2 | Building on the state-of-the-art SAINT architecture 3 | (https://github.com/somepago/saint), we implemented an end-to-end 4 | attention model for synthesising tabular data under differential privacy. 5 | 6 | https://arxiv.org/abs/2308.14784 7 | 8 | @article{truda2023generating, 9 | title={Generating tabular datasets under differential privacy}, 10 | author={Truda, Gianluca}, 11 | journal={arXiv preprint arXiv:2308.14784}, 12 | year={2023} 13 | } 14 | """ 15 | 16 | import mlflow 17 | import numpy as np 18 | import torch 19 | from models.architectures import Discriminator, Generator 20 | from opacus import PrivacyEngine 21 | from torch import nn 22 | from torch.autograd import Variable 23 | from torch.utils.data import DataLoader, Dataset 24 | from utilities import * 25 | 26 | 27 | class MyDataset(Dataset): 28 | def __init__(self, data): 29 | self.data = data 30 | 31 | def return_data(self): 32 | return self.data 33 | 34 | def __len__(self): 35 | return self.data.shape[0] 36 | 37 | def __getitem__(self, idx): 38 | if torch.is_tensor(idx): 39 | idx = idx.tolist() 40 | 41 | X = self.data[idx, :] 42 | return torch.as_tensor(X, dtype=torch.float64) 43 | 44 | 45 | class Autoencoder(nn.Module): 46 | def __init__(self, example_dim, compression_dim, binary=False, device="cpu"): 47 | super().__init__() 48 | 49 | print(example_dim, compression_dim) 50 | 51 | self.compression_dim = compression_dim 52 | 53 | self.pre_encoder = nn.Sequential( 54 | nn.Linear(example_dim, compression_dim), nn.Tanh() if binary else nn.LeakyReLU(0.2) 55 | ).to(device) 56 | 57 | self.attn_encoder = nn.MultiheadAttention( 58 | 1, 59 | 1, 60 | dropout=0.2, 61 | bias=True, 62 | add_bias_kv=False, 63 | add_zero_attn=False, 64 | kdim=None, 65 | vdim=None, 66 | batch_first=True, 67 | ).to(device) 68 | 69 | self.decoder = nn.Sequential( 70 | nn.Linear(compression_dim, (example_dim + compression_dim) // 2), 71 | nn.Tanh() if binary else nn.LeakyReLU(0.2), 72 | nn.Linear((example_dim + compression_dim) // 2, example_dim), 73 | nn.Sigmoid(), 74 | ).to(device) 75 | 76 | def encode(self, x): 77 | x = self.pre_encoder(x) 78 | x = x.reshape(*x.shape, 1) 79 | x, attn_weights = self.attn_encoder(x, x, x) 80 | return x.squeeze() 81 | 82 | def forward(self, x): 83 | return self.decoder(self.encode(x)) 84 | 85 | def get_encoder(self): 86 | return self.encoder 87 | 88 | def get_decoder(self): 89 | return self.decoder 90 | 91 | def get_compression_dim(self): 92 | return self.compression_dim 93 | 94 | 95 | class DPattentionGAN_Synthesiser: 96 | def __init__( 97 | self, 98 | batch_size=64, 99 | gen_lr=2e-4, 100 | dis_lr=2e-4, 101 | ae_lr=0.005, 102 | latent_dim=100, 103 | gen_dims=(256, 256), 104 | dis_dims=(256, 256), 105 | ae_compress_dim=15, 106 | epsilon_target=5, 107 | max_grad_norm=1.0, 108 | ae_eps_frac=0.3, 109 | epoch_target=200, 110 | delta=1e-5, 111 | mlflow_logging=True, 112 | cuda=True, 113 | ): 114 | 115 | # Setting up GPU (if available and specified) 116 | if cuda: 117 | assert torch.cuda.is_available() 118 | self.cuda = cuda 119 | self.device = torch.device("cuda:0" if torch.cuda.is_available() and cuda else "cpu") 120 | 121 | # Hyperparameters 122 | self.batch_size = batch_size 123 | self.gen_lr = gen_lr 124 | self.dis_lr = dis_lr 125 | self.ae_lr = ae_lr 126 | self.latent_dim = latent_dim 127 | self.gen_dims = gen_dims 128 | self.dis_dims = dis_dims 129 | self.ae_compress_dim = ae_compress_dim 130 | self.max_grad_norm = max_grad_norm 131 | self.ae_eps_frac = ae_eps_frac 132 | self.epoch_target = epoch_target 133 | 134 | # Setting privacy budget 135 | self.epsilon_target = epsilon_target 136 | self._delta = delta 137 | 138 | # Logging to MLflow 139 | self.mlflow_logging = mlflow_logging 140 | if self.mlflow_logging: 141 | _param_dict = gather_object_params(self, prefix="init.") 142 | mlflow.log_params(_param_dict) 143 | 144 | # Initialise training variables 145 | self._elapsed_batches = 0 146 | self._elapsed_epochs = 0 147 | self._epsilon = epsilon_target 148 | self._eps = 0 149 | 150 | def fit(self, train_data, n_epochs=10, epsilon=100): 151 | 152 | self._epsilon = epsilon 153 | 154 | Tensor = torch.cuda.FloatTensor if self.cuda else torch.FloatTensor 155 | self.data_dim = train_data.shape[-1] 156 | self.data_n = train_data.shape[0] 157 | 158 | if not isinstance(train_data, DataLoader): 159 | train_data = DataLoader(MyDataset(train_data), batch_size=self.batch_size) 160 | 161 | # Check if training for first time or continuing (don't reinitialise) 162 | if self._elapsed_batches == 0: 163 | 164 | self.AE = Autoencoder( 165 | example_dim=self.data_dim, 166 | compression_dim=self.ae_compress_dim, 167 | binary=False, 168 | device=self.device, 169 | ) 170 | self.decoder = self.AE.decoder 171 | 172 | self.G = Generator( 173 | self.latent_dim, self.AE.get_compression_dim(), gen_dims=self.gen_dims 174 | ).to(self.device) 175 | self.D = Discriminator(self.data_dim, dis_dims=self.dis_dims).to(self.device) 176 | 177 | self._nparams_ae = count_parameters(self.AE) 178 | self._nparams_g = count_parameters(self.G) 179 | self._nparams_d = count_parameters(self.D) 180 | 181 | if self.mlflow_logging: 182 | mlflow.log_params( 183 | { 184 | "nparams.AE": self._nparams_ae, 185 | "nparams.G": self._nparams_g, 186 | "nparams.D": self._nparams_d, 187 | "nparams.total": self._nparams_ae + self._nparams_g + self._nparams_d, 188 | } 189 | ) 190 | _model_desc = str(self.AE) + "\n" + str(self.G) + "\n" + str(self.D) 191 | mlflow.log_text(_model_desc, "model_desription.txt") 192 | 193 | self.optim_enc = torch.optim.Adam( 194 | params=list(self.AE.pre_encoder.parameters()) 195 | + list(self.AE.attn_encoder.parameters()), 196 | lr=self.ae_lr, 197 | betas=(0.9, 0.999), 198 | weight_decay=0, 199 | ) 200 | 201 | self.optim_dec = torch.optim.Adam( 202 | params=self.AE.get_decoder().parameters(), 203 | lr=self.ae_lr, 204 | betas=(0.9, 0.999), 205 | weight_decay=0, 206 | ) 207 | 208 | self.privacy_engine_AE = PrivacyEngine(accountant="rdp", secure_mode=False) 209 | ( 210 | self.AE.decoder, 211 | self.optim_dec, 212 | train_data, 213 | ) = self.privacy_engine.make_private_with_epsilon( 214 | module=self.AE.get_decoder(), 215 | optimizer=self.optim_dec, 216 | data_loader=train_data, 217 | target_epsilon=self.ae_eps_frac * self.epsilon_target, 218 | target_delta=self._delta, 219 | epochs=1, 220 | max_grad_norm=self.max_grad_norm, 221 | poisson_sampling=True, 222 | ) 223 | 224 | # Log privacy engine and optimiser parameters 225 | if self.mlflow_logging: 226 | _param_dict = gather_object_params( 227 | self.privacy_engine_AE, prefix="privacy_engine_AE." 228 | ) 229 | mlflow.log_params(_param_dict) 230 | _param_dict = gather_object_params(self.optim_dec, prefix="optim_dec.") 231 | mlflow.log_params(_param_dict) 232 | 233 | self.optim_G = torch.optim.RMSprop( 234 | params=self.G.parameters(), lr=self.gen_lr, alpha=0.99, weight_decay=0 235 | ) 236 | 237 | self.optim_D = torch.optim.RMSprop( 238 | params=self.D.parameters(), lr=self.dis_lr, alpha=0.99, weight_decay=0 239 | ) 240 | 241 | self.privacy_engine_D = PrivacyEngine(accountant="rdp", secure_mode=False) 242 | self.D, self.optim_D, train_data = self.privacy_engine.make_private_with_epsilon( 243 | module=self.D, 244 | optimizer=self.optim_D, 245 | target_epsilon=self.epsilon_target * (1 / self.ae_eps_frac), 246 | target_delta=self._delta, 247 | epochs=n_epochs, 248 | max_grad_norm=self.max_grad_norm, 249 | poisson_sampling=True, 250 | ) 251 | 252 | # Log privacy engine and optimiser parameters 253 | if self.mlflow_logging: 254 | _param_dict = gather_object_params( 255 | self.privacy_engine_D, prefix="privacy_engine_D." 256 | ) 257 | mlflow.log_params(_param_dict) 258 | _param_dict = gather_object_params(self.optim_D, prefix="optim_D.") 259 | mlflow.log_params(_param_dict) 260 | 261 | self.ae_criterion = nn.BCELoss() 262 | 263 | # AE pretraining 264 | self._elapsed_batches += 1 265 | for i, X in enumerate(train_data): 266 | self._eps_ae = self.privacy_engine_AE.get_epsilon(self._delta) 267 | if self._eps_ae >= self._epsilon: 268 | print(f"Privacy budget reached in pre-training ({self._eps_ae})") 269 | return self 270 | 271 | self._elapsed_batches += 1 272 | self.optim_enc.zero_grad() 273 | self.optim_dec.zero_grad() 274 | real_X = Variable(X.type(Tensor)) 275 | output = self.AE(real_X) 276 | loss = self.ae_criterion(output, real_X) 277 | loss.backward() 278 | self.optim_enc.step() 279 | self.optim_dec.step() 280 | 281 | if i % 300 == 0: 282 | print(f"AE loss: {loss.item():.4f}") 283 | 284 | if i % 20 == 0 and self.mlflow_logging: 285 | mlflow.log_metrics( 286 | { 287 | "elapsed_batches": self._elapsed_batches, 288 | "train_loss.AE": loss.item(), 289 | "used_epsilon.AE": self._eps_ae, 290 | "used_epsilon.D": 0.0, 291 | "used_epsilon.total": self._eps_ae, 292 | }, 293 | step=self._elapsed_batches, 294 | ) 295 | 296 | self._eps_ae = self.privacy_engine_D.get_epsilon(self._delta) 297 | print(f"AE pretrain used {self._eps_ae} epsilon of budget") 298 | 299 | # Ensure that models are in training mode 300 | self.G.train() 301 | self.decoder.train() 302 | 303 | # GAN training 304 | for epoch in range(n_epochs): 305 | self._elapsed_epochs += 1 306 | for i, X in enumerate(train_data): 307 | _eps = self.privacy_engine_D.get_epsilon(self._delta) 308 | self._eps = _eps + self._eps_ae 309 | if self._eps >= self._epsilon: 310 | print(f"Privacy budget reached in epoch {epoch}") 311 | return self 312 | 313 | self._elapsed_batches += 1 314 | 315 | real_X = Variable(X.type(Tensor)) 316 | 317 | # Train Discriminator 318 | self.optim_D.zero_grad() 319 | z = torch.randn(real_X.size(0), self.latent_dim, device=self.device) 320 | fake = self.decoder(self.G(z)).detach() 321 | real_validity = self.D(real_X) 322 | fake_validity = self.D(fake) 323 | d_loss = -torch.mean(real_validity) + torch.mean(fake_validity) 324 | d_loss.backward() 325 | self.optim_D.step() 326 | 327 | # Train Generator 328 | z = torch.randn(X.size(0), self.latent_dim, device=self.device) 329 | fake = self.decoder(self.G(z)) 330 | self.optim_G.zero_grad() 331 | g_loss = -torch.mean(self.D(fake)) 332 | g_loss.backward() 333 | self.optim_G.step() 334 | 335 | if i % 50 == 0 and self.mlflow_logging: 336 | mlflow.log_metrics( 337 | { 338 | "elapsed_batches": self._elapsed_batches, 339 | "elapsed_epochs": self._elapsed_epochs, 340 | "train_loss.G": g_loss.item(), 341 | "train_loss.D": d_loss.item(), 342 | "used_epsilon.D": _eps, 343 | "used_epsilon.total": self._eps, 344 | # "best_alpha": self._best_alpha, 345 | "validity.fake": fake_validity.mean().item(), 346 | "validity.real": real_validity.mean().item(), 347 | }, 348 | step=self._elapsed_batches, 349 | ) 350 | # Weight and Grad norms for G and D 351 | _g_norm_dict = calc_norm_dict(self.G) 352 | mlflow.log_metrics(_g_norm_dict, step=self._elapsed_batches) 353 | _d_norm_dict = calc_norm_dict(self.D) 354 | mlflow.log_metrics(_d_norm_dict, step=self._elapsed_batches) 355 | # Diversity of fakes from G and real data 356 | mlflow.log_metrics( 357 | { 358 | "X_fake.norm": fake.norm().item(), 359 | "X_real.norm": real_X.norm().item(), 360 | }, 361 | step=self._elapsed_batches, 362 | ) 363 | 364 | print( 365 | ( 366 | f"{epoch}\t[D loss: {d_loss.item()}]\t" 367 | f"[G loss: {g_loss.item()}]\t" 368 | f"Eps:{self._eps:.3f}" 369 | ) 370 | ) 371 | 372 | return self 373 | 374 | def sample(self, n=None): 375 | 376 | # Set evaluation mode 377 | self.G.eval() 378 | self.decoder.eval() 379 | n = self.batch_size if n is None else n 380 | Tensor = torch.cuda.FloatTensor if self.cuda else torch.FloatTensor 381 | with torch.no_grad(): 382 | # Sample noise as generator input 383 | z = Variable(Tensor(np.random.normal(0, 1, (n, self.latent_dim)))) 384 | 385 | out = self.decoder(self.G(z)) 386 | self.G.train() 387 | self.decoder.train() 388 | 389 | return out.detach().cpu() 390 | -------------------------------------------------------------------------------- /tablediffusion/models/table_diffusion.py: -------------------------------------------------------------------------------- 1 | """ 2 | Code for the `TableDiffusion` model: 3 | The first differentially-private diffusion model for tabular datasets. 4 | 5 | https://arxiv.org/abs/2308.14784 6 | 7 | @article{truda2023generating, 8 | title={Generating tabular datasets under differential privacy}, 9 | author={Truda, Gianluca}, 10 | journal={arXiv preprint arXiv:2308.14784}, 11 | year={2023} 12 | } 13 | """ 14 | 15 | import warnings 16 | 17 | import mlflow 18 | import numpy as np 19 | import pandas as pd 20 | import torch 21 | from matplotlib import pyplot as plt 22 | from models.architectures import Generator 23 | from opacus import PrivacyEngine 24 | from sklearn.preprocessing import OneHotEncoder, QuantileTransformer 25 | from torch import nn 26 | from torch.autograd import Variable 27 | from torch.utils.data import DataLoader 28 | from utilities import * 29 | 30 | # Ignore opacus hook warnings 31 | warnings.filterwarnings( 32 | "ignore", 33 | message="Using a non-full backward hook when the forward contains multiple autograd Nodes", 34 | ) 35 | 36 | # Function to compute the cosine noise schedule 37 | def get_beta(t, T): 38 | return (1 - np.cos((np.pi * t) / T)) / 2 + 0.1 39 | 40 | class MixedTypeGenerator(Generator): 41 | def __init__( 42 | self, 43 | embedding_dim, 44 | data_dim, 45 | gen_dims=(256, 256), 46 | predict_noise=True, 47 | categorical_start_idx=None, 48 | cat_counts=None, 49 | ): 50 | # Initialise parent (Generator) with the parameters 51 | super().__init__(embedding_dim, data_dim, gen_dims) 52 | self.categorical_start_idx = categorical_start_idx 53 | self.cat_counts = cat_counts 54 | self.predict_noise = predict_noise 55 | 56 | def forward(self, x): 57 | data = self.seq(x) 58 | 59 | if self.predict_noise: 60 | # Just predicting gaussian noise 61 | return data 62 | 63 | # Split into numerical and categorical outputs 64 | numerical_outputs = data[:, : self.categorical_start_idx] 65 | categorical_outputs = data[:, self.categorical_start_idx :] 66 | _idx = 0 67 | # Softmax over each category 68 | for k, v in self.cat_counts.items(): 69 | categorical_outputs[:, _idx : _idx + v] = torch.softmax( 70 | categorical_outputs[:, _idx : _idx + v], dim=-1 71 | ) 72 | _idx += v 73 | return torch.cat((numerical_outputs, categorical_outputs), dim=-1) 74 | 75 | 76 | class TableDiffusion_Synthesiser: 77 | def __init__( 78 | self, 79 | batch_size=1024, 80 | lr=0.005, 81 | b1=0.5, 82 | b2=0.999, 83 | dims=(128, 128), 84 | diffusion_steps=5, 85 | predict_noise=True, 86 | max_grad_norm=1.0, 87 | epsilon_target=1.0, 88 | epoch_target=5, 89 | delta=1e-5, 90 | sample_img_interval=None, 91 | mlflow_logging=True, 92 | cuda=True, 93 | ): 94 | from datetime import datetime 95 | self._now = datetime.now().strftime("%m%d%H%M%S") 96 | # Setting up GPU (if available and specified) 97 | if cuda: 98 | assert torch.cuda.is_available() 99 | self.cuda = cuda 100 | self.device = torch.device("cuda:0" if torch.cuda.is_available() and cuda else "cpu") 101 | 102 | # Hyperparameters 103 | self.batch_size = batch_size 104 | self.lr = lr 105 | self.b1 = b1 106 | self.b2 = b2 107 | self.dims = dims 108 | self.diffusion_steps = diffusion_steps 109 | self.pred_noise = predict_noise 110 | self.max_grad_norm = max_grad_norm 111 | self.epoch_target = epoch_target 112 | self.sample_img_interval = sample_img_interval 113 | 114 | # Setting privacy budget 115 | self.epsilon_target = epsilon_target 116 | self._delta = delta 117 | 118 | # Logging to MLflow 119 | self.mlflow_logging = mlflow_logging 120 | if self.mlflow_logging: 121 | _param_dict = gather_object_params(self, prefix="init.") 122 | mlflow.log_params(_param_dict) 123 | 124 | # Initialise training variables 125 | self._elapsed_batches = 0 126 | self._elapsed_epochs = 0 127 | self._epsilon = epsilon_target 128 | self._eps = 0 129 | 130 | def fit(self, df, n_epochs=10, epsilon=100, discrete_columns=[], verbose=True): 131 | 132 | self._epsilon = epsilon 133 | self.data_dim = df.shape[1] 134 | self.data_n = df.shape[0] 135 | self.disc_columns = discrete_columns 136 | 137 | Tensor = torch.cuda.FloatTensor if self.cuda else torch.FloatTensor 138 | 139 | self.q_transformers = {} 140 | self.encoders = {} 141 | self.category_counts = {} 142 | 143 | # Preprocessing 144 | self._original_types = df.dtypes 145 | self._original_columns = df.columns 146 | df_encoded = df.select_dtypes(include="number").copy() # numerical features 147 | df_encoded_cat = pd.DataFrame() # categorical features 148 | for col in df.columns: 149 | if col in self.disc_columns: 150 | self.encoders[col] = OneHotEncoder(sparse_output=False, handle_unknown="ignore") 151 | transformed = self.encoders[col].fit_transform(df[col].values.reshape(-1, 1)) 152 | transformed_df = pd.DataFrame( 153 | transformed, columns=[f"{col}_{i}" for i in range(transformed.shape[1])] 154 | ) 155 | df_encoded_cat = pd.concat([df_encoded_cat, transformed_df], axis=1) 156 | # Log the number of categories for each discrete column 157 | self.category_counts[col] = transformed_df.shape[1] 158 | else: 159 | self.q_transformers[col] = QuantileTransformer() 160 | df_encoded[col] = self.q_transformers[col].fit_transform( 161 | df[col].values.reshape(-1, 1) 162 | ) 163 | df_encoded = pd.concat([df_encoded, df_encoded_cat], axis=1) 164 | 165 | categorical_start_idx = transformed_df.shape[1] + 1 166 | self.total_categories = sum(self.category_counts.values()) 167 | self.encoded_columns = df_encoded.columns # store the column names of the encoded data 168 | self.data_dim = df_encoded.shape[1] # store the dimensionality of the encoded data 169 | self.data_n = df_encoded.shape[0] # store the total number of data points 170 | 171 | # Convert df to tensor and wrap in DataLoader 172 | train_data = DataLoader( 173 | torch.from_numpy(df_encoded.values.astype(np.float32)).to(self.device), 174 | batch_size=self.batch_size, 175 | drop_last=False, 176 | ) 177 | 178 | # Create MLP model 179 | self.model = MixedTypeGenerator( 180 | df_encoded.shape[1], 181 | self.data_dim, 182 | self.dims, 183 | self.pred_noise, 184 | categorical_start_idx, 185 | self.category_counts, 186 | ).to(self.device) 187 | if verbose: 188 | print(self.model) 189 | self._nparams = count_parameters(self.model) 190 | 191 | if self.mlflow_logging: 192 | mlflow.log_params( 193 | { 194 | "nparams.total": self._nparams, 195 | } 196 | ) 197 | 198 | # Initialise optimiser (and scheduler) 199 | self.optim = torch.optim.Adam( 200 | self.model.parameters(), 201 | lr=self.lr, 202 | betas=(self.b1, self.b2), 203 | ) 204 | 205 | self.privacy_engine = PrivacyEngine(accountant="rdp", secure_mode=False) 206 | self.model, self.optim, train_data = self.privacy_engine.make_private_with_epsilon( 207 | module=self.model, 208 | optimizer=self.optim, 209 | data_loader=train_data, 210 | target_epsilon=self.epsilon_target, 211 | target_delta=self._delta, 212 | epochs=self.epoch_target, 213 | max_grad_norm=self.max_grad_norm, 214 | poisson_sampling=True, 215 | ) 216 | 217 | # Log privacy engine and optimiser parameters 218 | if self.mlflow_logging: 219 | _param_dict = gather_object_params(self.privacy_engine, prefix="privacy_engine.") 220 | mlflow.log_params(_param_dict) 221 | _param_dict = gather_object_params(self.optim, prefix="optim.") 222 | mlflow.log_params(_param_dict) 223 | 224 | # Define loss functions 225 | mse_loss = nn.MSELoss() 226 | kl_loss = nn.KLDivLoss(reduction="batchmean") 227 | 228 | # Enforce training mode 229 | self.model.train() 230 | 231 | # Training loop 232 | for epoch in range(n_epochs): 233 | self._elapsed_epochs += 1 234 | for i, X in enumerate(train_data): 235 | # Check if loss is NaN and early stop 236 | if i > 2 and loss.isnan(): 237 | print("Loss is NaN. Early stopping.") 238 | return self 239 | if self.sample_img_interval is not None and i % self.sample_img_interval == 0: 240 | fig, axs = plt.subplots(self.diffusion_steps, 5, figsize=(4*self.diffusion_steps, 4*5)) 241 | 242 | self._elapsed_batches += 1 243 | 244 | # Configure input 245 | real_X = Variable(X.type(Tensor)) 246 | agg_loss = torch.Tensor([0]).to(self.device) 247 | 248 | # Diffusion process with cosine noise schedule 249 | for t in range(self.diffusion_steps): 250 | self._eps = self.privacy_engine.get_epsilon(self._delta) 251 | if self._eps >= self.epsilon_target: 252 | print(f"Privacy budget reached in epoch {epoch} (batch {i}, {t=}).") 253 | return self 254 | beta_t = get_beta(t, self.diffusion_steps) 255 | noise = torch.randn_like(real_X).to(self.device) * np.sqrt(beta_t) 256 | noised_data = real_X + noise 257 | if self.sample_img_interval is not None and i % self.sample_img_interval == 0: 258 | print(f"Epoch {epoch} (batch {i}, {t=}), {np.sqrt(beta_t)=}") 259 | 260 | if self.pred_noise: 261 | # Use the model as a diffusion noise predictor 262 | predicted_noise = self.model(noised_data) 263 | 264 | # Calculate loss between predicted and actualy noise using MSE 265 | numeric_loss = mse_loss(predicted_noise, noise) 266 | categorical_loss = torch.tensor(0.0) 267 | loss = numeric_loss 268 | 269 | else: 270 | # Use the model as a mixed-type denoiser 271 | denoised_data = self.model(noised_data) 272 | 273 | # Calculate numeric loss using MSE 274 | numeric_loss = mse_loss( 275 | denoised_data[:, :categorical_start_idx], 276 | real_X[:, :categorical_start_idx], 277 | ) 278 | 279 | # Convert categoricals to log-space (to avoid underflow issue) and calculate KL loss for each original feature 280 | _idx = categorical_start_idx 281 | categorical_losses = [] 282 | for _col, _cat_len in self.category_counts.items(): 283 | categorical_losses.append( 284 | kl_loss( 285 | torch.log(denoised_data[:, _idx : _idx + _cat_len]), 286 | real_X[:, _idx : _idx + _cat_len], 287 | ) 288 | ) 289 | _idx += _cat_len 290 | 291 | # Average categorical losses over total number of categories across all categorical features 292 | categorical_loss = ( 293 | sum(categorical_losses) / self.total_categories 294 | if categorical_losses 295 | else 0 296 | ) 297 | 298 | loss = numeric_loss + categorical_loss 299 | 300 | if self.sample_img_interval is not None and i % self.sample_img_interval == 0: 301 | with torch.no_grad(): 302 | ax = axs[t] 303 | ax[0].imshow(X.clone().detach().cpu().numpy()); ax[0].set_title("X") 304 | ax[1].imshow(noise.clone().detach().cpu().numpy()); ax[1].set_title(f"noise_{t}") 305 | ax[2].imshow(noised_data.clone().detach().cpu().numpy()); ax[2].set_title(f"noised_data_{t}") 306 | if self.pred_noise: 307 | ax[3].imshow(predicted_noise.clone().detach().cpu().numpy()); ax[3].set_title(f"predicted_noise_{t}") 308 | denoised_data = noised_data - predicted_noise*np.sqrt(beta_t) 309 | ax[4].imshow(denoised_data.clone().detach().cpu().numpy()); ax[4].set_title(f"denoised_data_{t}") 310 | 311 | # Add losses from each diffusion step 312 | agg_loss += loss 313 | 314 | # Average loss over diffusion steps 315 | loss = agg_loss / self.diffusion_steps 316 | print(f"Batches: {self._elapsed_batches}, {agg_loss=}") 317 | 318 | # Backward propagation and optimization step 319 | self.optim.zero_grad() 320 | loss.backward() 321 | self.optim.step() 322 | 323 | 324 | if self.sample_img_interval is not None and i % self.sample_img_interval == 0: 325 | plt.savefig(f"../results/diffusion_figs/{self._now}_forward_T{self.diffusion_steps}_B{self._elapsed_batches}.png") 326 | sample = self.sample(n=X.shape[0], post_process=False) 327 | plt.cla(); plt.clf() 328 | plt.imshow(sample) 329 | plt.savefig(f"../results/diffusion_figs/{self._now}_sample_T{self.diffusion_steps}_B{self._elapsed_batches}.png") 330 | 331 | if i % 20 == 0: 332 | if verbose: 333 | print( 334 | f"[Epoch {epoch}/{n_epochs}] [Batch {i}/{len(train_data)}] numerical loss: {numeric_loss.item():.6f}, categorical loss: {categorical_loss.item():.6f}, epsilon: {self._eps:.6f}" 335 | ) 336 | if self.mlflow_logging: 337 | mlflow.log_metrics( 338 | { 339 | "elapsed_batches": self._elapsed_batches, 340 | "elapsed_epochs": self._elapsed_epochs, 341 | "train_loss.numerical": numeric_loss.item(), 342 | "train_loss.categorical": categorical_loss.item(), 343 | "train_loss.total": loss.item(), 344 | "used_epsilon.total": self._eps, 345 | }, 346 | step=self._elapsed_batches, 347 | ) 348 | 349 | # Log weight and grad norms 350 | _norm_dict = calc_norm_dict(self.model) 351 | mlflow.log_metrics(_norm_dict, step=self._elapsed_batches) 352 | 353 | return self 354 | 355 | def sample(self, n=None, post_process=True): 356 | self.model.eval() 357 | n = self.batch_size if n is None else n 358 | # Generate noise samples 359 | samples = torch.randn((n, self.data_dim)).to(self.device) 360 | fig, axs = plt.subplots(self.diffusion_steps, 4, figsize=(4*self.diffusion_steps, 4*4)) 361 | 362 | # Generate synthetic data by runnin reverse diffusion process 363 | with torch.no_grad(): 364 | for t in range(self.diffusion_steps -1, -1, -1): 365 | beta_t = get_beta(t, self.diffusion_steps) 366 | noise_scale = np.sqrt(beta_t) 367 | print(f"Sampling {t=}, {np.sqrt(beta_t)=}") 368 | ax = axs[self.diffusion_steps - t - 1] 369 | ax[2].imshow(samples.clone().detach().cpu().numpy()); ax[2].set_title(f"samples_{t}") 370 | 371 | if self.pred_noise: 372 | # Repeatedly predict and subtract noise 373 | pred_noise = self.model(samples) 374 | predicted_noise = pred_noise * noise_scale 375 | ax[0].imshow(pred_noise.clone().detach().cpu().numpy()); ax[0].set_title(f"pred_noise_{t}") 376 | ax[1].imshow(predicted_noise.clone().detach().cpu().numpy()); ax[1].set_title(f"predicted_noise_{t}") 377 | 378 | samples = samples - predicted_noise 379 | else: 380 | # Repeatedly denoise 381 | samples = self.model(samples) 382 | ax[3].imshow(samples.clone().detach().cpu().numpy()); ax[3].set_title(f"samples_{t-1}") 383 | 384 | if self.sample_img_interval is not None: 385 | plt.savefig(f"../results/diffusion_figs/{self._now}_reverse_T{self.diffusion_steps}_B{self._elapsed_batches}.png") 386 | 387 | synthetic_data = samples.detach().cpu().numpy() 388 | self.model.train() 389 | 390 | if not post_process: 391 | return synthetic_data 392 | 393 | # Postprocessing: apply inverse transformations 394 | df_synthetic = pd.DataFrame(synthetic_data, columns=self.encoded_columns) 395 | for col in self.encoders: 396 | transformed_cols = [c for c in df_synthetic.columns if c.startswith(f"{col}_")] 397 | if transformed_cols: 398 | encoded_data = df_synthetic[transformed_cols].values 399 | df_synthetic[col] = self.encoders[col].inverse_transform(encoded_data).ravel() 400 | df_synthetic = df_synthetic.drop(columns=transformed_cols) 401 | 402 | for col in self.q_transformers: 403 | df_synthetic[col] = self.q_transformers[col].inverse_transform( 404 | df_synthetic[col].values.reshape(-1, 1) 405 | ) 406 | 407 | # Cast to the original datatypes for dataframe compatibility 408 | df_synthetic = df_synthetic.astype(self._original_types) 409 | # Order the columns as they were in the original dataframe 410 | df_synthetic = df_synthetic[self._original_columns] 411 | 412 | return df_synthetic 413 | -------------------------------------------------------------------------------- /tablediffusion/models/dp_attention_vae.py: -------------------------------------------------------------------------------- 1 | """ 2 | Building on the state-of-the-art SAINT architecture 3 | (https://github.com/somepago/saint), we implemented an end-to-end 4 | attention model for synthesising tabular data under differential privacy. 5 | 6 | https://arxiv.org/abs/2308.14784 7 | 8 | @article{truda2023generating, 9 | title={Generating tabular datasets under differential privacy}, 10 | author={Truda, Gianluca}, 11 | journal={arXiv preprint arXiv:2308.14784}, 12 | year={2023} 13 | } 14 | """ 15 | 16 | import mlflow 17 | import numpy as np 18 | import pandas as pd 19 | import torch 20 | import torch.optim as optim 21 | from models.architectures import Decoder, Encoder 22 | from models.saint_ae import SAINT_AE 23 | from opacus import PrivacyEngine 24 | from sklearn.preprocessing import LabelEncoder 25 | from torch import nn 26 | from torch.utils.data import DataLoader 27 | from utilities import * 28 | from utilities.saint_utils import DataSetCatCon, embed_data_mask, mdn_loss 29 | 30 | 31 | class DPattentionVAE_Synthesiser: 32 | def __init__( 33 | self, 34 | batch_size=512, 35 | embedding_size=64, 36 | b1=0.5, 37 | b2=0.999, 38 | latent_dim=100, 39 | dec_dims=(256, 256), 40 | enc_dims=(256, 256), 41 | n_critic=5, 42 | lr_trans=0.0005, 43 | lr_mlps=0.01, 44 | lr_vae=1e-3, 45 | transformer_depth=1, 46 | attention_heads=3, 47 | mdn=True, 48 | mdn_heads=7, 49 | loss_weight_cat=1.0, 50 | loss_weight_cont=1.0, 51 | loss_weight_kld=1.0, 52 | max_grad_norm=1.0, 53 | epsilon_target=5, 54 | epoch_target=5, 55 | pretrain_epochs=0, 56 | delta=1e-5, 57 | mlflow_logging=True, 58 | cuda=True, 59 | **kwargs, 60 | ): 61 | # Setting up GPU (if available and specified) 62 | if cuda: 63 | assert torch.cuda.is_available() 64 | self.cuda = cuda 65 | self.device = torch.device("cuda:0" if torch.cuda.is_available() and cuda else "cpu") 66 | 67 | # Hyperparameters 68 | self.batch_size = batch_size 69 | self.lr_trans = lr_trans 70 | self.lr_mlps = lr_mlps 71 | self.embedding_size = embedding_size 72 | self.lr_vae = lr_vae 73 | self.b1, self.b2 = b1, b2 74 | self.latent_dim = latent_dim 75 | self.dec_dims = dec_dims 76 | self.enc_dims = enc_dims 77 | self.n_critic = n_critic 78 | self.transformer_depth = transformer_depth 79 | self.attention_heads = attention_heads 80 | self.mdn = mdn 81 | self.mdn_heads = mdn_heads 82 | self.lw_cat = loss_weight_cat 83 | self.lw_cont = loss_weight_cont 84 | self.lw_reg = loss_weight_kld 85 | self.max_grad_norm = max_grad_norm 86 | self.epoch_target = epoch_target 87 | self.pretrain_epochs = pretrain_epochs 88 | 89 | # Setting privacy budget 90 | self.epsilon_target = epsilon_target 91 | self._delta = delta 92 | 93 | # Logging to MLflow 94 | self.mlflow_logging = mlflow_logging 95 | if self.mlflow_logging: 96 | _param_dict = gather_object_params(self, prefix="init.") 97 | mlflow.log_params(_param_dict) 98 | 99 | # Initialise training variables 100 | self._elapsed_batches = 0 101 | self._elapsed_epochs = 0 102 | self._epsilon = epsilon_target 103 | self._eps = 0 104 | 105 | def fit( 106 | self, train_data, discrete_columns=(), n_epochs=7, epsilon=100, verbose=True, **kwargs 107 | ): 108 | 109 | self._epsilon = epsilon 110 | self.data_dim = train_data.shape[-1] 111 | self.data_n = train_data.shape[0] 112 | 113 | if verbose: 114 | print(f"Device is {self.device}.") 115 | 116 | Tensor = torch.cuda.FloatTensor if self.cuda else torch.FloatTensor 117 | self.dset_shape = train_data.shape 118 | self.colnames = train_data.columns 119 | 120 | self.disc_cols = list(discrete_columns) 121 | self.numeric_cols = [c for c in self.colnames if c not in self.disc_cols] 122 | self.cat_idxs = [i for i, c in enumerate(self.colnames) if c in self.disc_cols] 123 | 124 | # The cardinality of each categorical feature 125 | cat_dims = [train_data.iloc[:, i].nunique() for i in self.cat_idxs] 126 | 127 | self.con_idxs = [i for i, _ in enumerate(self.colnames) if i not in self.cat_idxs] 128 | 129 | # Encode categoricals 130 | self.cat_label_encs = [] 131 | for i in self.cat_idxs: 132 | l_enc = LabelEncoder() 133 | train_data.iloc[:, i] = l_enc.fit_transform(train_data.values[:, i]) 134 | # store labels for inverse transform 135 | self.cat_label_encs.append(l_enc) 136 | 137 | # TODO do I even need this still? 138 | train_mean = train_data.values[:, self.con_idxs].mean() 139 | train_std = train_data.values[:, self.con_idxs].std() 140 | continuous_mean_std = np.array([train_mean, train_std]).astype(np.float32) 141 | 142 | # Appending 1 for CLS token, this is later used to generate embeddings. 143 | cat_dims = np.append(np.array([1]), np.array(cat_dims)).astype(int) 144 | 145 | # Check if training for first time or continuing (don't reinitialise) 146 | if self._elapsed_batches == 0: 147 | 148 | # Initialise transformer-based Autoencoder 149 | self.AE = SAINT_AE( 150 | categories=tuple(cat_dims), 151 | num_continuous=len(self.con_idxs), 152 | dim=self.embedding_size, 153 | transformer_depth=self.transformer_depth, 154 | attention_heads=self.attention_heads, 155 | mdn=self.mdn, 156 | mdn_heads=self.mdn_heads, 157 | ).to(self.device) 158 | 159 | # Initialise generator and discriminator 160 | self.enc = Encoder(self.embedding_size, self.enc_dims, self.latent_dim).to(self.device) 161 | self.dec = Decoder(self.latent_dim, self.dec_dims, self.embedding_size).to(self.device) 162 | 163 | # Count and log model parameters 164 | self._nparams_ae = count_parameters(self.AE) 165 | self._nparams_trans = count_parameters(self.AE.transformer, verbose=False) 166 | self._nparams_mlp1 = count_parameters(self.AE.mlp1, verbose=False) 167 | self._nparams_mlp2 = count_parameters(self.AE.mlp2, verbose=False) 168 | self._nparams_enc = count_parameters(self.enc) 169 | self._nparams_dec = count_parameters(self.dec) 170 | self.total_params = self._nparams_dec + self._nparams_enc + self._nparams_ae 171 | 172 | if self.mlflow_logging: 173 | mlflow.log_params( 174 | { 175 | "nparams.AE": self._nparams_ae, 176 | "nparams.trans": self._nparams_trans, 177 | "nparams.mlp1": self._nparams_mlp1, 178 | "nparams.mlp2": self._nparams_mlp2, 179 | "nparams.enc": self._nparams_enc, 180 | "nparams.dec": self._nparams_dec, 181 | "nparams.total": self.total_params, 182 | } 183 | ) 184 | _model_desc = str(self.AE) + "\n" + str(self.dec) + "\n" + str(self.enc) 185 | mlflow.log_text(_model_desc, "model_desription.txt") 186 | 187 | # Make the dataset and dataloader 188 | train_ds = DataSetCatCon( 189 | train_data, 190 | self.cat_idxs, 191 | # continuous_mean_std, # Normalisation 192 | ) 193 | trainloader = DataLoader(train_ds, batch_size=self.batch_size, shuffle=True) 194 | self.trainloader = trainloader # Needed later for pseudo-sampling 195 | 196 | # Initialise optimisers 197 | self.optim_trans = optim.AdamW(self.AE.transformer.parameters(), lr=self.lr_trans) 198 | self.optim_mlp1 = optim.Adam(self.AE.mlp1.parameters(), lr=self.lr_mlps) 199 | self.optim_mlp2 = optim.Adam(self.AE.mlp2.parameters(), lr=self.lr_mlps) 200 | self.optim_VAE = torch.optim.Adam( 201 | list(self.enc.parameters()) + list(self.dec.parameters()), 202 | lr=self.lr_vae, 203 | ) 204 | 205 | # Initialise and attach privacy engines 206 | self.privacy_engine_1 = PrivacyEngine(accountant="rdp", secure_mode=False) 207 | ( 208 | self.AE.mlp1, 209 | self.optim_mlp1, 210 | trainloader, 211 | ) = self.privacy_engine_1.make_private_with_epsilon( 212 | module=self.AE.mlp1, 213 | optimizer=self.optim_mlp1, 214 | data_loader=trainloader, 215 | target_epsilon=self.epsilon_target / 2, 216 | target_delta=self._delta, 217 | epochs=self.epoch_target, 218 | max_grad_norm=self.max_grad_norm, 219 | poisson_sampling=True, 220 | ) 221 | self.privacy_engine_2 = PrivacyEngine(accountant="rdp", secure_mode=False) 222 | ( 223 | self.AE.mlp2, 224 | self.optim_mlp2, 225 | trainloader, 226 | ) = self.privacy_engine_2.make_private_with_epsilon( 227 | module=self.AE.mlp2, 228 | optimizer=self.optim_mlp2, 229 | data_loader=trainloader, 230 | target_epsilon=self.epsilon_target / 2, 231 | target_delta=self._delta, 232 | epochs=self.epoch_target - self.pretrain_epochs, 233 | max_grad_norm=self.max_grad_norm, 234 | poisson_sampling=True, 235 | ) 236 | 237 | # Log privacy engine and optimiser parameters 238 | if self.mlflow_logging: 239 | _param_dict = gather_object_params( 240 | self.privacy_engine_1, prefix="privacy_engine_1." 241 | ) 242 | mlflow.log_params(_param_dict) 243 | _param_dict = gather_object_params(self.optim_mlp1, prefix="optim_mlp1.") 244 | mlflow.log_params(_param_dict) 245 | _param_dict = gather_object_params( 246 | self.privacy_engine_2, prefix="privacy_engine_2." 247 | ) 248 | mlflow.log_params(_param_dict) 249 | _param_dict = gather_object_params(self.optim_mlp2, prefix="optim_mlp2.") 250 | mlflow.log_params(_param_dict) 251 | 252 | # Loss criteria 253 | criterion1 = nn.CrossEntropyLoss() 254 | criterion2 = nn.MSELoss() 255 | 256 | # Enforce training mode 257 | self.AE.train() 258 | self.dec.train() 259 | self.enc.train() 260 | 261 | if verbose: 262 | print("Training...") 263 | 264 | for epoch in range(n_epochs): 265 | self._elapsed_epochs += 1 266 | for i, data in enumerate(trainloader, 0): 267 | self._eps1 = self.privacy_engine_1.get_epsilon(self._delta) 268 | self._eps2 = self.privacy_engine_2.get_epsilon(self._delta) 269 | 270 | # TODO additive? 271 | self._eps = self._eps2 + self._eps1 272 | if self._eps >= self._epsilon: 273 | print(f"Privacy budget reached in epoch {epoch}") 274 | return self 275 | 276 | loss = 0 277 | self._elapsed_batches += 1 278 | 279 | # Zero gradients for all optimisers 280 | self.optim_trans.zero_grad() 281 | self.optim_mlp1.zero_grad() 282 | self.optim_mlp2.zero_grad() 283 | self.optim_VAE.zero_grad() 284 | 285 | """ 286 | `x_categ` is the the categorical data (batch_size x cat_cols+1) 287 | `x_cont` has continuous data (batch_size x cont_cols) 288 | `cat_mask` is an array of ones same shape as x_categ and an additional column(corresponding to CLS token) set to 0s (batch_size, cat_cols+1) 289 | `con_mask` is an array of ones same shape as x_cont (batch_size, cont_cols) 290 | """ 291 | x_categ, x_cont, cat_mask, con_mask = ( 292 | data[0].to(self.device), 293 | data[1].to(self.device), 294 | data[2].to(self.device), 295 | data[3].to(self.device), 296 | ) 297 | _, x_categ_enc_2, x_cont_enc_2 = embed_data_mask( 298 | x_categ, x_cont, cat_mask, con_mask, self.AE 299 | ) 300 | 301 | # Trim CLS token off categorical targets 302 | x_categ = x_categ[:, 1:] 303 | 304 | # Forward pass 305 | x_prime = self.AE.encode(x_categ_enc_2, x_cont_enc_2) 306 | 307 | if epoch < self.pretrain_epochs: 308 | x_prime_fake = x_prime 309 | else: 310 | mu, std, logvar = self.enc(x_prime) 311 | x_prime_fake, _ = self.dec(torch.randn_like(std) * std + mu) 312 | cat_outs, con_outs = self.AE.decode(x_prime_fake) 313 | 314 | l2 = 0 315 | if len(con_outs) > 0: 316 | if self.mdn: 317 | # MDN loss 318 | l2 = 0 319 | for _i, con in enumerate(con_outs): 320 | pi, mu, sigma = con 321 | l_mdn = mdn_loss(x_cont[:, _i], pi, mu, sigma) 322 | l2 += l_mdn 323 | else: 324 | con_outs = torch.cat(con_outs, dim=1) 325 | # Sqrt makes into RMSE loss 326 | l2 = torch.sqrt(criterion2(con_outs, x_cont)) 327 | l1 = 0 328 | n_cat = x_categ.shape[-1] 329 | for j in range(n_cat): 330 | x_probs = torch.full(cat_outs[j].shape, 0.01).to(self.device) 331 | for _i in range(cat_outs[j].shape[0]): 332 | x_probs[_i, x_categ[_i, j]] = 0.99 333 | l1 += criterion1(cat_outs[j], x_probs) 334 | 335 | # Reconstruction loss 336 | loss += self.lw_cat * l1 + self.lw_cont * l2 337 | 338 | if epoch >= self.pretrain_epochs: 339 | # Add KLD for regularisation loss 340 | KLD = -0.5 * torch.sum(1 + logvar - mu**2 - logvar.exp()) 341 | loss += self.lw_reg * KLD 342 | else: 343 | KLD = torch.Tensor([0]) 344 | 345 | # Early stop on collapsed loss 346 | # if loss.isnan(): 347 | # raise RuntimeError("Loss is NaN") 348 | # if loss.isinf(): 349 | # raise RuntimeError("Loss is inf") 350 | 351 | loss.backward() 352 | 353 | self.optim_mlp1.step() 354 | self.optim_mlp2.step() 355 | if epoch < self.pretrain_epochs: 356 | self.optim_trans.step() 357 | else: 358 | self.optim_VAE.step() 359 | 360 | if i % 10 == 0 and self.mlflow_logging: 361 | mlflow.log_metrics( 362 | { 363 | "elapsed_batches": self._elapsed_batches, 364 | "elapsed_epochs": self._elapsed_epochs, 365 | "loss.l1": l1.item(), 366 | "loss.l2": l2.item(), 367 | "loss.KLD": KLD.item(), 368 | "loss.Total": loss.item(), 369 | "used_epsilon.mlp1": self._eps1, 370 | "used_epsilon.mlp2": self._eps2, 371 | "used_epsilon.total": self._eps, 372 | # "best_alpha1": self._best_alpha1, 373 | # "best_alpha2": self._best_alpha2, 374 | }, 375 | step=self._elapsed_batches, 376 | ) 377 | # Weight and Grad norms 378 | mlflow.log_metrics(calc_norm_dict(self.AE), step=self._elapsed_batches) 379 | mlflow.log_metrics(calc_norm_dict(self.enc), step=self._elapsed_batches) 380 | mlflow.log_metrics(calc_norm_dict(self.dec), step=self._elapsed_batches) 381 | 382 | if verbose: 383 | print(f"Epoch: {epoch}, Total Loss: {loss}") 384 | 385 | if self.mlflow_logging: 386 | mlflow.log_metrics( 387 | { 388 | "elapsed_batches": self._elapsed_batches, 389 | "elapsed_epochs": self._elapsed_epochs, 390 | "loss.l1": l1.item(), 391 | "loss.l2": l2.item(), 392 | "loss.KLD": KLD.item(), 393 | "loss.Total": loss.item(), 394 | "used_epsilon.mlp1": self._eps1, 395 | "used_epsilon.mlp2": self._eps2, 396 | "used_epsilon.total": self._eps, 397 | # "best_alpha1": self._best_alpha1, 398 | # "best_alpha2": self._best_alpha2, 399 | }, 400 | step=self._elapsed_batches, 401 | ) 402 | 403 | if verbose: 404 | print("END OF AE TRAINING!") 405 | 406 | return self 407 | 408 | def sample(self, n=None): 409 | 410 | # Set evaluation mode 411 | self.AE.eval() 412 | self.dec.eval() 413 | self.enc.eval() 414 | 415 | n = self.batch_size if n is None else n 416 | Tensor = torch.cuda.FloatTensor if self.cuda else torch.FloatTensor 417 | cat_samples, con_samples = [[] for i in self.cat_idxs], [[] for i in self.con_idxs] 418 | 419 | with torch.no_grad(): 420 | # Sample noise z 421 | _m = torch.zeros(self.batch_size, self.latent_dim) 422 | _s = _m + 1 423 | z = torch.normal(mean=_m, std=_s).to(self.device) 424 | 425 | # Pass z to Decoder, then inverse trasformation (MLPs) 426 | x_hat, sigmas = self.dec(z) 427 | cat_tx, con_tx = self.AE.inv_transform(x_hat) 428 | 429 | # Set output 430 | for j, d in enumerate(cat_tx): 431 | cat_samples[j] = list(d.cpu().flatten().numpy()) 432 | for j, d in enumerate(con_tx): 433 | con_samples[j] = list(d.cpu().flatten().numpy()) 434 | 435 | # convert labels back to strings 436 | cat_samples = [ 437 | self.cat_label_encs[i].inverse_transform(c) for i, c in enumerate(cat_samples) 438 | ] 439 | 440 | # Rebuild columns in correct order 441 | cols = [] 442 | for i in range(self.dset_shape[1]): 443 | if i in self.cat_idxs: 444 | col = cat_samples[0] 445 | cat_samples = cat_samples[1:] 446 | else: 447 | col = con_samples[0] 448 | con_samples = con_samples[1:] 449 | cols.append(col) 450 | 451 | # Convert to dataframe 452 | df = pd.DataFrame(cols).T.sample(n, replace=True) 453 | df.columns = self.colnames 454 | # Try cast non-discrete columns to numeric types 455 | df[self.numeric_cols] = df[self.numeric_cols].apply(pd.to_numeric, errors="ignore") 456 | # Apply rounding 457 | df[self.numeric_cols] = df[self.numeric_cols].round(1) 458 | 459 | # Re-enable training mode 460 | self.AE.train() 461 | self.dec.train() 462 | self.enc.train() 463 | 464 | return df 465 | -------------------------------------------------------------------------------- /examples/example_training_run.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "id": "9nhTK0DKG45x" 7 | }, 8 | "source": [ 9 | "# Setup " 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": 1, 15 | "metadata": { 16 | "executionInfo": { 17 | "elapsed": 6, 18 | "status": "ok", 19 | "timestamp": 1655476302841, 20 | "user": { 21 | "displayName": "Gianluca Truda", 22 | "userId": "10545274143306236899" 23 | }, 24 | "user_tz": -60 25 | }, 26 | "id": "EztabF_kAjyD" 27 | }, 28 | "outputs": [ 29 | { 30 | "name": "stdout", 31 | "output_type": "stream", 32 | "text": [ 33 | "/bin/bash: warning: setlocale: LC_ALL: cannot change locale (en_GB.UTF-8)\n", 34 | "/home/ubuntu/thesis-dp-synth\n" 35 | ] 36 | } 37 | ], 38 | "source": [ 39 | "from pathlib import Path\n", 40 | "import os\n", 41 | "\n", 42 | "SRCDIR = \"dpgai\"\n", 43 | "DIR = Path(\"../thesis\")\n", 44 | "DATADIR = DIR / \"data\"\n", 45 | "RESULTDIR = DIR / \"results\"\n", 46 | "\n", 47 | "!pwd\n", 48 | "\n", 49 | "for p in [SRCDIR, DIR, DATADIR, RESULTDIR]:\n", 50 | " if not os.path.exists(p):\n", 51 | " print(f\"{p} does not exist\")" 52 | ] 53 | }, 54 | { 55 | "cell_type": "code", 56 | "execution_count": 2, 57 | "metadata": { 58 | "colab": { 59 | "base_uri": "https://localhost:8080/" 60 | }, 61 | "executionInfo": { 62 | "elapsed": 8, 63 | "status": "ok", 64 | "timestamp": 1655476329774, 65 | "user": { 66 | "displayName": "Gianluca Truda", 67 | "userId": "10545274143306236899" 68 | }, 69 | "user_tz": -60 70 | }, 71 | "id": "jcGRwOisznas", 72 | "outputId": "ef6a9c95-bc86-4db7-89e1-2707c723fa50" 73 | }, 74 | "outputs": [ 75 | { 76 | "name": "stdout", 77 | "output_type": "stream", 78 | "text": [ 79 | "/bin/bash: warning: setlocale: LC_ALL: cannot change locale (en_GB.UTF-8)\n", 80 | "Python 3.10.11\n" 81 | ] 82 | } 83 | ], 84 | "source": [ 85 | "!python3 --version" 86 | ] 87 | }, 88 | { 89 | "cell_type": "code", 90 | "execution_count": 3, 91 | "metadata": { 92 | "colab": { 93 | "base_uri": "https://localhost:8080/" 94 | }, 95 | "executionInfo": { 96 | "elapsed": 492, 97 | "status": "ok", 98 | "timestamp": 1655476330262, 99 | "user": { 100 | "displayName": "Gianluca Truda", 101 | "userId": "10545274143306236899" 102 | }, 103 | "user_tz": -60 104 | }, 105 | "id": "AcWYVYod5-om", 106 | "outputId": "9a37f8fe-b47e-4d4d-8441-a53194623447" 107 | }, 108 | "outputs": [ 109 | { 110 | "name": "stdout", 111 | "output_type": "stream", 112 | "text": [ 113 | "/bin/bash: warning: setlocale: LC_ALL: cannot change locale (en_GB.UTF-8)\n", 114 | "Tue May 30 22:29:55 2023 \n", 115 | "+-----------------------------------------------------------------------------+\n", 116 | "| NVIDIA-SMI 515.65.01 Driver Version: 515.65.01 CUDA Version: 11.7 |\n", 117 | "|-------------------------------+----------------------+----------------------+\n", 118 | "| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |\n", 119 | "| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |\n", 120 | "| | | MIG M. |\n", 121 | "|===============================+======================+======================|\n", 122 | "| 0 Tesla T4 On | 00000000:00:1E.0 Off | 0 |\n", 123 | "| N/A 42C P8 16W / 70W | 2MiB / 15360MiB | 0% Default |\n", 124 | "| | | N/A |\n", 125 | "+-------------------------------+----------------------+----------------------+\n", 126 | " \n", 127 | "+-----------------------------------------------------------------------------+\n", 128 | "| Processes: |\n", 129 | "| GPU GI CI PID Type Process name GPU Memory |\n", 130 | "| ID ID Usage |\n", 131 | "|=============================================================================|\n", 132 | "| No running processes found |\n", 133 | "+-----------------------------------------------------------------------------+\n" 134 | ] 135 | } 136 | ], 137 | "source": [ 138 | "!nvidia-smi" 139 | ] 140 | }, 141 | { 142 | "cell_type": "code", 143 | "execution_count": null, 144 | "metadata": { 145 | "colab": { 146 | "base_uri": "https://localhost:8080/" 147 | }, 148 | "executionInfo": { 149 | "elapsed": 68808, 150 | "status": "ok", 151 | "timestamp": 1655476399068, 152 | "user": { 153 | "displayName": "Gianluca Truda", 154 | "userId": "10545274143306236899" 155 | }, 156 | "user_tz": -60 157 | }, 158 | "id": "cSVKDhe8nYUZ", 159 | "outputId": "56ab4fd1-1f29-444b-ea02-e12949118ef4" 160 | }, 161 | "outputs": [], 162 | "source": [ 163 | "# %%capture\n", 164 | "from __future__ import print_function\n", 165 | "import argparse\n", 166 | "import os\n", 167 | "from datetime import datetime\n", 168 | "import random\n", 169 | "import torch\n", 170 | "import torch.nn as nn\n", 171 | "import torch.nn.parallel\n", 172 | "import torch.backends.cudnn as cudnn\n", 173 | "import torch.optim as optim\n", 174 | "import torch.utils.data\n", 175 | "import numpy as np\n", 176 | "import pandas as pd\n", 177 | "\n", 178 | "import matplotlib.pyplot as plt\n", 179 | "from IPython.display import HTML\n", 180 | "import seaborn as sns\n", 181 | "from tqdm import tqdm" 182 | ] 183 | }, 184 | { 185 | "cell_type": "code", 186 | "execution_count": 5, 187 | "metadata": { 188 | "colab": { 189 | "base_uri": "https://localhost:8080/" 190 | }, 191 | "executionInfo": { 192 | "elapsed": 68808, 193 | "status": "ok", 194 | "timestamp": 1655476399068, 195 | "user": { 196 | "displayName": "Gianluca Truda", 197 | "userId": "10545274143306236899" 198 | }, 199 | "user_tz": -60 200 | }, 201 | "id": "cSVKDhe8nYUZ", 202 | "outputId": "56ab4fd1-1f29-444b-ea02-e12949118ef4", 203 | "tags": [] 204 | }, 205 | "outputs": [ 206 | { 207 | "name": "stdout", 208 | "output_type": "stream", 209 | "text": [ 210 | "time: 7.71 ms (started: 2023-05-30 22:29:57 +00:00)\n" 211 | ] 212 | } 213 | ], 214 | "source": [ 215 | "%load_ext autotime\n", 216 | "\n", 217 | "# !pip install mlflow[extras]\n", 218 | "\n", 219 | "%matplotlib inline\n", 220 | "%config InlineBackend.figure_format = 'retina'\n", 221 | "\n", 222 | "# Set sensible defaults\n", 223 | "sns.set()\n", 224 | "sns.set_style(\"ticks\")\n", 225 | "sns.set_context('paper')" 226 | ] 227 | }, 228 | { 229 | "cell_type": "code", 230 | "execution_count": 6, 231 | "metadata": { 232 | "colab": { 233 | "base_uri": "https://localhost:8080/" 234 | }, 235 | "executionInfo": { 236 | "elapsed": 754, 237 | "status": "ok", 238 | "timestamp": 1655476399817, 239 | "user": { 240 | "displayName": "Gianluca Truda", 241 | "userId": "10545274143306236899" 242 | }, 243 | "user_tz": -60 244 | }, 245 | "id": "EUUSC4-yAhd1", 246 | "outputId": "981b2a59-2ee9-41b7-c8c8-18f19bf3957e" 247 | }, 248 | "outputs": [ 249 | { 250 | "name": "stdout", 251 | "output_type": "stream", 252 | "text": [ 253 | "time: 331 ms (started: 2023-05-30 22:29:57 +00:00)\n" 254 | ] 255 | } 256 | ], 257 | "source": [ 258 | "import mlflow\n", 259 | "import dotenv\n", 260 | "dotenv.load_dotenv()\n", 261 | "MLFLOW_URI = os.getenv(\"MLFLOW_URI\")\n", 262 | "mlflow.set_tracking_uri(MLFLOW_URI)" 263 | ] 264 | }, 265 | { 266 | "cell_type": "code", 267 | "execution_count": 7, 268 | "metadata": { 269 | "colab": { 270 | "base_uri": "https://localhost:8080/" 271 | }, 272 | "executionInfo": { 273 | "elapsed": 18, 274 | "status": "ok", 275 | "timestamp": 1655476399818, 276 | "user": { 277 | "displayName": "Gianluca Truda", 278 | "userId": "10545274143306236899" 279 | }, 280 | "user_tz": -60 281 | }, 282 | "id": "i-e1-i9m3FF7", 283 | "outputId": "9ed80332-7395-4da4-f9e6-ae359144c4a7" 284 | }, 285 | "outputs": [ 286 | { 287 | "name": "stdout", 288 | "output_type": "stream", 289 | "text": [ 290 | "cuda:0\n", 291 | "time: 169 ms (started: 2023-05-30 22:29:58 +00:00)\n" 292 | ] 293 | } 294 | ], 295 | "source": [ 296 | "# Decide which device we want to run on\n", 297 | "DEVICE = torch.device(\"cuda:0\" if (torch.cuda.is_available()) else \"cpu\")\n", 298 | "print(DEVICE)" 299 | ] 300 | }, 301 | { 302 | "cell_type": "code", 303 | "execution_count": 8, 304 | "metadata": { 305 | "colab": { 306 | "base_uri": "https://localhost:8080/" 307 | }, 308 | "executionInfo": { 309 | "elapsed": 320, 310 | "status": "ok", 311 | "timestamp": 1655476593616, 312 | "user": { 313 | "displayName": "Gianluca Truda", 314 | "userId": "10545274143306236899" 315 | }, 316 | "user_tz": -60 317 | }, 318 | "id": "JmQYHzNx2ew3", 319 | "outputId": "cdec7da8-6708-40d7-abb8-fb03af2d3b1f" 320 | }, 321 | "outputs": [ 322 | { 323 | "name": "stdout", 324 | "output_type": "stream", 325 | "text": [ 326 | "Random (meta) seed: 999\n", 327 | "time: 30.5 ms (started: 2023-05-30 22:29:58 +00:00)\n" 328 | ] 329 | } 330 | ], 331 | "source": [ 332 | "# Set random seed for reproducibility\n", 333 | "SEED = 999\n", 334 | "# SEED = random.randint(1, 10000) # use if you want new results\n", 335 | "print(\"Random (meta) seed: \", SEED)" 336 | ] 337 | }, 338 | { 339 | "cell_type": "markdown", 340 | "metadata": { 341 | "id": "DhzsQzlwN7iq" 342 | }, 343 | "source": [ 344 | "# Synthesis loop\n", 345 | "\n", 346 | "Data synthesis over multiple synthesisers and datasets, with persistence." 347 | ] 348 | }, 349 | { 350 | "cell_type": "code", 351 | "execution_count": 9, 352 | "metadata": { 353 | "colab": { 354 | "base_uri": "https://localhost:8080/" 355 | }, 356 | "executionInfo": { 357 | "elapsed": 10, 358 | "status": "ok", 359 | "timestamp": 1655476594078, 360 | "user": { 361 | "displayName": "Gianluca Truda", 362 | "userId": "10545274143306236899" 363 | }, 364 | "user_tz": -60 365 | }, 366 | "id": "qlGXL-zHgz0m", 367 | "outputId": "171dad15-d633-447e-c688-b4feec5ff760" 368 | }, 369 | "outputs": [ 370 | { 371 | "name": "stdout", 372 | "output_type": "stream", 373 | "text": [ 374 | "time: 23.8 ms (started: 2023-05-30 22:29:58 +00:00)\n" 375 | ] 376 | } 377 | ], 378 | "source": [ 379 | "%load_ext autoreload\n", 380 | "%autoreload 2" 381 | ] 382 | }, 383 | { 384 | "cell_type": "code", 385 | "execution_count": 10, 386 | "metadata": { 387 | "colab": { 388 | "base_uri": "https://localhost:8080/" 389 | }, 390 | "executionInfo": { 391 | "elapsed": 8, 392 | "status": "ok", 393 | "timestamp": 1655476594079, 394 | "user": { 395 | "displayName": "Gianluca Truda", 396 | "userId": "10545274143306236899" 397 | }, 398 | "user_tz": -60 399 | }, 400 | "id": "NR1e3lM-brkM", 401 | "outputId": "65bf44b6-4a89-4207-ff84-385ab003601e" 402 | }, 403 | "outputs": [ 404 | { 405 | "name": "stdout", 406 | "output_type": "stream", 407 | "text": [ 408 | "['/home/ubuntu/thesis-dp-synth', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '', '/home/ubuntu/.cache/pypoetry/virtualenvs/thesis-dp-synth-YuPmdaUF-py3.10/lib/python3.10/site-packages', 'dpgai']\n", 409 | "time: 19.2 ms (started: 2023-05-30 22:29:58 +00:00)\n" 410 | ] 411 | } 412 | ], 413 | "source": [ 414 | "import sys\n", 415 | "\n", 416 | "sys.path.append(str(SRCDIR))\n", 417 | "print(sys.path)" 418 | ] 419 | }, 420 | { 421 | "cell_type": "code", 422 | "execution_count": 11, 423 | "metadata": { 424 | "colab": { 425 | "base_uri": "https://localhost:8080/" 426 | }, 427 | "executionInfo": { 428 | "elapsed": 8, 429 | "status": "ok", 430 | "timestamp": 1655476631728, 431 | "user": { 432 | "displayName": "Gianluca Truda", 433 | "userId": "10545274143306236899" 434 | }, 435 | "user_tz": -60 436 | }, 437 | "id": "cM80dsn9OG4l", 438 | "outputId": "07fcec56-106d-4beb-c7ee-21151defa7b2" 439 | }, 440 | "outputs": [ 441 | { 442 | "name": "stdout", 443 | "output_type": "stream", 444 | "text": [ 445 | "time: 234 ms (started: 2023-05-30 22:29:58 +00:00)\n" 446 | ] 447 | } 448 | ], 449 | "source": [ 450 | "from dpgai.models import *\n", 451 | "\n", 452 | "EPOCHS = 5\n", 453 | "DIFFUSION_STEPS = 3\n", 454 | "\n", 455 | "synthesisers = {\n", 456 | " \"TableDiffusionDenoiser_Synthesiser\": (\n", 457 | " TabDM_Synthesiser,\n", 458 | " {\n", 459 | " \"batch_size\": 1024,\n", 460 | " \"lr\": 0.005,\n", 461 | " \"dims\": (128, 128),\n", 462 | " \"mlflow_logging\": True,\n", 463 | " \"epoch_target\": EPOCHS * DIFFUSION_STEPS,\n", 464 | " \"diffusion_steps\": DIFFUSION_STEPS,\n", 465 | " \"predict_noise\": False,\n", 466 | " },\n", 467 | " {\n", 468 | " \"n_epochs\": EPOCHS,\n", 469 | " \"verbose\": True,\n", 470 | " },\n", 471 | " {\n", 472 | " \"use_raw_data\": True,\n", 473 | " },\n", 474 | " ),\n", 475 | " \"TableDiffusion_Synthesiser\": (\n", 476 | " TabDM_Synthesiser,\n", 477 | " {\n", 478 | " \"batch_size\": 1024,\n", 479 | " \"lr\": 0.005,\n", 480 | " \"dims\": (128, 128),\n", 481 | " \"mlflow_logging\": True,\n", 482 | " \"epoch_target\": EPOCHS * DIFFUSION_STEPS,\n", 483 | " \"diffusion_steps\": DIFFUSION_STEPS,\n", 484 | " \"predict_noise\": True,\n", 485 | " },\n", 486 | " {\n", 487 | " \"n_epochs\": EPOCHS,\n", 488 | " \"verbose\": True,\n", 489 | " },\n", 490 | " {\n", 491 | " \"use_raw_data\": True,\n", 492 | " },\n", 493 | " ),\n", 494 | " \"DPautoGAN_Synthesiser\": (\n", 495 | " DPautoGAN_Synthesiser,\n", 496 | " {\n", 497 | " 'batch_size': 512,\n", 498 | " 'latent_dim': 64,\n", 499 | " \"gen_dims\": (128, 128),\n", 500 | " \"dis_dims\": (128, 128),\n", 501 | " 'gen_lr': 0.0001,\n", 502 | " 'dis_lr': 0.0007,\n", 503 | " \"ae_lr\": 0.02,\n", 504 | " \"ae_compress_dim\": 16,\n", 505 | " \"ae_eps_frac\": 0.4,\n", 506 | " 'epoch_target': EPOCHS,\n", 507 | " 'mlflow_logging': True,\n", 508 | " },\n", 509 | " {\n", 510 | " \"n_epochs\": EPOCHS,\n", 511 | " },\n", 512 | " {\n", 513 | " \"use_raw_data\": False,\n", 514 | " },\n", 515 | " ),\n", 516 | " \"DPWGAN_Synthesiser\": (\n", 517 | " WGAN_Synthesiser,\n", 518 | " {\n", 519 | " \"batch_size\": 512,\n", 520 | " 'gen_lr': 0.005,\n", 521 | " 'dis_lr': 0.001,\n", 522 | " \"latent_dim\": 64,\n", 523 | " 'n_critic': 2,\n", 524 | " \"epoch_target\": EPOCHS,\n", 525 | " \"mlflow_logging\": True,\n", 526 | " },\n", 527 | " {\n", 528 | " \"n_epochs\": EPOCHS,\n", 529 | " },\n", 530 | " {\n", 531 | " \"use_raw_data\": False,\n", 532 | " },\n", 533 | " ),\n", 534 | " \"PATEGAN_Synthesiser\": (\n", 535 | " PATEGAN_Synthesiser,\n", 536 | " {\n", 537 | " 'batch_size': 1024,\n", 538 | " \"gen_dims\": (128, 128),\n", 539 | " \"dis_dims\": (128, 128),\n", 540 | " 'gen_lr': 0.1,\n", 541 | " 'dis_lr': 0.1,\n", 542 | " 'latent_dim': 64,\n", 543 | " 'num_teachers': 30,\n", 544 | " 'teacher_iters': 8,\n", 545 | " 'student_iters': 5,\n", 546 | " 'epoch_target': EPOCHS,\n", 547 | " 'mlflow_logging': True,\n", 548 | " },\n", 549 | " {\n", 550 | " 'n_epochs': EPOCHS,\n", 551 | " 'noise_multiplier': 0.0048,\n", 552 | " },\n", 553 | " {\n", 554 | " \"use_raw_data\": False,\n", 555 | " },\n", 556 | " ),\n", 557 | "}" 558 | ] 559 | }, 560 | { 561 | "cell_type": "code", 562 | "execution_count": 12, 563 | "metadata": { 564 | "executionInfo": { 565 | "elapsed": 6, 566 | "status": "ok", 567 | "timestamp": 1655476631729, 568 | "user": { 569 | "displayName": "Gianluca Truda", 570 | "userId": "10545274143306236899" 571 | }, 572 | "user_tz": -60 573 | }, 574 | "id": "KFgwQr_as1lg" 575 | }, 576 | "outputs": [ 577 | { 578 | "data": { 579 | "text/plain": [ 580 | "{'TableDiffusionDenoiser_Synthesiser': (models.dp_tab_dm.TabDM_Synthesiser,\n", 581 | " {'batch_size': 1024,\n", 582 | " 'lr': 0.005,\n", 583 | " 'dims': (128, 128),\n", 584 | " 'mlflow_logging': True,\n", 585 | " 'epoch_target': 15,\n", 586 | " 'diffusion_steps': 3,\n", 587 | " 'predict_noise': False},\n", 588 | " {'n_epochs': 5, 'verbose': True},\n", 589 | " {'use_raw_data': True}),\n", 590 | " 'TableDiffusion_Synthesiser': (models.dp_tab_dm.TabDM_Synthesiser,\n", 591 | " {'batch_size': 1024,\n", 592 | " 'lr': 0.005,\n", 593 | " 'dims': (128, 128),\n", 594 | " 'mlflow_logging': True,\n", 595 | " 'epoch_target': 15,\n", 596 | " 'diffusion_steps': 3,\n", 597 | " 'predict_noise': True},\n", 598 | " {'n_epochs': 5, 'verbose': True},\n", 599 | " {'use_raw_data': True}),\n", 600 | " 'DPautoGAN_Synthesiser': (models.dp_auto_gan.DPautoGAN_Synthesiser,\n", 601 | " {'batch_size': 512,\n", 602 | " 'latent_dim': 64,\n", 603 | " 'gen_dims': (128, 128),\n", 604 | " 'dis_dims': (128, 128),\n", 605 | " 'gen_lr': 0.0001,\n", 606 | " 'dis_lr': 0.0007,\n", 607 | " 'ae_lr': 0.02,\n", 608 | " 'ae_compress_dim': 16,\n", 609 | " 'ae_eps_frac': 0.4,\n", 610 | " 'epoch_target': 5,\n", 611 | " 'mlflow_logging': True},\n", 612 | " {'n_epochs': 5},\n", 613 | " {'use_raw_data': False}),\n", 614 | " 'DPWGAN_Synthesiser': (models.dp_wgan.WGAN_Synthesiser,\n", 615 | " {'batch_size': 512,\n", 616 | " 'gen_lr': 0.005,\n", 617 | " 'dis_lr': 0.001,\n", 618 | " 'latent_dim': 64,\n", 619 | " 'n_critic': 2,\n", 620 | " 'epoch_target': 5,\n", 621 | " 'mlflow_logging': True},\n", 622 | " {'n_epochs': 5},\n", 623 | " {'use_raw_data': False}),\n", 624 | " 'PATEGAN_Synthesiser': (models.pate_gan.PATEGAN_Synthesiser,\n", 625 | " {'batch_size': 1024,\n", 626 | " 'gen_dims': (128, 128),\n", 627 | " 'dis_dims': (128, 128),\n", 628 | " 'gen_lr': 0.1,\n", 629 | " 'dis_lr': 0.1,\n", 630 | " 'latent_dim': 64,\n", 631 | " 'num_teachers': 30,\n", 632 | " 'teacher_iters': 8,\n", 633 | " 'student_iters': 5,\n", 634 | " 'epoch_target': 5,\n", 635 | " 'mlflow_logging': True},\n", 636 | " {'n_epochs': 5, 'noise_multiplier': 0.0048},\n", 637 | " {'use_raw_data': False})}" 638 | ] 639 | }, 640 | "execution_count": 12, 641 | "metadata": {}, 642 | "output_type": "execute_result" 643 | }, 644 | { 645 | "name": "stdout", 646 | "output_type": "stream", 647 | "text": [ 648 | "time: 25.6 ms (started: 2023-05-30 22:29:58 +00:00)\n" 649 | ] 650 | } 651 | ], 652 | "source": [ 653 | "synthesisers" 654 | ] 655 | }, 656 | { 657 | "cell_type": "code", 658 | "execution_count": null, 659 | "metadata": { 660 | "colab": { 661 | "background_save": true, 662 | "base_uri": "https://localhost:8080/" 663 | }, 664 | "id": "5Kg9cS7PN-b9" 665 | }, 666 | "outputs": [], 667 | "source": [ 668 | "from dpgai.config import datasets\n", 669 | "from dpgai.utilities import run_synthesisers\n", 670 | "\n", 671 | "exp_hash = datetime.now().strftime(\"%y%m%d_%H%M%S\")\n", 672 | "EXP_NAME = f\"exp_{exp_hash}\"\n", 673 | "\n", 674 | "# Make directories for experiment EXP_NAME\n", 675 | "EXP_PATH = RESULTDIR / EXP_NAME\n", 676 | "FAKE_DSET_PATH = EXP_PATH / \"fake_datasets\"\n", 677 | "if not os.path.exists(FAKE_DSET_PATH):\n", 678 | " os.makedirs(FAKE_DSET_PATH)\n", 679 | "\n", 680 | "exp_id = mlflow.create_experiment(f\"{EXP_NAME}\")\n", 681 | "\n", 682 | "print(f\"\\n\\nRunning experiment: {EXP_NAME}\\n\\n\")\n", 683 | "\n", 684 | "run_synthesisers(\n", 685 | " datasets=datasets,\n", 686 | " synthesisers=synthesisers,\n", 687 | " exp_name=EXP_NAME,\n", 688 | " exp_id=exp_id,\n", 689 | " datadir=DATADIR,\n", 690 | " repodir=\"./\",\n", 691 | " epsilon_values=[0.5, 1.0, 5.0, 10.0, 50.0, 100.0, 500.0, 1000.0],\n", 692 | " repeats=10,\n", 693 | " metaseed=SEED,\n", 694 | " generate_fakes=True,\n", 695 | " fake_sample_path=EXP_PATH / \"samples\",\n", 696 | " fake_data_path=FAKE_DSET_PATH,\n", 697 | " with_benchmark=True,\n", 698 | " ctgan_epochs=30,\n", 699 | " cuda=True,\n", 700 | ")\n", 701 | "\n", 702 | "mlflow.end_run()" 703 | ] 704 | } 705 | ], 706 | "metadata": { 707 | "accelerator": "GPU", 708 | "colab": { 709 | "background_execution": "on", 710 | "collapsed_sections": [], 711 | "machine_shape": "hm", 712 | "name": "synthesiser_comparison_v34.ipynb", 713 | "version": "" 714 | }, 715 | "gpuClass": "standard", 716 | "kernelspec": { 717 | "display_name": "Python 3 (ipykernel)", 718 | "language": "python", 719 | "name": "python3" 720 | }, 721 | "language_info": { 722 | "codemirror_mode": { 723 | "name": "ipython", 724 | "version": 3 725 | }, 726 | "file_extension": ".py", 727 | "mimetype": "text/x-python", 728 | "name": "python", 729 | "nbconvert_exporter": "python", 730 | "pygments_lexer": "ipython3", 731 | "version": "3.10.8" 732 | } 733 | }, 734 | "nbformat": 4, 735 | "nbformat_minor": 4 736 | } 737 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------