forked from pytorch/opacus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimdb.py
295 lines (256 loc) · 8.08 KB
/
imdb.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Training sentiment prediction model on IMDB movie reviews dataset.
Architecture and reference results from https://arxiv.org/pdf/1911.11607.pdf
"""
import argparse
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from datasets import load_dataset
from opacus import PrivacyEngine
from torch.functional import F
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import DataLoader
from tqdm import tqdm
from transformers import BertTokenizerFast
# TODO: this is still broken
class SampleNet(nn.Module):
def __init__(self, vocab_size: int):
super().__init__()
self.emb = nn.Embedding(vocab_size, 16)
self.pool = nn.AdaptiveAvgPool1d(1)
self.fc1 = nn.Linear(16, 16)
self.fc2 = nn.Linear(16, 2)
def forward(self, x):
x = self.emb(x)
x = x.transpose(1, 2)
x = self.pool(x).squeeze()
x = self.fc1(x)
x = F.relu(x)
x = self.fc2(x)
return x
def name(self):
return "SampleNet"
def binary_accuracy(preds, y):
correct = (y.long() == torch.argmax(preds, dim=1)).float()
acc = correct.sum() / len(correct)
return acc
def padded_collate(batch, padding_idx=0):
x = pad_sequence(
[elem["input_ids"] for elem in batch],
batch_first=True,
padding_value=padding_idx,
)
y = torch.stack([elem["label"] for elem in batch]).long()
return x, y
def train(args, model, train_loader, optimizer, privacy_engine, epoch):
criterion = nn.CrossEntropyLoss()
losses = []
accuracies = []
device = torch.device(args.device)
model = model.train().to(device)
for data, label in tqdm(train_loader):
data = data.to(device)
label = label.to(device)
optimizer.zero_grad()
predictions = model(data).squeeze(1)
loss = criterion(predictions, label)
acc = binary_accuracy(predictions, label)
loss.backward()
optimizer.step()
losses.append(loss.item())
accuracies.append(acc.item())
if not args.disable_dp:
epsilon, best_alpha = privacy_engine.accountant.get_privacy_spent(
delta=args.delta
)
print(
f"Train Epoch: {epoch} \t"
f"Train Loss: {np.mean(losses):.6f} "
f"Train Accuracy: {np.mean(accuracies):.6f} "
f"(ε = {epsilon:.2f}, δ = {args.delta}) for α = {best_alpha}"
)
else:
print(
f"Train Epoch: {epoch} \t Loss: {np.mean(losses):.6f} ] \t Accuracy: {np.mean(accuracies):.6f}"
)
def evaluate(args, model, test_loader):
criterion = nn.CrossEntropyLoss()
losses = []
accuracies = []
device = torch.device(args.device)
model = model.eval().to(device)
with torch.no_grad():
for data, label in tqdm(test_loader):
data = data.to(device)
label = label.to(device)
predictions = model(data).squeeze(1)
loss = criterion(predictions, label)
acc = binary_accuracy(predictions, label)
losses.append(loss.item())
accuracies.append(acc.item())
mean_accuracy = np.mean(accuracies)
print(
"\nTest set: Average loss: {:.4f}, Accuracy: {:.2f}%\n".format(
np.mean(losses), mean_accuracy * 100
)
)
return mean_accuracy
def main():
parser = argparse.ArgumentParser(
description="Opacus IMDB Example",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"-b",
"--batch-size",
type=int,
default=64,
metavar="B",
help="input batch size for test",
)
parser.add_argument(
"-n",
"--epochs",
type=int,
default=10,
metavar="N",
help="number of epochs to train",
)
parser.add_argument(
"--lr",
type=float,
default=0.02,
metavar="LR",
help="learning rate",
)
parser.add_argument(
"--sigma",
type=float,
default=0.56,
metavar="S",
help="Noise multiplier",
)
parser.add_argument(
"-c",
"--max-per-sample-grad_norm",
type=float,
default=1.0,
metavar="C",
help="Clip per-sample gradients to this norm",
)
parser.add_argument(
"--delta",
type=float,
default=1e-5,
metavar="D",
help="Target delta (default: 1e-5)",
)
parser.add_argument(
"--max-sequence-length",
type=int,
default=256,
metavar="SL",
help="Longer sequences will be cut to this length",
)
parser.add_argument(
"--device",
type=str,
default="cuda",
help="GPU ID for this process",
)
parser.add_argument(
"--save-model",
action="store_true",
default=False,
help="Save the trained model",
)
parser.add_argument(
"--disable-dp",
action="store_true",
default=False,
help="Disable privacy training and just train with vanilla optimizer",
)
parser.add_argument(
"--secure-rng",
action="store_true",
default=False,
help="Enable Secure RNG to have trustworthy privacy guarantees. Comes at a performance cost",
)
parser.add_argument(
"--data-root", type=str, default="../imdb", help="Where IMDB is/will be stored"
)
parser.add_argument(
"-j",
"--workers",
default=2,
type=int,
metavar="N",
help="number of data loading workers",
)
args = parser.parse_args()
device = torch.device(args.device)
raw_dataset = load_dataset("imdb", cache_dir=args.data_root)
tokenizer = BertTokenizerFast.from_pretrained("bert-base-cased")
dataset = raw_dataset.map(
lambda x: tokenizer(
x["text"], truncation=True, max_length=args.max_sequence_length
),
batched=True,
)
dataset.set_format(type="torch", columns=["input_ids", "label"])
train_dataset = dataset["train"]
test_dataset = dataset["test"]
train_loader = DataLoader(
train_dataset,
num_workers=args.workers,
batch_size=args.batch_size,
collate_fn=padded_collate,
pin_memory=True,
shuffle=True,
)
test_loader = torch.utils.data.DataLoader(
test_dataset,
batch_size=args.batch_size,
shuffle=False,
num_workers=args.workers,
collate_fn=padded_collate,
pin_memory=True,
)
model = SampleNet(vocab_size=len(tokenizer)).to(device)
optimizer = optim.Adam(model.parameters(), lr=args.lr)
privacy_engine = None
if not args.disable_dp:
privacy_engine = PrivacyEngine(secure_mode=args.secure_rng)
# TODO: we need to switch poisson sampling back on, but the
# model exhibits strange behaviour with batch_size=1
model, optimizer, train_loader = privacy_engine.make_private(
module=model,
optimizer=optimizer,
data_loader=train_loader,
noise_multiplier=args.sigma,
max_grad_norm=args.max_per_sample_grad_norm,
poisson_sampling=False,
)
mean_accuracy = 0
for epoch in range(1, args.epochs + 1):
train(args, model, train_loader, optimizer, privacy_engine, epoch)
mean_accuracy = evaluate(args, model, test_loader)
torch.save(mean_accuracy, "run_results_imdb_classification.pt")
if __name__ == "__main__":
main()