-
Notifications
You must be signed in to change notification settings - Fork 362
/
Copy pathlayers.py
581 lines (504 loc) · 19 KB
/
layers.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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
# 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.
from typing import Callable, Dict, Optional, Tuple, Type, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
from opacus.grad_sample.utils import wrap_model
from opacus.layers import DPGRU, DPLSTM, DPRNN, DPMultiheadAttention
from opacus.layers.dp_rnn import DPRNNBase
class LayerType:
LINEAR: str = "linear"
CONV: str = "conv"
LAYERNORM: str = "layernorm"
INSTANCENORM: str = "instancenorm"
GROUPNORM: str = "groupnorm"
EMBEDDING: str = "embedding"
MHA: str = "mha"
DPMHA: str = "dpmha"
RNN: str = "rnn"
DPRNN: str = "dprnn"
GRU: str = "gru"
DPGRU: str = "dpgru"
LSTM: str = "lstm"
DPLSTM: str = "dplstm"
class Layer:
_input_tensor: torch.Tensor
_module: nn.Module
_labels: torch.Tensor
def __init__(
self,
*,
random_seed: Optional[int] = None,
criterion: Callable = F.cross_entropy,
) -> None:
"""Sets random seed and criterion."""
if random_seed is not None:
torch.manual_seed(random_seed)
self._criterion = criterion
@staticmethod
def _get_memory_difference(device: torch.device, stats: Dict[str, int]) -> int:
"""If applicable, computes the device's CUDA memory difference between the
sum of the values in the stats dict and the current allocated CUDA memory.
Args:
device: torch.device
stats: dictionary from item names (e.g. input_tensor, module, labels)
to their respective sizes
Returns:
device's CUDA memory difference between the sum of the values in the
stats dict and the current allocated CUDA memory if given a CUDA
device. 0 if given a CPU device.
"""
if device.type == "cuda":
return torch.cuda.memory_allocated(device) - sum(stats.values())
return 0
def _inputs_to(self, device: torch.device, stats: Dict[str, int]) -> Dict[str, int]:
"""Some modules (e.g. RNNs) take additional layer inputs such as initial
hidden state. These modules should override this function accordingly.
Args:
device: torch.device
stats: dictionary from item names (e.g. input_tensor, module, labels)
to their respective sizes
Returns: updated stats dictionary with input tensor sizes
"""
self._input_tensor = self._input_tensor.to(device)
stats["input_tensor"] = self._get_memory_difference(device=device, stats=stats)
return stats
def to(self, device: torch.device) -> Dict[str, int]:
"""Moves input_tensor, additional inputs, module, and labels to device.
Args:
device: torch.device
Returns:
Dictionary from item names (e.g. input_tensor, module, labels) to
their respective sizes if CUDA device, else respective sizes are all
set to 0.
"""
stats: Dict[str, int] = {}
stats["offset"] = self._get_memory_difference(device=device, stats=stats)
# some modules take additional inputs such as hidden state
stats = self._inputs_to(device=device, stats=stats)
self._module = self._module.to(device)
stats["layer"] = self._get_memory_difference(device=device, stats=stats)
self._labels = self._labels.to(device)
stats["labels"] = self._get_memory_difference(device=device, stats=stats)
# check that all memory is accounted for
if device.type == "cuda":
assert torch.cuda.memory_allocated(device) == sum(stats.values())
return stats
def forward_only(self) -> torch.Tensor:
return self._module(self._input_tensor)
def forward_backward(self) -> None:
preds = self.forward_only()
loss = self._criterion(preds, self._labels)
loss.backward()
self._module.zero_grad()
def make_private(self, gsm_mode: str = "hooks") -> None:
self._module = wrap_model(self._module, grad_sample_mode=gsm_mode)
@property
def module(self):
return self._module
def __del__(self):
self.to(torch.device("cpu"))
class LinearBase(Layer):
def __init__(
self,
*,
batch_size: int,
input_shape: Tuple[int, ...],
in_features: int,
out_features: int,
bias: bool = True,
random_seed: Optional[int] = None,
criterion: Callable = F.cross_entropy,
) -> None:
super().__init__(random_seed=random_seed, criterion=criterion)
self._input_tensor = torch.randn(batch_size, *input_shape, in_features)
self._module = nn.Linear(
in_features=in_features,
out_features=out_features,
bias=bias,
)
self._labels = torch.randn(batch_size, *input_shape, out_features)
class ConvBase(Layer):
def __init__(
self,
*,
batch_size: int,
in_channels: int,
input_shape: Tuple[int, ...],
out_channels: int,
kernel_size: Union[int, Tuple[int, ...]],
stride: Union[int, Tuple[int, ...]] = 1,
padding: Union[str, int, Tuple[int, ...]] = 0,
dilation: Union[int, Tuple[int, ...]] = 1,
groups: int = 1,
bias: bool = True,
padding_mode: str = "zeros",
random_seed: Optional[int] = None,
criterion: Callable = F.cross_entropy,
) -> None:
super().__init__(random_seed=random_seed, criterion=criterion)
D = len(input_shape)
if D == 1:
self._module_name = nn.Conv1d
elif D == 2:
self._module_name = nn.Conv2d
elif D == 3:
self._module_name = nn.Conv3d
else:
raise Exception("Input shape must be between 1 and 3 long")
self._input_tensor = torch.randn(batch_size, in_channels, *input_shape)
self._module = self._module_name(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
dilation=dilation,
groups=groups,
bias=bias,
padding_mode=padding_mode,
)
outputs = self._module(self._input_tensor)
self._labels = torch.randn(outputs.shape)
del outputs
class LayerNormBase(Layer):
def __init__(
self,
*,
batch_size: int,
input_shape: Tuple[int, ...],
D: int,
eps: float = 1e-05,
elementwise_affine: bool = True,
random_seed: Optional[int] = None,
criterion: Callable = F.cross_entropy,
) -> None:
super().__init__(random_seed=random_seed, criterion=criterion)
self._input_tensor = torch.randn(batch_size, *input_shape)
self._module = nn.LayerNorm(
normalized_shape=self._input_tensor.shape[-D:],
eps=eps,
elementwise_affine=elementwise_affine,
)
self._labels = torch.randn(self._input_tensor.shape)
class InstanceNormBase(Layer):
def __init__(
self,
*,
batch_size: int,
num_features: int,
input_shape: Tuple[int, ...],
eps: float = 1e-05,
affine: bool = False,
track_running_stats: bool = False,
random_seed: Optional[int] = None,
criterion: Callable = F.cross_entropy,
) -> None:
super().__init__(random_seed=random_seed, criterion=criterion)
D = len(input_shape)
if D == 1:
self._module_name = nn.InstanceNorm1d
elif D == 2:
self._module_name = nn.InstanceNorm2d
elif D == 3:
self._module_name = nn.InstanceNorm3d
else:
raise Exception("Input shape must be between 1 and 3 long")
self._input_tensor = torch.randn(batch_size, num_features, *input_shape)
self._module = self._module_name(
num_features=num_features,
eps=eps,
affine=affine,
track_running_stats=track_running_stats,
)
self._labels = torch.randn(self._input_tensor.shape)
class GroupNormBase(Layer):
def __init__(
self,
*,
batch_size: int,
input_shape: Tuple[int, ...],
num_groups: int,
num_channels: int,
eps: float = 1e-05,
affine: bool = True,
random_seed: Optional[int] = None,
criterion: Callable = F.cross_entropy,
) -> None:
super().__init__(random_seed=random_seed, criterion=criterion)
self._input_tensor = torch.randn(batch_size, num_channels, *input_shape)
self._module = nn.GroupNorm(
num_groups=num_groups, num_channels=num_channels, eps=eps, affine=affine
)
self._labels = torch.randn(self._input_tensor.shape)
class EmbeddingBase(Layer):
def __init__(
self,
*,
batch_size: int,
input_shape: Tuple[int, ...],
num_embeddings: int,
embedding_dim: int,
padding_idx: Optional[int] = None,
max_norm: Optional[float] = None,
norm_type: float = 2.0,
scale_grad_by_freq: bool = False,
sparse: bool = False,
random_seed: Optional[int] = None,
criterion: Callable = F.cross_entropy,
) -> None:
super().__init__(random_seed=random_seed, criterion=criterion)
self._input_tensor = torch.randint(
high=num_embeddings,
size=(batch_size, *input_shape),
dtype=torch.long,
)
self._module = nn.Embedding(
num_embeddings=num_embeddings,
embedding_dim=embedding_dim,
padding_idx=padding_idx,
max_norm=max_norm,
norm_type=norm_type,
scale_grad_by_freq=scale_grad_by_freq,
sparse=sparse,
)
self._labels = torch.randn(batch_size, *input_shape, embedding_dim)
class MHABase(Layer):
def __init__(
self,
*,
layer: Union[Type[nn.MultiheadAttention], Type[DPMultiheadAttention]],
batch_size: int,
source_seq_len: int,
targ_seq_len: int,
embed_dim: int,
num_heads: int,
dropout: float = 0.0,
bias: bool = True,
add_bias_kv: bool = False,
add_zero_attn: bool = False,
kdim: Optional[int] = None,
vdim: Optional[int] = None,
batch_first: bool = False,
random_seed: Optional[int] = None,
criterion: Callable = F.cross_entropy,
) -> None:
super().__init__(random_seed=random_seed, criterion=criterion)
kdim = kdim if kdim else embed_dim
vdim = vdim if vdim else embed_dim
self._input_tensor = (
torch.randn(targ_seq_len, batch_size, embed_dim)
if not batch_first
else torch.randn(batch_size, targ_seq_len, embed_dim)
)
self._key = (
torch.randn(source_seq_len, batch_size, kdim)
if not batch_first
else torch.randn(batch_size, source_seq_len, kdim)
)
self._value = (
torch.randn(source_seq_len, batch_size, vdim)
if not batch_first
else torch.randn(batch_size, source_seq_len, vdim)
)
self._module = layer(
embed_dim,
num_heads,
dropout=dropout,
bias=bias,
add_bias_kv=add_bias_kv,
add_zero_attn=add_zero_attn,
kdim=kdim,
vdim=vdim,
)
self._labels = (
torch.randn(targ_seq_len, batch_size, embed_dim)
if not batch_first
else torch.randn(batch_size, targ_seq_len, embed_dim)
)
def _inputs_to(self, device: torch.device, stats: Dict[str, int]) -> Dict[str, int]:
"""MultiheadAttention takes additional layer inputs key and value.
Args:
device: torch.device
stats: dictionary from item names (e.g. input_tensor, module, labels)
to their respective sizes
Returns: updated stats dictionary with input tensor, key, and value size
"""
stats = super()._inputs_to(device=device, stats=stats)
self._key = self._key.to(device)
stats["key"] = self._get_memory_difference(device=device, stats=stats)
self._value = self._value.to(device)
stats["value"] = self._get_memory_difference(device=device, stats=stats)
return stats
def forward_only(self) -> torch.Tensor:
return self._module(self._input_tensor, self._key, self._value)[0]
class RNNBase(Layer):
def __init__(
self,
*,
layer: Union[Type[DPRNNBase], Type[nn.RNNBase]],
batch_size: int,
seq_len: int,
input_size: int,
hidden_size: int,
num_layers: int = 1,
bias: bool = False,
batch_first: bool = False,
dropout: float = 0,
bidirectional: bool = False,
random_seed: Optional[int] = None,
criterion: Callable = F.cross_entropy,
**kwargs,
) -> None:
super().__init__(random_seed=random_seed, criterion=criterion)
self._input_tensor = (
torch.randn(
seq_len,
batch_size,
input_size,
)
if not batch_first
else torch.randn(batch_size, seq_len, input_size)
)
D = 2 if bidirectional else 1
self._h_0 = torch.randn(D * num_layers, batch_size, hidden_size)
self._module = layer(
input_size=input_size,
hidden_size=hidden_size,
num_layers=num_layers,
bias=bias,
batch_first=batch_first,
dropout=dropout,
bidirectional=bidirectional,
**kwargs,
)
self._labels = (
torch.randn(seq_len, batch_size, D * hidden_size)
if not batch_first
else torch.randn(batch_size, seq_len, D * hidden_size)
)
def _inputs_to(self, device: torch.device, stats: Dict[str, int]) -> Dict[str, int]:
"""RNNs take additional layer inputs h_0.
Args:
device: torch.device
stats: dictionary from item names (e.g. input_tensor, module, labels)
to their respective sizes
Returns: updated stats dictionary with input tensor and h_0 size
"""
stats = super()._inputs_to(device=device, stats=stats)
self._h_0 = self._h_0.to(device)
stats["h_0"] = self._get_memory_difference(device=device, stats=stats)
return stats
def forward_only(self) -> torch.Tensor:
return self._module(self._input_tensor, self._h_0)[0]
class LSTMBase(RNNBase):
def __init__(
self,
*,
layer: Union[Type[nn.LSTM], Type[DPLSTM]],
batch_size: int,
seq_len: int,
input_size: int,
hidden_size: int,
num_layers: int = 1,
bias: bool = False,
batch_first: bool = False,
dropout: float = 0,
bidirectional: bool = False,
proj_size: int = 0,
random_seed: Optional[int] = None,
criterion: Callable = F.cross_entropy,
) -> None:
super().__init__(
layer=layer,
batch_size=batch_size,
seq_len=seq_len,
input_size=input_size,
hidden_size=hidden_size,
num_layers=num_layers,
bias=bias,
batch_first=batch_first,
dropout=dropout,
bidirectional=bidirectional,
proj_size=proj_size,
random_seed=random_seed,
criterion=criterion,
)
h_out = proj_size if proj_size > 0 else hidden_size
D = 2 if bidirectional else 1
self._h_0 = torch.randn(D * num_layers, batch_size, h_out)
self._c_0 = torch.randn(D * num_layers, batch_size, hidden_size)
self._labels = (
torch.randn(seq_len, batch_size, D * h_out)
if not batch_first
else torch.randn(batch_size, seq_len, D * h_out)
)
def _inputs_to(self, device: torch.device, stats: Dict[str, int]) -> Dict[str, int]:
"""LSTMs take additional layer inputs h_0, c_0.
Args:
device: torch.device
stats: dictionary from item names (e.g. input_tensor, module, labels)
to their respective sizes
Returns: updated stats dictionary with input tensor, h_0, and c_0 size
"""
stats = super()._inputs_to(device=device, stats=stats)
self._h_0 = self._h_0.to(device)
stats["h_0"] = self._get_memory_difference(device=device, stats=stats)
self._c_0 = self._c_0.to(device)
stats["c_0"] = self._get_memory_difference(device=device, stats=stats)
return stats
def forward_only(self) -> torch.Tensor:
return self._module(self._input_tensor, (self._h_0, self._c_0))[0]
class LayerFactory:
@staticmethod
# flake8: noqa C901
def create(
layer_name: str, gsm_mode: str = "baseline", **kwargs
) -> Optional[Layer]:
if gsm_mode not in ("baseline", "hooks", "ew", "functorch"):
raise ValueError(f"Unexpected grad_sample_mode={gsm_mode}")
if layer_name == LayerType.LINEAR:
module = LinearBase(**kwargs)
elif layer_name == LayerType.CONV:
module = ConvBase(**kwargs)
elif layer_name == LayerType.LAYERNORM:
module = LayerNormBase(**kwargs)
elif layer_name == LayerType.INSTANCENORM:
module = InstanceNormBase(**kwargs)
elif layer_name == LayerType.GROUPNORM:
module = GroupNormBase(**kwargs)
elif layer_name == LayerType.EMBEDDING:
module = EmbeddingBase(**kwargs)
elif layer_name == LayerType.RNN:
module = RNNBase(layer=nn.RNN, **kwargs)
elif layer_name == LayerType.DPRNN:
module = RNNBase(layer=DPRNN, **kwargs)
elif layer_name == LayerType.GRU:
module = RNNBase(layer=nn.GRU, **kwargs)
elif layer_name == LayerType.DPGRU:
module = RNNBase(layer=DPGRU, **kwargs)
elif layer_name == LayerType.LSTM:
module = LSTMBase(layer=nn.LSTM, **kwargs)
elif layer_name == LayerType.DPLSTM:
module = LSTMBase(layer=DPLSTM, **kwargs)
elif layer_name == LayerType.MHA:
module = MHABase(layer=nn.MultiheadAttention, **kwargs)
elif layer_name == LayerType.DPMHA:
module = MHABase(layer=DPMultiheadAttention, **kwargs)
else:
raise Exception(f"Invalid layer type: {layer_name}.")
if gsm_mode != "baseline":
module.make_private(gsm_mode=gsm_mode)
return module