├── MANIFEST.in ├── opacus_lab └── models │ └── GPT2 │ ├── model │ ├── __init__.py │ ├── masking.py │ ├── feedforward.py │ ├── embedding.py │ ├── attention.py │ └── transformer.py │ ├── dataset.py │ ├── train.py │ └── refactor.py ├── tests └── test_refactor.py ├── README.md ├── examples └── GPT2 │ ├── prepare-wikitext-103.sh │ ├── preprocess-wikitext-103.py │ ├── README.md │ └── run.py ├── CONTRIBUTING.md ├── .gitignore ├── CODE_OF_CONDUCT.md └── LICENSE /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include requirements.txt 2 | -------------------------------------------------------------------------------- /opacus_lab/models/GPT2/model/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Meta Platforms, Inc. and its affiliates. All Rights Reserved 3 | 4 | # from GPT2.model.attention import (Past, BaseAttention, MultiHeadAttention, 5 | # AttentionLayer) 6 | # from GPT2.model.embedding import PositionalEmbedding, TokenEmbedding 7 | # from GPT2.model.feedforward import Activation, PositionwiseFeedForward 8 | # from GPT2.model.masking import PadMasking, FutureMasking 9 | # from GPT2.model.transformer import TransformerLayer, Transformer 10 | -------------------------------------------------------------------------------- /tests/test_refactor.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Meta Platforms, Inc. and its affiliates. All Rights Reserved 3 | import unittest 4 | 5 | from opacus_lab.models.GPT2.refactor import refactor_transformer, test_refactor 6 | from transformers import GPT2Config, GPT2LMHeadModel 7 | 8 | 9 | class LoadModelTest(unittest.TestCase): 10 | def test_load_model(self): 11 | size = "S" 12 | configuration = GPT2Config() 13 | pretrained_model = GPT2LMHeadModel(configuration) 14 | model = refactor_transformer( 15 | pretrained_model, 16 | size=size, 17 | ) 18 | self.assertTrue( 19 | test_refactor(pretrained_model, model, exact=False), "Refactor failed..." 20 | ) 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Opacus Lab 2 | 3 | Research and experimental code related to [Opacus](https://opacus.ai), a library that enables training PyTorch models with differential privacy. 4 | 5 | Opacus Lab is meant to be an experimental counterpart of the main [Opacus](https://opacus.ai) repository; it is used to include and experiment with features that are too niche or not mature to be included in the main repository. 6 | 7 | > :warning: **WARNING**: This code is considered experimental and we provide it as-is to the community as we develop it in the open source. We do not offer support for this code, nor do we maintain a pip package for it with releases. You are welcome to install from source and tinker with it as well as talk to us about it, preferably in our forum (https://discuss.pytorch.org/c/opacus/29). 8 | 9 | 10 | ## License 11 | This code is released under Apache 2.0, as found in the [LICENSE](https://github.com/facebookresearch/opacus-lab/tree/main/LICENSE) file. 12 | -------------------------------------------------------------------------------- /examples/GPT2/prepare-wikitext-103.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Copyright (c) Meta Platforms, Inc. and its affiliates. All Rights Reserved 3 | # This script is borrowed from pytorch/fairseq (version 0.6.2) 4 | # Adapted from https://github.com/facebookresearch/MIXER/blob/master/prepareData.sh 5 | 6 | URLS=( 7 | "https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-103-v1.zip" 8 | ) 9 | FILES=( 10 | "wikitext-103-v1.zip" 11 | ) 12 | 13 | for ((i=0;i<"${#URLS[@]}";++i)); do 14 | file="${FILES[i]}" 15 | if [ -f "$file"]; then 16 | echo "$file already exists, skipping download" 17 | else 18 | url="${URLS[i]}" 19 | wget "$url" 20 | if [ -f $file ]; then 21 | echo "$url successfully downloaded." 22 | else 23 | echo "$url not successfully downloaded." 24 | exit -1 25 | fi 26 | if [ "${file: -4}" == ".tgz" ]; then 27 | tar zxvf $file 28 | elif [ "${file: -4}" == ".tar" ]; then 29 | tar xvf "$file" 30 | elif [ "${file: -4}" == ".zip" ]; then 31 | unzip "$file" 32 | fi 33 | fi 34 | done 35 | cd .. 36 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Opacus Lab 2 | 3 | Opacus Lab is meant to be a repository for research and experimental code related to Opacus. We use Opacus Lab to include features that are too niche or not mature enough to integrate to the main Opacus repository. 4 | 5 | > :warning: **DISCLAIMER**: We are a small team, so at this time we can only commit to supporting the stable code we land in Opacus main repository. This means we normally would not maintain Opacus Lab and generally would not monitor contributions and accept pull requests. We offer this code as-is to develop in the open together with our community. You are free to use it in your own research (if you do, just cite Opacus. No need to cite this repo). 6 | Even though we do not accept pull requests to this repo, if you used or modified this code to do something cool let us know in the [forums](https://discuss.pytorch.org/c/opacus/29). 7 | 8 | 9 | ## Want to contribute to Opacus? 10 | 11 | Please visit the [main Opacus repository](https://github.com/pytorch/opacus/blob/main/CONTRIBUTING.md). 12 | 13 | 14 | ## License 15 | 16 | By contributing to Opacus Lab, you agree that your contributions will be licensed 17 | under the LICENSE file in the root directory of this source tree. 18 | -------------------------------------------------------------------------------- /opacus_lab/models/GPT2/dataset.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Meta Platforms, Inc. and its affiliates. All Rights Reserved 3 | 4 | import torch 5 | from torch.utils.data import Dataset 6 | 7 | 8 | def load_wikitext(path): 9 | corpus = dict() 10 | for dset in ["valid", "train", "test"]: 11 | corpus[dset] = torch.load(f"{path}/wikitext-103-{dset}-corpus.pt") 12 | return corpus 13 | 14 | 15 | class CorpusDataset(Dataset): 16 | def __init__(self, corpus, seqlen): 17 | super().__init__() 18 | self.corpus = corpus 19 | self.seqlen = seqlen 20 | 21 | def __len__(self): 22 | return int(len(self.corpus) / self.seqlen) 23 | 24 | def __getitem__(self, item): 25 | idx = item * self.seqlen 26 | return self.corpus[idx : idx + self.seqlen] 27 | 28 | 29 | class UserLvlDataset(Dataset): 30 | def __init__(self, users): 31 | super().__init__() 32 | # a list of users 33 | self.users = users # each user is a CorpusDataset 34 | 35 | def __len__(self): 36 | return len(self.users) 37 | 38 | def __getitem__(self, item): 39 | idx = torch.randint(len(self.users[item]), (1,)).item() 40 | return self.users[item][idx] 41 | -------------------------------------------------------------------------------- /examples/GPT2/preprocess-wikitext-103.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Meta Platforms, Inc. and its affiliates. All Rights Reserved 3 | 4 | import csv 5 | 6 | import torch 7 | import tqdm 8 | from transformers import GPT2Tokenizer 9 | 10 | tokenizer = GPT2Tokenizer.from_pretrained("gpt2") 11 | 12 | """ 13 | Script assumes in same directory as wikitext download (i.e. same directory 14 | that ran prepare-wikitext-103.sh) 15 | Change paths below as needed 16 | """ 17 | file_train = "wikitext-103/wiki.train.tokens" 18 | file_test = "wikitext-103/wiki.test.tokens" 19 | file_valid = "wikitext-103/wiki.valid.tokens" 20 | 21 | for file, name in [(file_train, "train"), (file_test, "test"), (file_valid, "valid")]: 22 | corpus = [] 23 | print(f"Processing wikitext {name} set...") 24 | with open(file, "r", encoding="utf-8") as f: 25 | csv_reader = csv.reader(f, delimiter="\n") 26 | for i, row in tqdm.tqdm(enumerate(csv_reader)): 27 | if row != [" "]: 28 | next_row = torch.tensor(tokenizer.encode(row[0])) 29 | corpus.append(next_row) 30 | 31 | corpus = torch.cat(corpus).long() 32 | print(f"Saving wikitext {name} corpus as Pytoch tensor...") 33 | torch.save(corpus, f"wikitext-103-{name}-corpus.pt") 34 | print("Done!") 35 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # Downloaded data 7 | data/ 8 | 9 | # Buck Targets 10 | TARGETS 11 | 12 | # Distribution / packaging 13 | .Python 14 | env/ 15 | build/ 16 | develop-eggs/ 17 | dist/ 18 | downloads/ 19 | eggs/ 20 | .eggs/ 21 | lib/ 22 | lib64/ 23 | parts/ 24 | sdist/ 25 | var/ 26 | wheels/ 27 | 28 | *.egg-info/ 29 | .installed.cfg 30 | *.egg 31 | 32 | # watchman 33 | # Watchman helper 34 | .watchmanconfig 35 | 36 | # OSX 37 | *.DS_Store 38 | 39 | # Atom plugin files and ctags 40 | .ftpconfig 41 | .ftpconfig.cson 42 | .ftpignore 43 | *.tags 44 | *.tags1 45 | 46 | # PyInstaller 47 | # Usually these files are written by a python script from a template 48 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 49 | *.manifest 50 | *.spec 51 | 52 | # Installer logs 53 | pip-log.txt 54 | pip-delete-this-directory.txt 55 | 56 | # Unit test / coverage reports 57 | htmlcov/ 58 | .tox/ 59 | .coverage 60 | .coverage.* 61 | .cache 62 | nosetests.xml 63 | coverage.xml 64 | *.cover 65 | .hypothesis/ 66 | .pytest_cache/ 67 | 68 | # PyBuilder 69 | target/ 70 | 71 | # Jupyter Notebook 72 | .ipynb_checkpoints 73 | 74 | # pyenv 75 | .python-version 76 | 77 | # dotenv 78 | .env 79 | 80 | # virtualenv 81 | .venv 82 | venv/ 83 | ENV/ 84 | 85 | # mypy 86 | .mypy_cache/ 87 | 88 | # vim 89 | *.swp 90 | -------------------------------------------------------------------------------- /opacus_lab/models/GPT2/model/masking.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Meta Platforms, Inc. and its affiliates. All Rights Reserved 3 | 4 | import torch 5 | import torch.nn as nn 6 | 7 | 8 | class PadMasking(nn.Module): 9 | """ 10 | Tensor Type Shape 11 | =========================================================================== 12 | input long (..., seq_len) 13 | --------------------------------------------------------------------------- 14 | output float (..., seq_len, seq_len + offset) 15 | =========================================================================== 16 | """ 17 | 18 | def __init__(self, pad_idx: int): 19 | super().__init__() 20 | self.pad_idx = pad_idx 21 | 22 | def forward(self, x: torch.Tensor, offset: int = 0) -> torch.Tensor: 23 | is_pad = (x == self.pad_idx).unsqueeze(-2) 24 | shifted = torch.zeros( 25 | x.size()[:-1] 26 | + ( 27 | 1, 28 | offset, 29 | ), 30 | dtype=torch.bool, 31 | device=x.device, 32 | ) 33 | 34 | mask = torch.cat((shifted, is_pad), dim=-1) 35 | return mask.expand(x.shape + mask.shape[-1:]) 36 | 37 | 38 | class FutureMasking(nn.Module): 39 | """ 40 | Tensor Type Shape 41 | =========================================================================== 42 | input long (..., seq_len) 43 | --------------------------------------------------------------------------- 44 | output float (..., seq_len, seq_len + offset) 45 | =========================================================================== 46 | """ 47 | 48 | def forward(self, x: torch.Tensor, offset: int = 0) -> torch.Tensor: 49 | seq_len = x.size(-1) 50 | 51 | # Create shifted upper triangular matrix. 52 | future = torch.ones( 53 | (seq_len, seq_len + offset), dtype=torch.bool, device=x.device 54 | ) 55 | future = future.triu(offset + 1) 56 | 57 | mask = future.view((1,) * (x.ndim - 1) + future.size()) 58 | return mask.expand(x.shape + mask.shape[-1:]) 59 | -------------------------------------------------------------------------------- /examples/GPT2/README.md: -------------------------------------------------------------------------------- 1 | # Opacus Compatible GPT-2 2 | 3 | To the best of our knowledge, this is the first Pytorch implementation of GPT-2 4 | that is compatible with Opacus. This implementation is *experimental* and does 5 | not yet achieve a reasonable trade-off between perplexity and differential 6 | privacy. 7 | 8 | ## Overview 9 | 10 | This directory contains a routine to refactor the Huggingface/torch-transformer 11 | implementation of GPT-2 into a module that is compatible with Opacus. This 12 | module also comes with built-in control & a utility that makes it easy to 13 | train the top k layers of GPT-2 (for a user selected k). Finally, we also 14 | include a low-rank factorization of the GPT-2 output layer (with the intent of 15 | reducing the # of parameters that DP-SGD fine-tunes). 16 | 17 | ## Instructions 18 | Begin by moving into the `opacus-lab/GPT2/` directory. 19 | 20 | ### Requirements 21 | Other than Pytorch and Opacus the only requirement is `transformers==4.7`. 22 | 23 | ### Python Path 24 | Set `export PYTHONPATH=~/Opacus-lab/` or whatever path the Opacus-lab base 25 | directory is in. 26 | 27 | ### Download Data 28 | Run `bash prepare-wikitext-103.sh` 29 | 30 | You can skip this if you already have the dataset downloaded. 31 | 32 | ### Preprocess Data 33 | Run `python preprocess-wikitext-103.py` 34 | 35 | This converts the raw text files into Pytorch tensors using on the GPT tokenizer. 36 | 37 | ### Train Model 38 | Run `python run.py` 39 | 40 | You can use the `-h` flag to learn more about the various arguments that are 41 | currently supported. 42 | 43 | ## Block Level vs. User Level Privacy 44 | For now, we only support block-level privacy. Generally speaking, for the 45 | goal of fine-tuning on some user's private text, we'd like to consider 46 | privacy at the user level rather than the block level. This is a stronger 47 | notion of privacy, so achieving a reasonable trade-off between perplexity 48 | and block-level privacy should be easier. In the near future, we aim to include 49 | support for the `UsrLvlDataset` class in `GPT2/dataset.py`. 50 | 51 | 52 | ## Code Acknowledgements 53 | We acknowledge the following code (all under the same Apache 2.0 License): 54 | - affjljoo3581/GPT2 for the base GPT-2 Pytorch implementation that we modify 55 | - pytorch/fairseq for the utilty script for downloading wikitext-103 56 | - huggingface/transformers for the GPT-2 Pytorch implementation & pre-trained weights 57 | that we refactor into 58 | -------------------------------------------------------------------------------- /opacus_lab/models/GPT2/model/feedforward.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Meta Platforms, Inc. and its affiliates. All Rights Reserved 3 | 4 | import math 5 | 6 | import torch 7 | import torch.nn as nn 8 | 9 | 10 | class Activation(nn.Module): 11 | """ 12 | Tensor Type Shape 13 | =========================================================================== 14 | input float (..., dims) 15 | --------------------------------------------------------------------------- 16 | output float (..., dims) 17 | =========================================================================== 18 | """ 19 | 20 | def __init__(self, activation="gelu"): 21 | super().__init__() 22 | if activation == "gelu": 23 | self.activation = self.gelu_new 24 | elif activation == "sigmoid": 25 | self.sigmoid = nn.Sigmoid() 26 | self.activation = lambda x: x * self.sigmoid(x) 27 | 28 | def gelu_new(self, x): 29 | """ 30 | Implementation of the GELU activation function currently in Google BERT 31 | repo (identical to OpenAI GPT). Also see the Gaussian Error Linear 32 | Units paper: https://arxiv.org/abs/1606.08415 33 | Note: This routine is taken from Huggingface/transformers V4.7.0 34 | """ 35 | return ( 36 | 0.5 37 | * x 38 | * ( 39 | 1.0 40 | + torch.tanh( 41 | math.sqrt(2.0 / math.pi) * (x + 0.044715 * torch.pow(x, 3.0)) 42 | ) 43 | ) 44 | ) 45 | 46 | def forward(self, x: torch.Tensor) -> torch.Tensor: 47 | return self.activation(x) 48 | 49 | 50 | class PositionwiseFeedForward(nn.Module): 51 | """ 52 | Tensor Type Shape 53 | =========================================================================== 54 | input float (..., dims) 55 | --------------------------------------------------------------------------- 56 | output float (..., dims) 57 | =========================================================================== 58 | """ 59 | 60 | def __init__(self, dims: int, rate: int = 4, dropout: float = 0.1): 61 | super().__init__() 62 | self.fc = nn.Linear(dims, dims * rate) 63 | self.act = Activation() 64 | self.proj = nn.Linear(dims * rate, dims) 65 | self.drop = nn.Dropout(dropout) 66 | 67 | def forward(self, x): 68 | x = self.fc(x) 69 | x = self.act(x) 70 | x = self.proj(x) 71 | x = self.drop(x) 72 | return x 73 | -------------------------------------------------------------------------------- /opacus_lab/models/GPT2/model/embedding.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Meta Platforms, Inc. and its affiliates. All Rights Reserved 3 | 4 | from typing import Dict 5 | 6 | import torch 7 | import torch.nn as nn 8 | 9 | 10 | class PositionalEmbedding(nn.Module): 11 | """ 12 | Tensor Type Shape 13 | =========================================================================== 14 | input long (..., seq_len) 15 | --------------------------------------------------------------------------- 16 | output float (..., seq_len, embedding_dim) 17 | =========================================================================== 18 | """ 19 | 20 | def __init__(self, seq_len: int, dims: int): 21 | super().__init__() 22 | self.emb = nn.Embedding(seq_len, dims) 23 | 24 | def reset_parameters(self): 25 | nn.init.normal_(self.emb.weight, std=0.02) 26 | 27 | def _load_from_state_dict( 28 | self, state_dict: Dict[str, torch.Tensor], prefix: str, *args, **kwargs 29 | ): 30 | weight = state_dict[f"{prefix}weight"] 31 | 32 | # Reduce or expand the positional embedding matrix to increase or 33 | # decrease the total sequence length. 34 | if weight.size(0) < self.emb.num_embeddings: 35 | weight = torch.cat((weight, self.weight[weight.size(0) :]), dim=0) 36 | elif weight.size(0) > self.emb.num_embeddings: 37 | weight = weight[: self.emb.num_embeddings] 38 | 39 | state_dict[f"{prefix}weight"] = weight 40 | super()._load_from_state_dict(state_dict, prefix, *args, **kwargs) 41 | 42 | def forward(self, x: torch.Tensor, offset: int = 0) -> torch.Tensor: 43 | position = torch.arange( 44 | offset, offset + x.size(-1), dtype=torch.long, device=x.device 45 | ) 46 | position = position.view((1,) * (x.ndim - 1) + (-1,)).expand_as(x) 47 | 48 | return self.emb(position) 49 | 50 | 51 | class TokenEmbedding(nn.Module): 52 | """ 53 | Tensor Type Shape 54 | =========================================================================== 55 | input long or float (..., seq_len) 56 | or (..., seq_len, embedding_dim) 57 | --------------------------------------------------------------------------- 58 | output float (..., seq_len, embedding_dim) 59 | or (..., seq_len, num_embeddings) 60 | =========================================================================== 61 | """ 62 | 63 | def __init__(self, words: int, dims: int): 64 | super().__init__() 65 | self.emb = nn.Embedding(words, dims) 66 | 67 | def reset_parameters(self): 68 | nn.init.normal_(self.emb.weight, std=0.02) 69 | 70 | def forward(self, x: torch.Tensor, transposed: bool = False) -> torch.Tensor: 71 | if transposed: 72 | return torch.matmul(x, self.emb.weight.transpose(0, 1)) 73 | else: 74 | return self.emb(x) 75 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to make participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies within all project spaces, and it also applies when 49 | an individual is representing the project or its community in public spaces. 50 | Examples of representing a project or community include using an official 51 | project e-mail address, posting via an official social media account, or acting 52 | as an appointed representative at an online or offline event. Representation of 53 | a project may be further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at . All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /opacus_lab/models/GPT2/model/attention.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Meta Platforms, Inc. and its affiliates. All Rights Reserved 3 | 4 | import math 5 | from typing import Optional, Tuple 6 | 7 | import torch 8 | import torch.nn as nn 9 | 10 | Past = Tuple[torch.Tensor, torch.Tensor] 11 | 12 | 13 | class BaseAttention(nn.Module): 14 | """ 15 | Tensor Type Shape 16 | ========================================================================== 17 | q float (..., query_len, dims) 18 | k float (..., kv_len, dims) 19 | v float (..., kv_len, dims) 20 | mask bool (..., query_len, kv_len) 21 | --------------------------------------------------------------------------- 22 | output float (..., query_len, dims) 23 | =========================================================================== 24 | """ 25 | 26 | def __init__(self, dropout: float = 0.1, max_position_embeddings: int = 1024): 27 | super().__init__() 28 | self.dropout = nn.Dropout(dropout) 29 | # register buffer for masked_bias and max_position_embeddings 30 | # copied from Huggingface's implementation (see causal_masking routine) 31 | self.mpe = max_position_embeddings 32 | self.register_buffer( 33 | "bias", 34 | torch.tril(torch.ones((self.mpe, self.mpe), dtype=torch.uint8)).view( 35 | 1, 1, self.mpe, self.mpe 36 | ), 37 | ) 38 | self.register_buffer("masked_bias", torch.tensor(-1e4)) 39 | 40 | def causal_masking(self, x, q, k): 41 | """ 42 | This routine is based off (and nearly identical to) the code in lines 43 | #188-#193 of Huggingface's transformers/models/gpt2/modeling_gpt2.py. 44 | (Version 4.7.0) 45 | """ 46 | q_len, k_len = q.size(-2), k.size(-2) 47 | causal_mask = self.bias[:, :, k_len - q_len : k_len, :k_len].bool() 48 | return torch.where(causal_mask, x, self.masked_bias.to(x.dtype)) 49 | 50 | def forward( 51 | self, 52 | q: torch.Tensor, 53 | k: torch.Tensor, 54 | v: torch.Tensor, 55 | mask: Optional[torch.Tensor] = None, 56 | ) -> torch.Tensor: 57 | x = torch.matmul(q, k.transpose(-1, -2)) 58 | x /= math.sqrt(k.size(-1)) 59 | x = self.causal_masking(x, q, k) 60 | x = nn.Softmax(dim=-1)(x) 61 | x = self.dropout(x) 62 | x = torch.matmul(x, v) 63 | return x 64 | 65 | 66 | class MultiHeadAttention(BaseAttention): 67 | """ 68 | Tensor Type Shape 69 | =========================================================================== 70 | q float (..., query_len, dims) 71 | k float (..., kv_len, dims) 72 | v float (..., kv_len, dims) 73 | mask bool (..., query_len, kv_len) 74 | --------------------------------------------------------------------------- 75 | output float (..., query_len, dims) 76 | =========================================================================== 77 | """ 78 | 79 | def __init__(self, heads: int, dropout: float = 0.1): 80 | super().__init__(dropout) 81 | self.heads = heads 82 | 83 | def forward( 84 | self, 85 | q: torch.Tensor, 86 | k: torch.Tensor, 87 | v: torch.Tensor, 88 | mask: Optional[torch.Tensor] = None, 89 | ) -> torch.Tensor: 90 | # Split the tensors to multi-heads. 91 | q = q.view(q.size()[:-1] + (self.heads, q.size(-1) // self.heads)) 92 | k = k.view(k.size()[:-1] + (self.heads, k.size(-1) // self.heads)) 93 | v = v.view(v.size()[:-1] + (self.heads, v.size(-1) // self.heads)) 94 | 95 | q = q.transpose(-3, -2) 96 | k = k.transpose(-3, -2) 97 | v = v.transpose(-3, -2) 98 | 99 | if mask is not None: 100 | mask = mask.unsqueeze(-3) 101 | 102 | # Calculate multi-headed attentions and merge them into one. 103 | return ( 104 | super() 105 | .forward(q, k, v, mask) 106 | .transpose(-3, -2) 107 | .contiguous() 108 | .view(q.size()[:-3] + (q.size(-2), v.size(-1) * self.heads)) 109 | ) 110 | 111 | 112 | class AttentionLayer(nn.Module): 113 | """ 114 | Tensor Type Shape 115 | =========================================================================== 116 | q float (..., query_len, dims) 117 | k float (..., kv_len, dims) 118 | v float (..., kv_len, dims) 119 | past (*) float (..., past_len, dims) 120 | mask bool (..., query_len, past_len + kv_len) 121 | --------------------------------------------------------------------------- 122 | output 1 float (..., query_len, dims) 123 | output 2 (*) float (..., past_len + kv_len, dims) 124 | =========================================================================== 125 | """ 126 | 127 | def __init__(self, heads: int, dims: int, dropout: float = 0.1): 128 | super().__init__() 129 | self.attn = MultiHeadAttention(heads, dropout) 130 | self.proj_q = nn.Linear(dims, dims) 131 | self.proj_k = nn.Linear(dims, dims) 132 | self.proj_v = nn.Linear(dims, dims) 133 | self.linear = nn.Linear(dims, dims) 134 | 135 | def forward( 136 | self, 137 | q: torch.Tensor, 138 | k: torch.Tensor, 139 | v: torch.Tensor, 140 | past: Optional[Past] = None, 141 | mask: Optional[torch.Tensor] = None, 142 | ) -> Tuple[torch.Tensor, Past]: 143 | q, k, v = self.proj_q(q), self.proj_k(k), self.proj_v(v) 144 | # Reuse attention keys and values by concatenating to the current ones. 145 | if past is not None: 146 | k = torch.cat((past[0], k), dim=-2) 147 | v = torch.cat((past[1], v), dim=-2) 148 | 149 | x = self.attn(q, k, v, mask) 150 | x = self.linear(x) 151 | return x, (k, v) 152 | -------------------------------------------------------------------------------- /opacus_lab/models/GPT2/train.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Meta Platforms, Inc. and its affiliates. All Rights Reserved 3 | 4 | 5 | import numpy as np 6 | import torch 7 | import torch.nn as nn 8 | import torch.optim as optim 9 | import tqdm 10 | from opacus import PrivacyEngine 11 | from transformers import AdamW, get_linear_schedule_with_warmup 12 | 13 | 14 | def finetunable_GPT2_params(model, finetune): 15 | # works on refactored GPT2 16 | def extract_finetune_index(name): 17 | # subroutine that parses string 18 | ft_idx = None 19 | if "emb" in name: 20 | ft_idx = -1 21 | elif name.startswith("transformers"): 22 | ft_idx = int(name.split(".")[1]) 23 | elif "head" in name: 24 | ft_idx = float("inf") # always FT the head 25 | return ft_idx 26 | 27 | params = [] 28 | for name, param in model.named_parameters(): 29 | if extract_finetune_index(name) >= finetune and param.requires_grad: 30 | params.append(param) 31 | else: 32 | param.requires_grad = False 33 | return params 34 | 35 | 36 | def set_up_optim( 37 | model, 38 | device, 39 | solver="AdamW", 40 | dp=False, 41 | finetune=-1, 42 | sample_rate=1, 43 | alphas=[2], 44 | noise_multiplier=0.01, 45 | max_grad_norm=0.1, 46 | batch_size=1, 47 | warmup_steps=5000, 48 | lr=0.001, 49 | Huggingface=False, 50 | perturb=False, 51 | ): 52 | model = model.to(device) 53 | if Huggingface: 54 | params = model.parameters() 55 | else: 56 | params = finetunable_GPT2_params(model, finetune) 57 | if solver == "AdamW": 58 | opt = AdamW 59 | elif solver == "SGD": 60 | opt = optim.SGD 61 | optimizer = opt(params, lr=lr) 62 | if dp: 63 | model.train() 64 | privacy_engine = PrivacyEngine( 65 | model, 66 | alphas=alphas, 67 | sample_rate=sample_rate, 68 | noise_multiplier=noise_multiplier, 69 | max_grad_norm=max_grad_norm, 70 | batch_size=batch_size, 71 | ) 72 | privacy_engine.attach(optimizer) 73 | else: 74 | optimizer.virtual_step = lambda: None 75 | return optimizer 76 | 77 | 78 | def cross_entropy_eval(lm_logits, labels): 79 | """ 80 | Routine from Huggingface's GPT-2 implementation (v 4.7.0) 81 | """ 82 | shift_logits = lm_logits[..., :-1, :].contiguous() 83 | shift_labels = labels[..., 1:].contiguous() 84 | # Flatten the tokens 85 | XH = nn.CrossEntropyLoss() 86 | return XH(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1)) 87 | 88 | 89 | def model_checkpoint(model, path, idx=0, epoch=0): 90 | chck_path = f"{path}/checkpoint_{idx}_at_epoch_{epoch}" 91 | print(f"Checkpointing model to: {chck_path}") 92 | torch.save(model, chck_path) 93 | 94 | 95 | def test( 96 | model, 97 | device, 98 | test_loader, 99 | epoch, 100 | max_iters, 101 | print_freq=100, 102 | delta=None, 103 | Huggingface=False, 104 | checkpoint=0, 105 | checkpoint_path=None, 106 | ): 107 | model.eval() 108 | losses = [] 109 | with torch.no_grad(): 110 | for i, data in enumerate(tqdm.tqdm(test_loader)): 111 | data = data.to(device) 112 | logits = model(data, labels=data).logits if Huggingface else model(data) 113 | loss = cross_entropy_eval(logits, data) 114 | losses.append(loss.item()) 115 | if i >= max_iters: 116 | break 117 | print(f"Val Loss: {np.mean(losses):.4f} ") 118 | if checkpoint_path != None: 119 | model_checkpoint(model, checkpoint_path, idx=checkpoint, epoch=epoch) 120 | return losses 121 | 122 | 123 | def train( 124 | model, 125 | device, 126 | train_loader, 127 | val_loader, 128 | epoch, 129 | optimizer, 130 | virtual_batch_size, 131 | max_iters, 132 | val_freq=2048, 133 | val_iters=512, 134 | print_freq=100, 135 | delta=1.0, 136 | Huggingface=False, 137 | checkpoint_path=None, 138 | ): 139 | model = model.to(device) 140 | model.train() 141 | losses = [] 142 | val_losses = [] 143 | eps = [] 144 | checkpt_counter = 0 145 | for i, data in enumerate(tqdm.tqdm(train_loader)): 146 | data = data.to(device) 147 | optimizer.zero_grad() 148 | logits = model(data, labels=data).logits if Huggingface else model(data) 149 | loss = cross_entropy_eval(logits, data) 150 | loss.backward() 151 | if ((i + 1) % virtual_batch_size == 0) or ((i + 1) == len(train_loader)): 152 | optimizer.step() 153 | optimizer.zero_grad() 154 | else: 155 | optimizer.virtual_step() 156 | losses.append(loss.item()) 157 | 158 | if (i + 1) % print_freq == 0: 159 | if delta >= 1: 160 | print(f"Train Epoch: {epoch} \t Loss: {np.mean(losses):.6f}") 161 | else: 162 | rdp = optimizer.privacy_engine.get_renyi_divergence()[0] 163 | epsilon = rdp * optimizer.privacy_engine.steps 164 | alpha = optimizer.privacy_engine.alphas[0] 165 | print( 166 | f"Train Epoch: {epoch} \t" 167 | f"Loss: {np.mean(losses[-20:]):.4f} " 168 | f"ε = {epsilon:.4f} for α = {alpha}" 169 | ) 170 | eps.append((epsilon, alpha)) 171 | if (i + 1) % val_freq == 0: 172 | val_loss = test( 173 | model, 174 | device, 175 | val_loader, 176 | epoch, 177 | val_iters, 178 | print_freq=val_iters, 179 | Huggingface=Huggingface, 180 | checkpoint_path=checkpoint_path, 181 | checkpoint=checkpt_counter, 182 | ) 183 | checkpt_counter += 1 184 | val_losses.append(val_loss) 185 | model.train() 186 | if i >= max_iters: 187 | print(f"Reached max iteration {i}. Training will now stop.") 188 | break 189 | 190 | return {"train_losses": losses, "val_losses": val_losses, "epsilons": eps} 191 | -------------------------------------------------------------------------------- /opacus_lab/models/GPT2/refactor.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Meta Platforms, Inc. and its affiliates. All Rights Reserved 3 | 4 | import torch 5 | import torch.nn as nn 6 | 7 | from opacus_lab.models.GPT2.model.attention import AttentionLayer 8 | from opacus_lab.models.GPT2.model.embedding import PositionalEmbedding, TokenEmbedding 9 | from opacus_lab.models.GPT2.model.feedforward import PositionwiseFeedForward 10 | from opacus_lab.models.GPT2.model.transformer import Transformer, TransformerLayer 11 | 12 | 13 | def refactor_transformer( 14 | GPT2, 15 | size="S", 16 | use_low_rank=False, 17 | lm_head_rank=768, 18 | dropout=0.0, 19 | perturb=False, 20 | vocab_size=50257, 21 | ): 22 | size_assertion_failure_str = f"Value {size} is not a valid size. " 23 | size_assertion_failure_str += 'Size must be one of: "S" (small), ' 24 | size_assertion_failure_str += '"M" (medium), "L" (large),' 25 | size_assertion_failure_str += '"XL" (extra large),' 26 | size_assertion_failure_str += 'or "D" (distilled).' 27 | assert size in {"S", "D", "M", "L", "XL"}, size_assertion_failure_str 28 | 29 | size2dim = {"S": 768, "M": 1024, "L": 1280, "XL": 1600, "D": 768} 30 | size2blks = {"S": 12, "M": 24, "L": 36, "XL": 48, "D": 6} 31 | size2head = {"S": 12, "M": 16, "L": 20, "XL": 25, "D": 12} 32 | # specify some "architecture size" vars 33 | dim = size2dim[size] 34 | n_blks = size2blks[size] 35 | n_heads = size2head[size] 36 | 37 | # define a bunch of modular subroutines to complete the refactor 38 | 39 | def refactor_feedforward(GPT2MLP): 40 | FC = GPT2MLP.c_fc 41 | Proj = GPT2MLP.c_proj 42 | 43 | Feedforward = PositionwiseFeedForward(dim) 44 | Feedforward.fc.weight = nn.Parameter(FC.weight.t()) 45 | Feedforward.fc.bias = nn.Parameter(FC.bias) 46 | Feedforward.proj.weight = nn.Parameter(Proj.weight.t()) 47 | Feedforward.proj.bias = nn.Parameter(Proj.bias) 48 | return Feedforward 49 | 50 | def refactor_attention(GPT2Attention): 51 | Conv1D = GPT2Attention.c_attn 52 | Proj = GPT2Attention.c_proj 53 | 54 | Attention = AttentionLayer(n_heads, dim, 0.1) 55 | Attention.linear.weight = nn.Parameter(Proj.weight.t()) 56 | Attention.linear.bias = nn.Parameter(Proj.bias) 57 | 58 | q_weight, k_weight, v_weight = torch.split(Conv1D.weight, [dim] * 3, dim=-1) 59 | q_bias, k_bias, v_bias = torch.split(Conv1D.bias, [dim] * 3, dim=-1) 60 | 61 | Attention.proj_q.weight = nn.Parameter(q_weight.t()) 62 | Attention.proj_k.weight = nn.Parameter(k_weight.t()) 63 | Attention.proj_v.weight = nn.Parameter(v_weight.t()) 64 | 65 | Attention.proj_q.bias = nn.Parameter(q_bias) 66 | Attention.proj_k.bias = nn.Parameter(k_bias) 67 | Attention.proj_v.bias = nn.Parameter(v_bias) 68 | 69 | return Attention 70 | 71 | def refactor_block(GPT2Block): 72 | # 4X expansion rate is hardcoded below 73 | Block = TransformerLayer(n_heads, dim, 4) 74 | 75 | # first copy layernorm weights, no refactor needed 76 | Block.ln_attn.weight = nn.Parameter(GPT2Block.ln_1.weight) 77 | Block.ln_attn.bias = nn.Parameter(GPT2Block.ln_1.bias) 78 | Block.ln_ff.weight = nn.Parameter(GPT2Block.ln_2.weight) 79 | Block.ln_ff.bias = nn.Parameter(GPT2Block.ln_2.bias) 80 | 81 | # next refactor and copy the attention & FC layers 82 | Block.attn = refactor_attention(GPT2Block.attn) 83 | Block.ff = refactor_feedforward(GPT2Block.mlp) 84 | 85 | return Block 86 | 87 | def refactor_embeddings(GPT2): 88 | # num of pos emb hardcoded below 89 | wpe = PositionalEmbedding(1024, dim) 90 | wte = TokenEmbedding(vocab_size, dim) 91 | 92 | # If we extend the vocabulary, we only set the new embeddings 93 | gpt2_vocab_size = GPT2.transformer.wte.weight.shape[0] 94 | wte.emb.weight.data[:gpt2_vocab_size] = GPT2.transformer.wte.weight.data 95 | wpe.emb.weight = nn.Parameter(GPT2.transformer.wpe.weight) 96 | return wpe, wte 97 | 98 | def refactor_head(GPT2): 99 | head = nn.Linear(dim, vocab_size, bias=False) 100 | ln_head = nn.LayerNorm(dim) 101 | ln_head.weight = nn.Parameter(GPT2.transformer.ln_f.weight) 102 | ln_head.bias = nn.Parameter(GPT2.transformer.ln_f.bias) 103 | 104 | gpt2_vocab_size = GPT2.lm_head.weight.shape[0] 105 | head.weight.data[:gpt2_vocab_size] = GPT2.lm_head.weight.data 106 | 107 | return head, ln_head 108 | 109 | # a few hardcoded values: 110 | # pad index token id = 50256 111 | # max sequence len = 1024 112 | # head expansion factor = 4 113 | T = Transformer( 114 | n_blks, 115 | 50256, 116 | vocab_size, 117 | 1024, 118 | n_heads, 119 | dim, 120 | 4, 121 | use_low_rank_head=use_low_rank, 122 | lm_head_rank=lm_head_rank, 123 | perturb=perturb, 124 | dropout=dropout, 125 | ) 126 | 127 | # first refactor the transformer stack 128 | for i, block in enumerate(GPT2.transformer.h): 129 | T.transformers[i] = refactor_block(block) 130 | 131 | # then refactor the embeddings 132 | positional_emb, token_emb = refactor_embeddings(GPT2) 133 | T.positional_embedding = positional_emb 134 | T.token_embedding = token_emb 135 | 136 | # finally don't forget about head's layernorm & linear 137 | head, ln_head = refactor_head(GPT2) 138 | T.lm_head = head 139 | T.ln_head = ln_head 140 | 141 | return T 142 | 143 | 144 | def test_refactor(pretrained, refactored, vocab_size=50257, exact=True): 145 | V = pretrained.transformer.wte.weight.shape[0] 146 | B, T, V = 2, 5, vocab_size 147 | string = torch.randint(V, size=(B, T), dtype=torch.int32) 148 | pretrained = pretrained.eval() 149 | refactored = refactored.eval() 150 | X = pretrained(string) 151 | Y = refactored(string) 152 | 153 | # If refactored model has larger vocabulary, we restrict it to the pretrained model's vocab 154 | if Y.shape[1] > X.logits.shape[1]: 155 | Y = Y[:, : X.logits.shape[1]] 156 | 157 | if exact: 158 | return Y.equal(X.logits) 159 | else: 160 | return torch.norm(X.logits - Y) / torch.norm(X.logits) < 1e-4 161 | -------------------------------------------------------------------------------- /opacus_lab/models/GPT2/model/transformer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Meta Platforms, Inc. and its affiliates. All Rights Reserved 3 | 4 | from functools import partial 5 | from typing import List, Optional, Tuple, Union 6 | 7 | import torch 8 | import torch.nn as nn 9 | import torch.utils.checkpoint 10 | 11 | from opacus_lab.models.GPT2.model.attention import AttentionLayer, Past 12 | from opacus_lab.models.GPT2.model.embedding import PositionalEmbedding, TokenEmbedding 13 | from opacus_lab.models.GPT2.model.feedforward import PositionwiseFeedForward 14 | from opacus_lab.models.GPT2.model.masking import FutureMasking, PadMasking 15 | 16 | 17 | def factorize_linear_layer(LinearLayer, rank): 18 | U, S, Vh = torch.linalg.svd(LinearLayer.weight, full_matrices=False) 19 | V = Vh.mH 20 | lr_S = S[:rank] 21 | lr_U = U[:, 0:rank] 22 | lr_V = V.t()[:rank] 23 | out_features = lr_U.shape[0] 24 | in_features = lr_V.shape[1] 25 | bias = LinearLayer.bias is not None 26 | lr_LinearLayer = FactorizedLinear(in_features, out_features, rank, bias=bias) 27 | lr_LinearLayer.R.weight = nn.Parameter(torch.sqrt(lr_S).diag() @ lr_V) 28 | lr_LinearLayer.L.weight = nn.Parameter(lr_U @ torch.sqrt(lr_S).diag()) 29 | if bias: 30 | lr_LinearLayer.L.bias = nn.Parameter(LinearLayer.bias) 31 | return lr_LinearLayer 32 | 33 | 34 | def lrp_linear_layer(LinearLayer, rank): 35 | o, i = LinearLayer.weight.shape 36 | bias = LinearLayer.bias is not None 37 | lrp_LinearLayer = LowRankPerturbedLinear(i, o, rank, bias=bias) 38 | lrp_LinearLayer.core.weight = nn.Parameter(LinearLayer.weight, requires_grad=False) 39 | if bias: 40 | lrp_LinearLayer.core.bias = nn.Parameter(LinearLayer.bias, requires_grad=False) 41 | return lrp_LinearLayer 42 | 43 | 44 | class FactorizedLinear(nn.Module): 45 | def __init__( 46 | self, in_features: int, out_features: int, rank: int, bias: bool = True 47 | ): 48 | super().__init__() 49 | self.R = nn.Linear(in_features, rank, bias=False) 50 | self.L = nn.Linear(rank, out_features, bias=bias) 51 | 52 | def forward(self, x: torch.Tensor): 53 | return self.L(self.R(x)) 54 | 55 | 56 | class LowRankPerturbedLinear(nn.Module): 57 | def __init__( 58 | self, 59 | in_features: int, 60 | out_features: int, 61 | rank: int, 62 | scale: float = 0.0001, 63 | bias: bool = True, 64 | ): 65 | super().__init__() 66 | self.core = nn.Linear(in_features, out_features, bias=bias) 67 | self.LR = FactorizedLinear(in_features, out_features, rank, bias=bias) 68 | self.scale = scale 69 | 70 | def forward(self, x: torch.Tensor): 71 | return self.scale * self.LR(x) + self.core(x) 72 | 73 | 74 | class TransformerLayer(nn.Module): 75 | """ 76 | Tensor Type Shape 77 | =========================================================================== 78 | x float (..., seq_len, dims) 79 | past (*) float (..., past_len, dims) 80 | mask bool (..., seq_len, past_len + seq_len) 81 | --------------------------------------------------------------------------- 82 | output 1 float (..., seq_len, dims) 83 | output 2 (*) float (..., past_len + seq_len, dims) 84 | =========================================================================== 85 | """ 86 | 87 | def __init__(self, heads: int, dims: int, rate: int, dropout: float = 0.1): 88 | super().__init__() 89 | self.attn = AttentionLayer(heads, dims, dropout) 90 | self.ff = PositionwiseFeedForward(dims, rate, dropout) 91 | self.ln_attn = nn.LayerNorm(dims) 92 | self.ln_ff = nn.LayerNorm(dims) 93 | 94 | def forward( 95 | self, 96 | x: torch.Tensor, 97 | past: Optional[Past] = None, 98 | mask: Optional[torch.Tensor] = None, 99 | ) -> Union[torch.Tensor, Tuple[torch.Tensor, Past]]: 100 | # Layer normalizations are performed before the layers respectively. 101 | a = self.ln_attn(x) 102 | a, past = self.attn(a, a, a, past, mask) 103 | x = x + a 104 | x = x + self.ff(self.ln_ff(x)) 105 | return x 106 | 107 | 108 | class Transformer(nn.Module): 109 | """ 110 | Tensor Type Shape 111 | =========================================================================== 112 | x long (..., seq_len) 113 | past (**) float (..., past_len, dims) 114 | --------------------------------------------------------------------------- 115 | output 1 float (..., seq_len, dims) 116 | output 2 (**) float (..., past_len + seq_len, dims) 117 | =========================================================================== 118 | """ 119 | 120 | def __init__( 121 | self, 122 | layers: int, 123 | pad_idx: int, 124 | words: int, 125 | seq_len: int, 126 | heads: int, 127 | dims: int, 128 | rate: int = 4, 129 | dropout: float = 0.1, 130 | finetune: int = -1, 131 | lm_head_rank: int = 768, 132 | use_low_rank_head: bool = False, 133 | perturb: bool = True, 134 | bidirectional: bool = True, 135 | ): 136 | super().__init__() 137 | self.bidirectional = bidirectional 138 | self.pad_masking = PadMasking(pad_idx) 139 | self.future_masking = FutureMasking() 140 | self.positional_embedding = PositionalEmbedding(seq_len, dims) 141 | self.token_embedding = TokenEmbedding(words, dims) 142 | self.dropout_embedding = nn.Dropout(dropout) 143 | 144 | self.transformers = nn.ModuleList( 145 | [TransformerLayer(heads, dims, rate, dropout) for _ in range(layers)] 146 | ) 147 | self.ln_head = nn.LayerNorm(dims) 148 | self.finetune = finetune 149 | 150 | if use_low_rank_head and lm_head_rank < dims: 151 | if perturb: 152 | self.lm_head = LowRankPerturbedLinear( 153 | dims, words, rank=lm_head_rank, bias=False 154 | ) 155 | else: 156 | self.lm_head = FactorizedLinear( 157 | dims, words, rank=lm_head_rank, bias=False 158 | ) 159 | else: 160 | self.lm_head = nn.Linear(dims, words, bias=False) 161 | 162 | def forward( 163 | self, 164 | x: torch.Tensor, 165 | past: Optional[List[Past]] = None, 166 | use_grad_ckpt: bool = False, 167 | ) -> Union[torch.Tensor, Tuple[torch.Tensor, List[Past]]]: 168 | torch.set_grad_enabled(self.finetune < 0) 169 | offset = past[0][0].size(-2) if past is not None else 0 170 | 171 | # Create masking tensor. 172 | mask = self.pad_masking(x, offset) 173 | if not self.bidirectional: 174 | mask = mask + self.future_masking(x, offset) 175 | 176 | x = self.token_embedding(x) + self.positional_embedding(x, offset) 177 | x = self.dropout_embedding(x) 178 | 179 | # Apply transformer layers sequentially. 180 | for i, transformer in enumerate(self.transformers): 181 | torch.set_grad_enabled(self.finetune <= i) 182 | if self.training and use_grad_ckpt: 183 | transformer = partial(torch.utils.checkpoint.checkpoint, transformer) 184 | 185 | x = transformer(x, past[i] if past is not None else None, mask) 186 | 187 | torch.set_grad_enabled(self.finetune <= i + 1) 188 | x = self.ln_head(x) 189 | x = self.lm_head(x) 190 | return x 191 | -------------------------------------------------------------------------------- /examples/GPT2/run.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Meta Platforms, Inc. and its affiliates. All Rights Reserved 3 | 4 | import argparse 5 | 6 | import torch 7 | from opacus_lab.models.GPT2.dataset import CorpusDataset 8 | from opacus_lab.models.GPT2.refactor import refactor_transformer, test_refactor 9 | from opacus_lab.models.GPT2.train import set_up_optim, train 10 | from torch.utils.data import DataLoader 11 | from transformers import GPT2LMHeadModel 12 | 13 | # until opacus-lab is pip installable as a module we 14 | # work around by just appending a sys path 15 | # import sys 16 | # sys.path.append('../../../opacus-lab') 17 | 18 | 19 | parser = argparse.ArgumentParser(description="GPT-2 implementation for Opacus") 20 | """parser.add_argument( 21 | "-sr", 22 | "--sample-rate", 23 | type=float, 24 | default=0.001, 25 | metavar="SR", 26 | help="sample rate used for batch construction (default: 0.001)", 27 | )""" 28 | parser.add_argument( 29 | "-bs", 30 | "--batch-size", 31 | type=int, 32 | default=1, 33 | metavar="BS", 34 | help="Batch size (default: 1)", 35 | ) 36 | parser.add_argument( 37 | "-vbs", 38 | "--virtual-batch-size", 39 | type=int, 40 | default=2048, 41 | metavar="VBS", 42 | help="Virtual batch size (default: 4)", 43 | ) 44 | parser.add_argument( 45 | "--seqlen", 46 | type=int, 47 | default=512, 48 | help="Sequence length to block text into (default: 32)", 49 | ) 50 | parser.add_argument( 51 | "--size", 52 | type=str, 53 | default="S", 54 | choices=["S", "L", "M", "D"], 55 | help="Model size of GPT-2 (default: S)", 56 | ) 57 | parser.add_argument( 58 | "--finetune-layers", 59 | type=int, 60 | default=-1, 61 | help="Fine-tune from which layer # upwards? Embeddings are layer # 0 \ 62 | (default: -1)", 63 | ) 64 | parser.add_argument( 65 | "--low-rank-head", 66 | action="store_true", 67 | default=False, 68 | help="Should we use a low-rank output layer? (default: false)", 69 | ) 70 | parser.add_argument( 71 | "--head-rank", 72 | type=int, 73 | default=768, 74 | help="Rank of the output layer. Ignored if --low-rank-head is not set.\ 75 | (default: 768)", 76 | ) 77 | parser.add_argument( 78 | "--perturb", 79 | action="store_true", 80 | default=False, 81 | help="Should we use a low-rank perturbation for the output layer? \ 82 | (default: false)", 83 | ) 84 | parser.add_argument( 85 | "-n", 86 | "--epochs", 87 | type=int, 88 | default=1, 89 | metavar="N", 90 | help="number of epochs to train (default: 1)", 91 | ) 92 | parser.add_argument( 93 | "--lr", 94 | type=float, 95 | default=0.0001, 96 | metavar="LR", 97 | help="learning rate (default: .1)", 98 | ) 99 | parser.add_argument( 100 | "--sigma", 101 | type=float, 102 | default=1.0, 103 | metavar="S", 104 | help="Noise multiplier (default 1.0)", 105 | ) 106 | parser.add_argument( 107 | "-c", 108 | "--gradclip", 109 | type=float, 110 | default=1.0, 111 | metavar="C", 112 | help="Clip per-sample gradients to this norm (default 1.0)", 113 | ) 114 | parser.add_argument( 115 | "--delta", 116 | type=float, 117 | default=1e-5, 118 | metavar="D", 119 | help="Target delta (default: 1e-5)", 120 | ) 121 | parser.add_argument( 122 | "--dropout", 123 | type=float, 124 | default=0.0, 125 | help="Dropout value (default: 0.0)", 126 | ) 127 | parser.add_argument( 128 | "--max-train-iters", 129 | type=float, 130 | default=float("inf"), 131 | help="Set a max # of training iterations (default: inf)", 132 | ) 133 | parser.add_argument( 134 | "--device", 135 | type=str, 136 | default="cuda", 137 | help="GPU ID for this process (default: 'cuda')", 138 | ) 139 | parser.add_argument( 140 | "--save-model", 141 | action="store_true", 142 | default=False, 143 | help="Save the trained model (default: false)", 144 | ) 145 | parser.add_argument( 146 | "--checkpoint-model", 147 | action="store_true", 148 | default=True, 149 | help="Checkpoint the model after each evaluation (default: true)", 150 | ) 151 | parser.add_argument( 152 | "--checkpoint-path", 153 | type=str, 154 | default="./", 155 | help="Path to save model checkpoints", 156 | ) 157 | parser.add_argument( 158 | "--print-freq", 159 | type=int, 160 | default=100, 161 | help="Print update every --print-freq iters (default: 100)", 162 | ) 163 | parser.add_argument( 164 | "--val-freq", 165 | type=int, 166 | default=2000, 167 | help="Run validation set every --val-freq iters (default: 2000)", 168 | ) 169 | parser.add_argument( 170 | "--val-iters", 171 | type=int, 172 | default=512, 173 | help="# of validation samples to run (default: 512)", 174 | ) 175 | parser.add_argument( 176 | "--disable-dp", 177 | action="store_true", 178 | default=False, 179 | help="Disable privacy training", 180 | ) 181 | parser.add_argument( 182 | "--skip-refactor", 183 | action="store_true", 184 | default=False, 185 | help="Skip refactor and use Huggingface's GPT-2. \ 186 | Requires setting --disable-dp flag.", 187 | ) 188 | parser.add_argument( 189 | "--secure-rng", 190 | action="store_true", 191 | default=False, 192 | help="Enable Secure RNG to have trustworthy privacy guarantees. \ 193 | Comes at a performance cost", 194 | ) 195 | parser.add_argument( 196 | "--seed", 197 | type=int, 198 | default=1234, 199 | help="Set random seed. Automatically ignored if using secure RNG.", 200 | ) 201 | parser.add_argument( 202 | "--data-root", 203 | type=str, 204 | default="./", 205 | help="Where wikitext is/will be stored", 206 | ) 207 | 208 | 209 | def _load_model(args): 210 | if args.size == "L": 211 | s = "gpt2-large" 212 | elif args.size == "M": 213 | s = "gpt2-medium" 214 | elif args.size == "S": 215 | s = "gpt2" 216 | elif args.size == "XL": 217 | s = "gpt2-xl" 218 | elif args.size == "D": 219 | s = "distilgpt2" 220 | else: 221 | raise ValueError(f"Unexpected value of arg.size {args.size}") 222 | model = GPT2LMHeadModel.from_pretrained(s) 223 | if not args.skip_refactor: 224 | pretrained_model = model 225 | model = refactor_transformer( 226 | pretrained_model, 227 | use_low_rank=args.low_rank_head, 228 | size=args.size, 229 | lm_head_rank=args.head_rank, 230 | perturb=args.perturb, 231 | dropout=args.dropout, 232 | ) 233 | assert test_refactor(pretrained_model, model), "Refactor failed..." 234 | print("Refactor successful!") 235 | return model 236 | 237 | 238 | def _load_wikitext(path): 239 | corpus = dict() 240 | for dset in ["valid", "train", "test"]: 241 | corpus[dset] = torch.load(f"{path}/wikitext-103-{dset}-corpus.pt") 242 | return corpus 243 | 244 | 245 | def _dataloading(args): 246 | corpus = _load_wikitext(args.data_root) 247 | trainloader = DataLoader( 248 | CorpusDataset(corpus["train"], args.seqlen), 249 | shuffle=True, 250 | batch_size=args.batch_size, 251 | ) 252 | testloader = DataLoader( 253 | CorpusDataset(corpus["test"], args.seqlen), 254 | shuffle=True, 255 | batch_size=args.batch_size, 256 | ) 257 | valloader = DataLoader( 258 | CorpusDataset(corpus["valid"], args.seqlen), 259 | shuffle=True, 260 | batch_size=args.batch_size, 261 | ) 262 | 263 | return trainloader, testloader, valloader 264 | 265 | 266 | def _training(args, model, loaders): 267 | trainloader, testloader, valloader = loaders 268 | n_samples = len(trainloader.dataset) 269 | sample_rate = (args.batch_size * args.virtual_batch_size) / n_samples 270 | optim, scheduler = set_up_optim( 271 | model, 272 | args.device, 273 | dp=(not args.disable_dp), 274 | finetune=args.finetune_layers, 275 | batch_size=args.batch_size, 276 | noise_multiplier=args.sigma, 277 | max_grad_norm=args.gradclip, 278 | alphas=[2, 4, 8, 16, 32], 279 | lr=args.lr, 280 | sample_rate=sample_rate, 281 | warmup_steps=args.warmup_steps, 282 | Huggingface=args.skip_refactor, 283 | ) 284 | L = dict() 285 | for e in range(args.epochs): 286 | L[e] = train( 287 | model, 288 | args.device, 289 | trainloader, 290 | valloader, 291 | e, 292 | optim, 293 | args.virtual_batch_size, 294 | args.max_train_iters, 295 | print_freq=args.print_freq, 296 | Huggingface=args.skip_refactor, 297 | delta=args.delta if not args.disable_dp else 1.0, 298 | checkpoint_path=args.checkpoint_path if args.checkpoint_model else None, 299 | ) 300 | return L 301 | 302 | 303 | if __name__ == "__main__": 304 | args = parser.parse_args() 305 | torch.manual_seed(args.seed) 306 | model = _load_model(args) 307 | loaders = _dataloading(args) 308 | _training(args, model, loaders) 309 | if args.save_model: 310 | torch.save(model, "GPT2.pt") 311 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019, PyTorch team 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------