Jagrut Thakare commited on
Commit
9be8aa9
·
1 Parent(s): 88984f3
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +6 -0
  2. .gitignore +5 -0
  3. AdaptiveWingLoss/.gitignore +8 -0
  4. AdaptiveWingLoss/core/__init__.py +0 -0
  5. AdaptiveWingLoss/core/coord_conv.py +153 -0
  6. AdaptiveWingLoss/core/dataloader.py +368 -0
  7. AdaptiveWingLoss/core/evaler.py +116 -0
  8. AdaptiveWingLoss/core/models.py +228 -0
  9. AdaptiveWingLoss/utils/__init__.py +0 -0
  10. AdaptiveWingLoss/utils/utils.py +355 -0
  11. LICENSE +201 -0
  12. SberSwapInference.ipynb +0 -0
  13. apex/.gitignore +6 -0
  14. apex/.gitmodules +7 -0
  15. apex/.nojekyll +0 -0
  16. apex/LICENSE +11 -0
  17. apex/README.md +146 -0
  18. apex/apex/RNN/README.md +1 -0
  19. apex/apex/RNN/RNNBackend.py +365 -0
  20. apex/apex/RNN/__init__.py +3 -0
  21. apex/apex/RNN/cells.py +84 -0
  22. apex/apex/RNN/models.py +54 -0
  23. apex/apex/__init__.py +20 -0
  24. apex/apex/amp/README.md +72 -0
  25. apex/apex/amp/__init__.py +5 -0
  26. apex/apex/amp/__version__.py +2 -0
  27. apex/apex/amp/_amp_state.py +69 -0
  28. apex/apex/amp/_initialize.py +263 -0
  29. apex/apex/amp/_process_optimizer.py +489 -0
  30. apex/apex/amp/amp.py +177 -0
  31. apex/apex/amp/compat.py +46 -0
  32. apex/apex/amp/frontend.py +442 -0
  33. apex/apex/amp/handle.py +281 -0
  34. apex/apex/amp/lists/__init__.py +0 -0
  35. apex/apex/amp/lists/functional_overrides.py +80 -0
  36. apex/apex/amp/lists/tensor_overrides.py +63 -0
  37. apex/apex/amp/lists/torch_overrides.py +115 -0
  38. apex/apex/amp/opt.py +103 -0
  39. apex/apex/amp/rnn_compat.py +53 -0
  40. apex/apex/amp/scaler.py +217 -0
  41. apex/apex/amp/utils.py +210 -0
  42. apex/apex/amp/wrap.py +276 -0
  43. apex/apex/contrib/__init__.py +0 -0
  44. apex/apex/contrib/bottleneck/__init__.py +1 -0
  45. apex/apex/contrib/bottleneck/bottleneck.py +214 -0
  46. apex/apex/contrib/bottleneck/test.py +71 -0
  47. apex/apex/contrib/csrc/bottleneck/bottleneck.cpp +1612 -0
  48. apex/apex/contrib/csrc/fmha/fmha_api.cpp +305 -0
  49. apex/apex/contrib/csrc/fmha/src/fmha.h +92 -0
  50. apex/apex/contrib/csrc/fmha/src/fmha/gemm.h +317 -0
.gitattributes CHANGED
@@ -33,3 +33,9 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ *.png filter=lfs diff=lfs merge=lfs -text
37
+ *.jpg filter=lfs diff=lfs merge=lfs -text
38
+ *.mp4 filter=lfs diff=lfs merge=lfs -text
39
+ *.gif filter=lfs diff=lfs merge=lfs -text
40
+ *.webp filter=lfs diff=lfs merge=lfs -text
41
+ *.params filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ */__pycache__/*
2
+ */__pycache__/
3
+ .ipynb_checkpoints
4
+ __pycache__
5
+ .venv/
AdaptiveWingLoss/.gitignore ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # Python generated files
2
+ *.pyc
3
+
4
+ # Project related files
5
+ ckpt/*.pth
6
+ dataset/*
7
+ !dataset/!.py
8
+ experiments/*
AdaptiveWingLoss/core/__init__.py ADDED
File without changes
AdaptiveWingLoss/core/coord_conv.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+
5
+ class AddCoordsTh(nn.Module):
6
+ def __init__(self, x_dim=64, y_dim=64, with_r=False, with_boundary=False):
7
+ super(AddCoordsTh, self).__init__()
8
+ self.x_dim = x_dim
9
+ self.y_dim = y_dim
10
+ self.with_r = with_r
11
+ self.with_boundary = with_boundary
12
+
13
+ def forward(self, input_tensor, heatmap=None):
14
+ """
15
+ input_tensor: (batch, c, x_dim, y_dim)
16
+ """
17
+ batch_size_tensor = input_tensor.shape[0]
18
+
19
+ xx_ones = torch.ones([1, self.y_dim], dtype=torch.int32).cuda()
20
+ xx_ones = xx_ones.unsqueeze(-1)
21
+
22
+ xx_range = torch.arange(self.x_dim, dtype=torch.int32).unsqueeze(0).cuda()
23
+ xx_range = xx_range.unsqueeze(1)
24
+
25
+ xx_channel = torch.matmul(xx_ones.float(), xx_range.float())
26
+ xx_channel = xx_channel.unsqueeze(-1)
27
+
28
+
29
+ yy_ones = torch.ones([1, self.x_dim], dtype=torch.int32).cuda()
30
+ yy_ones = yy_ones.unsqueeze(1)
31
+
32
+ yy_range = torch.arange(self.y_dim, dtype=torch.int32).unsqueeze(0).cuda()
33
+ yy_range = yy_range.unsqueeze(-1)
34
+
35
+ yy_channel = torch.matmul(yy_range.float(), yy_ones.float())
36
+ yy_channel = yy_channel.unsqueeze(-1)
37
+
38
+ xx_channel = xx_channel.permute(0, 3, 2, 1)
39
+ yy_channel = yy_channel.permute(0, 3, 2, 1)
40
+
41
+ xx_channel = xx_channel / (self.x_dim - 1)
42
+ yy_channel = yy_channel / (self.y_dim - 1)
43
+
44
+ xx_channel = xx_channel * 2 - 1
45
+ yy_channel = yy_channel * 2 - 1
46
+
47
+ xx_channel = xx_channel.repeat(batch_size_tensor, 1, 1, 1)
48
+ yy_channel = yy_channel.repeat(batch_size_tensor, 1, 1, 1)
49
+
50
+ if self.with_boundary and type(heatmap) != type(None):
51
+ boundary_channel = torch.clamp(heatmap[:, -1:, :, :],
52
+ 0.0, 1.0)
53
+
54
+ zero_tensor = torch.zeros_like(xx_channel)
55
+ xx_boundary_channel = torch.where(boundary_channel>0.05,
56
+ xx_channel, zero_tensor)
57
+ yy_boundary_channel = torch.where(boundary_channel>0.05,
58
+ yy_channel, zero_tensor)
59
+ if self.with_boundary and type(heatmap) != type(None):
60
+ xx_boundary_channel = xx_boundary_channel.cuda()
61
+ yy_boundary_channel = yy_boundary_channel.cuda()
62
+ ret = torch.cat([input_tensor, xx_channel, yy_channel], dim=1)
63
+
64
+
65
+ if self.with_r:
66
+ rr = torch.sqrt(torch.pow(xx_channel, 2) + torch.pow(yy_channel, 2))
67
+ rr = rr / torch.max(rr)
68
+ ret = torch.cat([ret, rr], dim=1)
69
+
70
+ if self.with_boundary and type(heatmap) != type(None):
71
+ ret = torch.cat([ret, xx_boundary_channel,
72
+ yy_boundary_channel], dim=1)
73
+ return ret
74
+
75
+
76
+ class CoordConvTh(nn.Module):
77
+ """CoordConv layer as in the paper."""
78
+ def __init__(self, x_dim, y_dim, with_r, with_boundary,
79
+ in_channels, first_one=False, *args, **kwargs):
80
+ super(CoordConvTh, self).__init__()
81
+ self.addcoords = AddCoordsTh(x_dim=x_dim, y_dim=y_dim, with_r=with_r,
82
+ with_boundary=with_boundary)
83
+ in_channels += 2
84
+ if with_r:
85
+ in_channels += 1
86
+ if with_boundary and not first_one:
87
+ in_channels += 2
88
+ self.conv = nn.Conv2d(in_channels=in_channels, *args, **kwargs)
89
+
90
+ def forward(self, input_tensor, heatmap=None):
91
+ ret = self.addcoords(input_tensor, heatmap)
92
+ last_channel = ret[:, -2:, :, :]
93
+ ret = self.conv(ret)
94
+ return ret, last_channel
95
+
96
+
97
+ '''
98
+ An alternative implementation for PyTorch with auto-infering the x-y dimensions.
99
+ '''
100
+ class AddCoords(nn.Module):
101
+
102
+ def __init__(self, with_r=False):
103
+ super().__init__()
104
+ self.with_r = with_r
105
+
106
+ def forward(self, input_tensor):
107
+ """
108
+ Args:
109
+ input_tensor: shape(batch, channel, x_dim, y_dim)
110
+ """
111
+ batch_size, _, x_dim, y_dim = input_tensor.size()
112
+
113
+ xx_channel = torch.arange(x_dim).repeat(1, y_dim, 1)
114
+ yy_channel = torch.arange(y_dim).repeat(1, x_dim, 1).transpose(1, 2)
115
+
116
+ xx_channel = xx_channel / (x_dim - 1)
117
+ yy_channel = yy_channel / (y_dim - 1)
118
+
119
+ xx_channel = xx_channel * 2 - 1
120
+ yy_channel = yy_channel * 2 - 1
121
+
122
+ xx_channel = xx_channel.repeat(batch_size, 1, 1, 1).transpose(2, 3)
123
+ yy_channel = yy_channel.repeat(batch_size, 1, 1, 1).transpose(2, 3)
124
+
125
+ if input_tensor.is_cuda:
126
+ xx_channel = xx_channel.cuda()
127
+ yy_channel = yy_channel.cuda()
128
+
129
+ ret = torch.cat([
130
+ input_tensor,
131
+ xx_channel.type_as(input_tensor),
132
+ yy_channel.type_as(input_tensor)], dim=1)
133
+
134
+ if self.with_r:
135
+ rr = torch.sqrt(torch.pow(xx_channel - 0.5, 2) + torch.pow(yy_channel - 0.5, 2))
136
+ if input_tensor.is_cuda:
137
+ rr = rr.cuda()
138
+ ret = torch.cat([ret, rr], dim=1)
139
+
140
+ return ret
141
+
142
+
143
+ class CoordConv(nn.Module):
144
+
145
+ def __init__(self, in_channels, out_channels, with_r=False, **kwargs):
146
+ super().__init__()
147
+ self.addcoords = AddCoords(with_r=with_r)
148
+ self.conv = nn.Conv2d(in_channels + 2, out_channels, **kwargs)
149
+
150
+ def forward(self, x):
151
+ ret = self.addcoords(x)
152
+ ret = self.conv(ret)
153
+ return ret
AdaptiveWingLoss/core/dataloader.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import os
3
+ import random
4
+ import glob
5
+ import torch
6
+ from skimage import io
7
+ from skimage import transform as ski_transform
8
+ from skimage.color import rgb2gray
9
+ import scipy.io as sio
10
+ from scipy import interpolate
11
+ import numpy as np
12
+ import matplotlib.pyplot as plt
13
+ from torch.utils.data import Dataset, DataLoader
14
+ from torchvision import transforms, utils
15
+ from torchvision.transforms import Lambda, Compose
16
+ from torchvision.transforms.functional import adjust_brightness, adjust_contrast, adjust_saturation, adjust_hue
17
+ from utils.utils import cv_crop, cv_rotate, draw_gaussian, transform, power_transform, shuffle_lr, fig2data, generate_weight_map
18
+ from PIL import Image
19
+ import cv2
20
+ import copy
21
+ import math
22
+ from imgaug import augmenters as iaa
23
+
24
+
25
+ class AddBoundary(object):
26
+ def __init__(self, num_landmarks=68):
27
+ self.num_landmarks = num_landmarks
28
+
29
+ def __call__(self, sample):
30
+ landmarks_64 = np.floor(sample['landmarks'] / 4.0)
31
+ if self.num_landmarks == 68:
32
+ boundaries = {}
33
+ boundaries['cheek'] = landmarks_64[0:17]
34
+ boundaries['left_eyebrow'] = landmarks_64[17:22]
35
+ boundaries['right_eyebrow'] = landmarks_64[22:27]
36
+ boundaries['uper_left_eyelid'] = landmarks_64[36:40]
37
+ boundaries['lower_left_eyelid'] = np.array([landmarks_64[i] for i in [36, 41, 40, 39]])
38
+ boundaries['upper_right_eyelid'] = landmarks_64[42:46]
39
+ boundaries['lower_right_eyelid'] = np.array([landmarks_64[i] for i in [42, 47, 46, 45]])
40
+ boundaries['noise'] = landmarks_64[27:31]
41
+ boundaries['noise_bot'] = landmarks_64[31:36]
42
+ boundaries['upper_outer_lip'] = landmarks_64[48:55]
43
+ boundaries['upper_inner_lip'] = np.array([landmarks_64[i] for i in [60, 61, 62, 63, 64]])
44
+ boundaries['lower_outer_lip'] = np.array([landmarks_64[i] for i in [48, 59, 58, 57, 56, 55, 54]])
45
+ boundaries['lower_inner_lip'] = np.array([landmarks_64[i] for i in [60, 67, 66, 65, 64]])
46
+ elif self.num_landmarks == 98:
47
+ boundaries = {}
48
+ boundaries['cheek'] = landmarks_64[0:33]
49
+ boundaries['left_eyebrow'] = landmarks_64[33:38]
50
+ boundaries['right_eyebrow'] = landmarks_64[42:47]
51
+ boundaries['uper_left_eyelid'] = landmarks_64[60:65]
52
+ boundaries['lower_left_eyelid'] = np.array([landmarks_64[i] for i in [60, 67, 66, 65, 64]])
53
+ boundaries['upper_right_eyelid'] = landmarks_64[68:73]
54
+ boundaries['lower_right_eyelid'] = np.array([landmarks_64[i] for i in [68, 75, 74, 73, 72]])
55
+ boundaries['noise'] = landmarks_64[51:55]
56
+ boundaries['noise_bot'] = landmarks_64[55:60]
57
+ boundaries['upper_outer_lip'] = landmarks_64[76:83]
58
+ boundaries['upper_inner_lip'] = np.array([landmarks_64[i] for i in [88, 89, 90, 91, 92]])
59
+ boundaries['lower_outer_lip'] = np.array([landmarks_64[i] for i in [76, 87, 86, 85, 84, 83, 82]])
60
+ boundaries['lower_inner_lip'] = np.array([landmarks_64[i] for i in [88, 95, 94, 93, 92]])
61
+ elif self.num_landmarks == 19:
62
+ boundaries = {}
63
+ boundaries['left_eyebrow'] = landmarks_64[0:3]
64
+ boundaries['right_eyebrow'] = landmarks_64[3:5]
65
+ boundaries['left_eye'] = landmarks_64[6:9]
66
+ boundaries['right_eye'] = landmarks_64[9:12]
67
+ boundaries['noise'] = landmarks_64[12:15]
68
+
69
+ elif self.num_landmarks == 29:
70
+ boundaries = {}
71
+ boundaries['upper_left_eyebrow'] = np.stack([
72
+ landmarks_64[0],
73
+ landmarks_64[4],
74
+ landmarks_64[2]
75
+ ], axis=0)
76
+ boundaries['lower_left_eyebrow'] = np.stack([
77
+ landmarks_64[0],
78
+ landmarks_64[5],
79
+ landmarks_64[2]
80
+ ], axis=0)
81
+ boundaries['upper_right_eyebrow'] = np.stack([
82
+ landmarks_64[1],
83
+ landmarks_64[6],
84
+ landmarks_64[3]
85
+ ], axis=0)
86
+ boundaries['lower_right_eyebrow'] = np.stack([
87
+ landmarks_64[1],
88
+ landmarks_64[7],
89
+ landmarks_64[3]
90
+ ], axis=0)
91
+ boundaries['upper_left_eye'] = np.stack([
92
+ landmarks_64[8],
93
+ landmarks_64[12],
94
+ landmarks_64[10]
95
+ ], axis=0)
96
+ boundaries['lower_left_eye'] = np.stack([
97
+ landmarks_64[8],
98
+ landmarks_64[13],
99
+ landmarks_64[10]
100
+ ], axis=0)
101
+ boundaries['upper_right_eye'] = np.stack([
102
+ landmarks_64[9],
103
+ landmarks_64[14],
104
+ landmarks_64[11]
105
+ ], axis=0)
106
+ boundaries['lower_right_eye'] = np.stack([
107
+ landmarks_64[9],
108
+ landmarks_64[15],
109
+ landmarks_64[11]
110
+ ], axis=0)
111
+ boundaries['noise'] = np.stack([
112
+ landmarks_64[18],
113
+ landmarks_64[21],
114
+ landmarks_64[19]
115
+ ], axis=0)
116
+ boundaries['outer_upper_lip'] = np.stack([
117
+ landmarks_64[22],
118
+ landmarks_64[24],
119
+ landmarks_64[23]
120
+ ], axis=0)
121
+ boundaries['inner_upper_lip'] = np.stack([
122
+ landmarks_64[22],
123
+ landmarks_64[25],
124
+ landmarks_64[23]
125
+ ], axis=0)
126
+ boundaries['outer_lower_lip'] = np.stack([
127
+ landmarks_64[22],
128
+ landmarks_64[26],
129
+ landmarks_64[23]
130
+ ], axis=0)
131
+ boundaries['inner_lower_lip'] = np.stack([
132
+ landmarks_64[22],
133
+ landmarks_64[27],
134
+ landmarks_64[23]
135
+ ], axis=0)
136
+ functions = {}
137
+
138
+ for key, points in boundaries.items():
139
+ temp = points[0]
140
+ new_points = points[0:1, :]
141
+ for point in points[1:]:
142
+ if point[0] == temp[0] and point[1] == temp[1]:
143
+ continue
144
+ else:
145
+ new_points = np.concatenate((new_points, np.expand_dims(point, 0)), axis=0)
146
+ temp = point
147
+ points = new_points
148
+ if points.shape[0] == 1:
149
+ points = np.concatenate((points, points+0.001), axis=0)
150
+ k = min(4, points.shape[0])
151
+ functions[key] = interpolate.splprep([points[:, 0], points[:, 1]], k=k-1,s=0)
152
+
153
+ boundary_map = np.zeros((64, 64))
154
+
155
+ fig = plt.figure(figsize=[64/96.0, 64/96.0], dpi=96)
156
+
157
+ ax = fig.add_axes([0, 0, 1, 1])
158
+
159
+ ax.axis('off')
160
+
161
+ ax.imshow(boundary_map, interpolation='nearest', cmap='gray')
162
+ #ax.scatter(landmarks[:, 0], landmarks[:, 1], s=1, marker=',', c='w')
163
+
164
+ for key in functions.keys():
165
+ xnew = np.arange(0, 1, 0.01)
166
+ out = interpolate.splev(xnew, functions[key][0], der=0)
167
+ plt.plot(out[0], out[1], ',', linewidth=1, color='w')
168
+
169
+ img = fig2data(fig)
170
+
171
+ plt.close()
172
+
173
+ sigma = 1
174
+ temp = 255-img[:,:,1]
175
+ temp = cv2.distanceTransform(temp, cv2.DIST_L2, cv2.DIST_MASK_PRECISE)
176
+ temp = temp.astype(np.float32)
177
+ temp = np.where(temp < 3*sigma, np.exp(-(temp*temp)/(2*sigma*sigma)), 0 )
178
+
179
+ fig = plt.figure(figsize=[64/96.0, 64/96.0], dpi=96)
180
+
181
+ ax = fig.add_axes([0, 0, 1, 1])
182
+
183
+ ax.axis('off')
184
+ ax.imshow(temp, cmap='gray')
185
+ plt.close()
186
+
187
+ boundary_map = fig2data(fig)
188
+
189
+ sample['boundary'] = boundary_map[:, :, 0]
190
+
191
+ return sample
192
+
193
+ class AddWeightMap(object):
194
+ def __call__(self, sample):
195
+ heatmap= sample['heatmap']
196
+ boundary = sample['boundary']
197
+ heatmap = np.concatenate((heatmap, np.expand_dims(boundary, axis=0)), 0)
198
+ weight_map = np.zeros_like(heatmap)
199
+ for i in range(heatmap.shape[0]):
200
+ weight_map[i] = generate_weight_map(weight_map[i],
201
+ heatmap[i])
202
+ sample['weight_map'] = weight_map
203
+ return sample
204
+
205
+ class ToTensor(object):
206
+ """Convert ndarrays in sample to Tensors."""
207
+
208
+ def __call__(self, sample):
209
+ image, heatmap, landmarks, boundary, weight_map= sample['image'], sample['heatmap'], sample['landmarks'], sample['boundary'], sample['weight_map']
210
+
211
+ # swap color axis because
212
+ # numpy image: H x W x C
213
+ # torch image: C X H X W
214
+ if len(image.shape) == 2:
215
+ image = np.expand_dims(image, axis=2)
216
+ image_small = np.expand_dims(image_small, axis=2)
217
+ image = image.transpose((2, 0, 1))
218
+ boundary = np.expand_dims(boundary, axis=2)
219
+ boundary = boundary.transpose((2, 0, 1))
220
+ return {'image': torch.from_numpy(image).float().div(255.0),
221
+ 'heatmap': torch.from_numpy(heatmap).float(),
222
+ 'landmarks': torch.from_numpy(landmarks).float(),
223
+ 'boundary': torch.from_numpy(boundary).float().div(255.0),
224
+ 'weight_map': torch.from_numpy(weight_map).float()}
225
+
226
+ class FaceLandmarksDataset(Dataset):
227
+ """Face Landmarks dataset."""
228
+
229
+ def __init__(self, img_dir, landmarks_dir, num_landmarks=68, gray_scale=False,
230
+ detect_face=False, enhance=False, center_shift=0,
231
+ transform=None,):
232
+ """
233
+ Args:
234
+ landmark_dir (string): Path to the mat file with landmarks saved.
235
+ img_dir (string): Directory with all the images.
236
+ transform (callable, optional): Optional transform to be applied
237
+ on a sample.
238
+ """
239
+ self.img_dir = img_dir
240
+ self.landmarks_dir = landmarks_dir
241
+ self.num_lanmdkars = num_landmarks
242
+ self.transform = transform
243
+ self.img_names = glob.glob(self.img_dir+'*.jpg') + \
244
+ glob.glob(self.img_dir+'*.png')
245
+ self.gray_scale = gray_scale
246
+ self.detect_face = detect_face
247
+ self.enhance = enhance
248
+ self.center_shift = center_shift
249
+ if self.detect_face:
250
+ self.face_detector = MTCNN(thresh=[0.5, 0.6, 0.7])
251
+ def __len__(self):
252
+ return len(self.img_names)
253
+
254
+ def __getitem__(self, idx):
255
+ img_name = self.img_names[idx]
256
+ pil_image = Image.open(img_name)
257
+ if pil_image.mode != "RGB":
258
+ # if input is grayscale image, convert it to 3 channel image
259
+ if self.enhance:
260
+ pil_image = power_transform(pil_image, 0.5)
261
+ temp_image = Image.new('RGB', pil_image.size)
262
+ temp_image.paste(pil_image)
263
+ pil_image = temp_image
264
+ image = np.array(pil_image)
265
+ if self.gray_scale:
266
+ image = rgb2gray(image)
267
+ image = np.expand_dims(image, axis=2)
268
+ image = np.concatenate((image, image, image), axis=2)
269
+ image = image * 255.0
270
+ image = image.astype(np.uint8)
271
+ if not self.detect_face:
272
+ center = [450//2, 450//2+0]
273
+ if self.center_shift != 0:
274
+ center[0] += int(np.random.uniform(-self.center_shift,
275
+ self.center_shift))
276
+ center[1] += int(np.random.uniform(-self.center_shift,
277
+ self.center_shift))
278
+ scale = 1.8
279
+ else:
280
+ detected_faces = self.face_detector.detect_image(image)
281
+ if len(detected_faces) > 0:
282
+ box = detected_faces[0]
283
+ left, top, right, bottom, _ = box
284
+ center = [right - (right - left) / 2.0,
285
+ bottom - (bottom - top) / 2.0]
286
+ center[1] = center[1] - (bottom - top) * 0.12
287
+ scale = (right - left + bottom - top) / 195.0
288
+ else:
289
+ center = [450//2, 450//2+0]
290
+ scale = 1.8
291
+ if self.center_shift != 0:
292
+ shift = self.center * self.center_shift / 450
293
+ center[0] += int(np.random.uniform(-shift, shift))
294
+ center[1] += int(np.random.uniform(-shift, shift))
295
+ base_name = os.path.basename(img_name)
296
+ landmarks_base_name = base_name[:-4] + '_pts.mat'
297
+ landmarks_name = os.path.join(self.landmarks_dir, landmarks_base_name)
298
+ if os.path.isfile(landmarks_name):
299
+ mat_data = sio.loadmat(landmarks_name)
300
+ landmarks = mat_data['pts_2d']
301
+ elif os.path.isfile(landmarks_name[:-8] + '.pts.npy'):
302
+ landmarks = np.load(landmarks_name[:-8] + '.pts.npy')
303
+ else:
304
+ landmarks = []
305
+ heatmap = []
306
+
307
+ if landmarks != []:
308
+ new_image, new_landmarks = cv_crop(image, landmarks, center,
309
+ scale, 256, self.center_shift)
310
+ tries = 0
311
+ while self.center_shift != 0 and tries < 5 and (np.max(new_landmarks) > 240 or np.min(new_landmarks) < 15):
312
+ center = [450//2, 450//2+0]
313
+ scale += 0.05
314
+ center[0] += int(np.random.uniform(-self.center_shift,
315
+ self.center_shift))
316
+ center[1] += int(np.random.uniform(-self.center_shift,
317
+ self.center_shift))
318
+
319
+ new_image, new_landmarks = cv_crop(image, landmarks,
320
+ center, scale, 256,
321
+ self.center_shift)
322
+ tries += 1
323
+ if np.max(new_landmarks) > 250 or np.min(new_landmarks) < 5:
324
+ center = [450//2, 450//2+0]
325
+ scale = 2.25
326
+ new_image, new_landmarks = cv_crop(image, landmarks,
327
+ center, scale, 256,
328
+ 100)
329
+ assert (np.min(new_landmarks) > 0 and np.max(new_landmarks) < 256), \
330
+ "Landmarks out of boundary!"
331
+ image = new_image
332
+ landmarks = new_landmarks
333
+ heatmap = np.zeros((self.num_lanmdkars, 64, 64))
334
+ for i in range(self.num_lanmdkars):
335
+ if landmarks[i][0] > 0:
336
+ heatmap[i] = draw_gaussian(heatmap[i], landmarks[i]/4.0+1, 1)
337
+ sample = {'image': image, 'heatmap': heatmap, 'landmarks': landmarks}
338
+ if self.transform:
339
+ sample = self.transform(sample)
340
+
341
+ return sample
342
+
343
+ def get_dataset(val_img_dir, val_landmarks_dir, batch_size,
344
+ num_landmarks=68, rotation=0, scale=0,
345
+ center_shift=0, random_flip=False,
346
+ brightness=0, contrast=0, saturation=0,
347
+ blur=False, noise=False, jpeg_effect=False,
348
+ random_occlusion=False, gray_scale=False,
349
+ detect_face=False, enhance=False):
350
+ val_transforms = transforms.Compose([AddBoundary(num_landmarks),
351
+ AddWeightMap(),
352
+ ToTensor()])
353
+
354
+ val_dataset = FaceLandmarksDataset(val_img_dir, val_landmarks_dir,
355
+ num_landmarks=num_landmarks,
356
+ gray_scale=gray_scale,
357
+ detect_face=detect_face,
358
+ enhance=enhance,
359
+ transform=val_transforms)
360
+
361
+ val_dataloader = torch.utils.data.DataLoader(val_dataset,
362
+ batch_size=batch_size,
363
+ shuffle=False,
364
+ num_workers=6)
365
+ data_loaders = {'val': val_dataloader}
366
+ dataset_sizes = {}
367
+ dataset_sizes['val'] = len(val_dataset)
368
+ return data_loaders, dataset_sizes
AdaptiveWingLoss/core/evaler.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import matplotlib
2
+ matplotlib.use('Agg')
3
+ import math
4
+ import torch
5
+ import copy
6
+ import time
7
+ from torch.autograd import Variable
8
+ import shutil
9
+ from skimage import io
10
+ import numpy as np
11
+ from utils.utils import fan_NME, show_landmarks, get_preds_fromhm
12
+ from PIL import Image, ImageDraw
13
+ import os
14
+ import sys
15
+ import cv2
16
+ import matplotlib.pyplot as plt
17
+
18
+
19
+ device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
20
+
21
+ def eval_model(model, dataloaders, dataset_sizes,
22
+ writer, use_gpu=True, epoches=5, dataset='val',
23
+ save_path='./', num_landmarks=68):
24
+ global_nme = 0
25
+ model.eval()
26
+ for epoch in range(epoches):
27
+ running_loss = 0
28
+ step = 0
29
+ total_nme = 0
30
+ total_count = 0
31
+ fail_count = 0
32
+ nmes = []
33
+ # running_corrects = 0
34
+
35
+ # Iterate over data.
36
+ with torch.no_grad():
37
+ for data in dataloaders[dataset]:
38
+ total_runtime = 0
39
+ run_count = 0
40
+ step_start = time.time()
41
+ step += 1
42
+ # get the inputs
43
+ inputs = data['image'].type(torch.FloatTensor)
44
+ labels_heatmap = data['heatmap'].type(torch.FloatTensor)
45
+ labels_boundary = data['boundary'].type(torch.FloatTensor)
46
+ landmarks = data['landmarks'].type(torch.FloatTensor)
47
+ loss_weight_map = data['weight_map'].type(torch.FloatTensor)
48
+ # wrap them in Variable
49
+ if use_gpu:
50
+ inputs = inputs.to(device)
51
+ labels_heatmap = labels_heatmap.to(device)
52
+ labels_boundary = labels_boundary.to(device)
53
+ loss_weight_map = loss_weight_map.to(device)
54
+ else:
55
+ inputs, labels_heatmap = Variable(inputs), Variable(labels_heatmap)
56
+ labels_boundary = Variable(labels_boundary)
57
+ labels = torch.cat((labels_heatmap, labels_boundary), 1)
58
+ single_start = time.time()
59
+ outputs, boundary_channels = model(inputs)
60
+ single_end = time.time()
61
+ total_runtime += time.time() - single_start
62
+ run_count += 1
63
+ step_end = time.time()
64
+ for i in range(inputs.shape[0]):
65
+ img = inputs[i]
66
+ img = img.cpu().numpy()
67
+ img = img.transpose((1, 2, 0))*255.0
68
+ img = img.astype(np.uint8)
69
+ img = Image.fromarray(img)
70
+ # pred_heatmap = outputs[-1][i].detach().cpu()[:-1, :, :]
71
+ pred_heatmap = outputs[-1][:, :-1, :, :][i].detach().cpu()
72
+ pred_landmarks, _ = get_preds_fromhm(pred_heatmap.unsqueeze(0))
73
+ pred_landmarks = pred_landmarks.squeeze().numpy()
74
+
75
+ gt_landmarks = data['landmarks'][i].numpy()
76
+ if num_landmarks == 68:
77
+ left_eye = np.average(gt_landmarks[36:42], axis=0)
78
+ right_eye = np.average(gt_landmarks[42:48], axis=0)
79
+ norm_factor = np.linalg.norm(left_eye - right_eye)
80
+ # norm_factor = np.linalg.norm(gt_landmarks[36]- gt_landmarks[45])
81
+
82
+ elif num_landmarks == 98:
83
+ norm_factor = np.linalg.norm(gt_landmarks[60]- gt_landmarks[72])
84
+ elif num_landmarks == 19:
85
+ left, top = gt_landmarks[-2, :]
86
+ right, bottom = gt_landmarks[-1, :]
87
+ norm_factor = math.sqrt(abs(right - left)*abs(top-bottom))
88
+ gt_landmarks = gt_landmarks[:-2, :]
89
+ elif num_landmarks == 29:
90
+ # norm_factor = np.linalg.norm(gt_landmarks[8]- gt_landmarks[9])
91
+ norm_factor = np.linalg.norm(gt_landmarks[16]- gt_landmarks[17])
92
+ single_nme = (np.sum(np.linalg.norm(pred_landmarks*4 - gt_landmarks, axis=1)) / pred_landmarks.shape[0]) / norm_factor
93
+
94
+ nmes.append(single_nme)
95
+ total_count += 1
96
+ if single_nme > 0.1:
97
+ fail_count += 1
98
+ if step % 10 == 0:
99
+ print('Step {} Time: {:.6f} Input Mean: {:.6f} Output Mean: {:.6f}'.format(
100
+ step, step_end - step_start,
101
+ torch.mean(labels),
102
+ torch.mean(outputs[0])))
103
+ # gt_landmarks = landmarks.numpy()
104
+ # pred_heatmap = outputs[-1].to('cpu').numpy()
105
+ gt_landmarks = landmarks
106
+ batch_nme = fan_NME(outputs[-1][:, :-1, :, :].detach().cpu(), gt_landmarks, num_landmarks)
107
+ # batch_nme = 0
108
+ total_nme += batch_nme
109
+ epoch_nme = total_nme / dataset_sizes['val']
110
+ global_nme += epoch_nme
111
+ nme_save_path = os.path.join(save_path, 'nme_log.npy')
112
+ np.save(nme_save_path, np.array(nmes))
113
+ print('NME: {:.6f} Failure Rate: {:.6f} Total Count: {:.6f} Fail Count: {:.6f}'.format(epoch_nme, fail_count/total_count, total_count, fail_count))
114
+ print('Evaluation done! Average NME: {:.6f}'.format(global_nme/epoches))
115
+ print('Everage runtime for a single batch: {:.6f}'.format(total_runtime/run_count))
116
+ return model
AdaptiveWingLoss/core/models.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ import math
5
+ from AdaptiveWingLoss.core.coord_conv import CoordConvTh
6
+
7
+
8
+ def conv3x3(in_planes, out_planes, strd=1, padding=1,
9
+ bias=False,dilation=1):
10
+ "3x3 convolution with padding"
11
+ return nn.Conv2d(in_planes, out_planes, kernel_size=3,
12
+ stride=strd, padding=padding, bias=bias,
13
+ dilation=dilation)
14
+
15
+ class BasicBlock(nn.Module):
16
+ expansion = 1
17
+
18
+ def __init__(self, inplanes, planes, stride=1, downsample=None):
19
+ super(BasicBlock, self).__init__()
20
+ self.conv1 = conv3x3(inplanes, planes, stride)
21
+ # self.bn1 = nn.BatchNorm2d(planes)
22
+ self.relu = nn.ReLU(inplace=True)
23
+ self.conv2 = conv3x3(planes, planes)
24
+ # self.bn2 = nn.BatchNorm2d(planes)
25
+ self.downsample = downsample
26
+ self.stride = stride
27
+
28
+ def forward(self, x):
29
+ residual = x
30
+
31
+ out = self.conv1(x)
32
+ # out = self.bn1(out)
33
+ out = self.relu(out)
34
+
35
+ out = self.conv2(out)
36
+ # out = self.bn2(out)
37
+
38
+ if self.downsample is not None:
39
+ residual = self.downsample(x)
40
+
41
+ out += residual
42
+ out = self.relu(out)
43
+
44
+ return out
45
+
46
+ class ConvBlock(nn.Module):
47
+ def __init__(self, in_planes, out_planes):
48
+ super(ConvBlock, self).__init__()
49
+ self.bn1 = nn.BatchNorm2d(in_planes)
50
+ self.conv1 = conv3x3(in_planes, int(out_planes / 2))
51
+ self.bn2 = nn.BatchNorm2d(int(out_planes / 2))
52
+ self.conv2 = conv3x3(int(out_planes / 2), int(out_planes / 4),
53
+ padding=1, dilation=1)
54
+ self.bn3 = nn.BatchNorm2d(int(out_planes / 4))
55
+ self.conv3 = conv3x3(int(out_planes / 4), int(out_planes / 4),
56
+ padding=1, dilation=1)
57
+
58
+ if in_planes != out_planes:
59
+ self.downsample = nn.Sequential(
60
+ nn.BatchNorm2d(in_planes),
61
+ nn.ReLU(True),
62
+ nn.Conv2d(in_planes, out_planes,
63
+ kernel_size=1, stride=1, bias=False),
64
+ )
65
+ else:
66
+ self.downsample = None
67
+
68
+ def forward(self, x):
69
+ residual = x
70
+
71
+ out1 = self.bn1(x)
72
+ out1 = F.relu(out1, True)
73
+ out1 = self.conv1(out1)
74
+
75
+ out2 = self.bn2(out1)
76
+ out2 = F.relu(out2, True)
77
+ out2 = self.conv2(out2)
78
+
79
+ out3 = self.bn3(out2)
80
+ out3 = F.relu(out3, True)
81
+ out3 = self.conv3(out3)
82
+
83
+ out3 = torch.cat((out1, out2, out3), 1)
84
+
85
+ if self.downsample is not None:
86
+ residual = self.downsample(residual)
87
+
88
+ out3 += residual
89
+
90
+ return out3
91
+
92
+ class HourGlass(nn.Module):
93
+ def __init__(self, num_modules, depth, num_features, first_one=False):
94
+ super(HourGlass, self).__init__()
95
+ self.num_modules = num_modules
96
+ self.depth = depth
97
+ self.features = num_features
98
+ self.coordconv = CoordConvTh(x_dim=64, y_dim=64,
99
+ with_r=True, with_boundary=True,
100
+ in_channels=256, first_one=first_one,
101
+ out_channels=256,
102
+ kernel_size=1,
103
+ stride=1, padding=0)
104
+ self._generate_network(self.depth)
105
+
106
+ def _generate_network(self, level):
107
+ self.add_module('b1_' + str(level), ConvBlock(256, 256))
108
+
109
+ self.add_module('b2_' + str(level), ConvBlock(256, 256))
110
+
111
+ if level > 1:
112
+ self._generate_network(level - 1)
113
+ else:
114
+ self.add_module('b2_plus_' + str(level), ConvBlock(256, 256))
115
+
116
+ self.add_module('b3_' + str(level), ConvBlock(256, 256))
117
+
118
+ def _forward(self, level, inp):
119
+ # Upper branch
120
+ up1 = inp
121
+ up1 = self._modules['b1_' + str(level)](up1)
122
+
123
+ # Lower branch
124
+ low1 = F.avg_pool2d(inp, 2, stride=2)
125
+ low1 = self._modules['b2_' + str(level)](low1)
126
+
127
+ if level > 1:
128
+ low2 = self._forward(level - 1, low1)
129
+ else:
130
+ low2 = low1
131
+ low2 = self._modules['b2_plus_' + str(level)](low2)
132
+
133
+ low3 = low2
134
+ low3 = self._modules['b3_' + str(level)](low3)
135
+
136
+ up2 = F.upsample(low3, scale_factor=2, mode='nearest')
137
+
138
+ return up1 + up2
139
+
140
+ def forward(self, x, heatmap):
141
+ x, last_channel = self.coordconv(x, heatmap)
142
+ return self._forward(self.depth, x), last_channel
143
+
144
+ class FAN(nn.Module):
145
+
146
+ def __init__(self, num_modules=1, end_relu=False, gray_scale=False,
147
+ num_landmarks=68):
148
+ super(FAN, self).__init__()
149
+ self.num_modules = num_modules
150
+ self.gray_scale = gray_scale
151
+ self.end_relu = end_relu
152
+ self.num_landmarks = num_landmarks
153
+
154
+ # Base part
155
+ if self.gray_scale:
156
+ self.conv1 = CoordConvTh(x_dim=256, y_dim=256,
157
+ with_r=True, with_boundary=False,
158
+ in_channels=3, out_channels=64,
159
+ kernel_size=7,
160
+ stride=2, padding=3)
161
+ else:
162
+ self.conv1 = CoordConvTh(x_dim=256, y_dim=256,
163
+ with_r=True, with_boundary=False,
164
+ in_channels=3, out_channels=64,
165
+ kernel_size=7,
166
+ stride=2, padding=3)
167
+ self.bn1 = nn.BatchNorm2d(64)
168
+ self.conv2 = ConvBlock(64, 128)
169
+ self.conv3 = ConvBlock(128, 128)
170
+ self.conv4 = ConvBlock(128, 256)
171
+
172
+ # Stacking part
173
+ for hg_module in range(self.num_modules):
174
+ if hg_module == 0:
175
+ first_one = True
176
+ else:
177
+ first_one = False
178
+ self.add_module('m' + str(hg_module), HourGlass(1, 4, 256,
179
+ first_one))
180
+ self.add_module('top_m_' + str(hg_module), ConvBlock(256, 256))
181
+ self.add_module('conv_last' + str(hg_module),
182
+ nn.Conv2d(256, 256, kernel_size=1, stride=1, padding=0))
183
+ self.add_module('bn_end' + str(hg_module), nn.BatchNorm2d(256))
184
+ self.add_module('l' + str(hg_module), nn.Conv2d(256,
185
+ num_landmarks+1, kernel_size=1, stride=1, padding=0))
186
+
187
+ if hg_module < self.num_modules - 1:
188
+ self.add_module(
189
+ 'bl' + str(hg_module), nn.Conv2d(256, 256, kernel_size=1, stride=1, padding=0))
190
+ self.add_module('al' + str(hg_module), nn.Conv2d(num_landmarks+1,
191
+ 256, kernel_size=1, stride=1, padding=0))
192
+
193
+ def forward(self, x):
194
+ x, _ = self.conv1(x)
195
+ x = F.relu(self.bn1(x), True)
196
+ # x = F.relu(self.bn1(self.conv1(x)), True)
197
+ x = F.avg_pool2d(self.conv2(x), 2, stride=2)
198
+ x = self.conv3(x)
199
+ x = self.conv4(x)
200
+
201
+ previous = x
202
+
203
+ outputs = []
204
+ boundary_channels = []
205
+ tmp_out = None
206
+ for i in range(self.num_modules):
207
+ hg, boundary_channel = self._modules['m' + str(i)](previous,
208
+ tmp_out)
209
+
210
+ ll = hg
211
+ ll = self._modules['top_m_' + str(i)](ll)
212
+
213
+ ll = F.relu(self._modules['bn_end' + str(i)]
214
+ (self._modules['conv_last' + str(i)](ll)), True)
215
+
216
+ # Predict heatmaps
217
+ tmp_out = self._modules['l' + str(i)](ll)
218
+ if self.end_relu:
219
+ tmp_out = F.relu(tmp_out) # HACK: Added relu
220
+ outputs.append(tmp_out)
221
+ boundary_channels.append(boundary_channel)
222
+
223
+ if i < self.num_modules - 1:
224
+ ll = self._modules['bl' + str(i)](ll)
225
+ tmp_out_ = self._modules['al' + str(i)](tmp_out)
226
+ previous = previous + ll + tmp_out_
227
+
228
+ return outputs, boundary_channels
AdaptiveWingLoss/utils/__init__.py ADDED
File without changes
AdaptiveWingLoss/utils/utils.py ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import print_function, division
2
+ import os
3
+ import sys
4
+ import math
5
+ import torch
6
+ import cv2
7
+ from PIL import Image
8
+ from skimage import io
9
+ from skimage import transform as ski_transform
10
+ from scipy import ndimage
11
+ import numpy as np
12
+ import matplotlib
13
+ import matplotlib.pyplot as plt
14
+ from torch.utils.data import Dataset, DataLoader
15
+ from torchvision import transforms, utils
16
+
17
+ def _gaussian(
18
+ size=3, sigma=0.25, amplitude=1, normalize=False, width=None,
19
+ height=None, sigma_horz=None, sigma_vert=None, mean_horz=0.5,
20
+ mean_vert=0.5):
21
+ # handle some defaults
22
+ if width is None:
23
+ width = size
24
+ if height is None:
25
+ height = size
26
+ if sigma_horz is None:
27
+ sigma_horz = sigma
28
+ if sigma_vert is None:
29
+ sigma_vert = sigma
30
+ center_x = mean_horz * width + 0.5
31
+ center_y = mean_vert * height + 0.5
32
+ gauss = np.empty((height, width), dtype=np.float32)
33
+ # generate kernel
34
+ for i in range(height):
35
+ for j in range(width):
36
+ gauss[i][j] = amplitude * math.exp(-(math.pow((j + 1 - center_x) / (
37
+ sigma_horz * width), 2) / 2.0 + math.pow((i + 1 - center_y) / (sigma_vert * height), 2) / 2.0))
38
+ if normalize:
39
+ gauss = gauss / np.sum(gauss)
40
+ return gauss
41
+
42
+ def draw_gaussian(image, point, sigma):
43
+ # Check if the gaussian is inside
44
+ ul = [np.floor(np.floor(point[0]) - 3 * sigma),
45
+ np.floor(np.floor(point[1]) - 3 * sigma)]
46
+ br = [np.floor(np.floor(point[0]) + 3 * sigma),
47
+ np.floor(np.floor(point[1]) + 3 * sigma)]
48
+ if (ul[0] > image.shape[1] or ul[1] >
49
+ image.shape[0] or br[0] < 1 or br[1] < 1):
50
+ return image
51
+ size = 6 * sigma + 1
52
+ g = _gaussian(size)
53
+ g_x = [int(max(1, -ul[0])), int(min(br[0], image.shape[1])) -
54
+ int(max(1, ul[0])) + int(max(1, -ul[0]))]
55
+ g_y = [int(max(1, -ul[1])), int(min(br[1], image.shape[0])) -
56
+ int(max(1, ul[1])) + int(max(1, -ul[1]))]
57
+ img_x = [int(max(1, ul[0])), int(min(br[0], image.shape[1]))]
58
+ img_y = [int(max(1, ul[1])), int(min(br[1], image.shape[0]))]
59
+ assert (g_x[0] > 0 and g_y[1] > 0)
60
+ correct = False
61
+ while not correct:
62
+ try:
63
+ image[img_y[0] - 1:img_y[1], img_x[0] - 1:img_x[1]
64
+ ] = image[img_y[0] - 1:img_y[1], img_x[0] - 1:img_x[1]] + g[g_y[0] - 1:g_y[1], g_x[0] - 1:g_x[1]]
65
+ correct = True
66
+ except:
67
+ print('img_x: {}, img_y: {}, g_x:{}, g_y:{}, point:{}, g_shape:{}, ul:{}, br:{}'.format(img_x, img_y, g_x, g_y, point, g.shape, ul, br))
68
+ ul = [np.floor(np.floor(point[0]) - 3 * sigma),
69
+ np.floor(np.floor(point[1]) - 3 * sigma)]
70
+ br = [np.floor(np.floor(point[0]) + 3 * sigma),
71
+ np.floor(np.floor(point[1]) + 3 * sigma)]
72
+ g_x = [int(max(1, -ul[0])), int(min(br[0], image.shape[1])) -
73
+ int(max(1, ul[0])) + int(max(1, -ul[0]))]
74
+ g_y = [int(max(1, -ul[1])), int(min(br[1], image.shape[0])) -
75
+ int(max(1, ul[1])) + int(max(1, -ul[1]))]
76
+ img_x = [int(max(1, ul[0])), int(min(br[0], image.shape[1]))]
77
+ img_y = [int(max(1, ul[1])), int(min(br[1], image.shape[0]))]
78
+ pass
79
+ image[image > 1] = 1
80
+ return image
81
+
82
+ def transform(point, center, scale, resolution, rotation=0, invert=False):
83
+ _pt = np.ones(3)
84
+ _pt[0] = point[0]
85
+ _pt[1] = point[1]
86
+
87
+ h = 200.0 * scale
88
+ t = np.eye(3)
89
+ t[0, 0] = resolution / h
90
+ t[1, 1] = resolution / h
91
+ t[0, 2] = resolution * (-center[0] / h + 0.5)
92
+ t[1, 2] = resolution * (-center[1] / h + 0.5)
93
+
94
+ if rotation != 0:
95
+ rotation = -rotation
96
+ r = np.eye(3)
97
+ ang = rotation * math.pi / 180.0
98
+ s = math.sin(ang)
99
+ c = math.cos(ang)
100
+ r[0][0] = c
101
+ r[0][1] = -s
102
+ r[1][0] = s
103
+ r[1][1] = c
104
+
105
+ t_ = np.eye(3)
106
+ t_[0][2] = -resolution / 2.0
107
+ t_[1][2] = -resolution / 2.0
108
+ t_inv = torch.eye(3)
109
+ t_inv[0][2] = resolution / 2.0
110
+ t_inv[1][2] = resolution / 2.0
111
+ t = reduce(np.matmul, [t_inv, r, t_, t])
112
+
113
+ if invert:
114
+ t = np.linalg.inv(t)
115
+ new_point = (np.matmul(t, _pt))[0:2]
116
+
117
+ return new_point.astype(int)
118
+
119
+ def cv_crop(image, landmarks, center, scale, resolution=256, center_shift=0):
120
+ new_image = cv2.copyMakeBorder(image, center_shift,
121
+ center_shift,
122
+ center_shift,
123
+ center_shift,
124
+ cv2.BORDER_CONSTANT, value=[0,0,0])
125
+ new_landmarks = landmarks.copy()
126
+ if center_shift != 0:
127
+ center[0] += center_shift
128
+ center[1] += center_shift
129
+ new_landmarks = new_landmarks + center_shift
130
+ length = 200 * scale
131
+ top = int(center[1] - length // 2)
132
+ bottom = int(center[1] + length // 2)
133
+ left = int(center[0] - length // 2)
134
+ right = int(center[0] + length // 2)
135
+ y_pad = abs(min(top, new_image.shape[0] - bottom, 0))
136
+ x_pad = abs(min(left, new_image.shape[1] - right, 0))
137
+ top, bottom, left, right = top + y_pad, bottom + y_pad, left + x_pad, right + x_pad
138
+ new_image = cv2.copyMakeBorder(new_image, y_pad,
139
+ y_pad,
140
+ x_pad,
141
+ x_pad,
142
+ cv2.BORDER_CONSTANT, value=[0,0,0])
143
+ new_image = new_image[top:bottom, left:right]
144
+ new_image = cv2.resize(new_image, dsize=(int(resolution), int(resolution)),
145
+ interpolation=cv2.INTER_LINEAR)
146
+ new_landmarks[:, 0] = (new_landmarks[:, 0] + x_pad - left) * resolution / length
147
+ new_landmarks[:, 1] = (new_landmarks[:, 1] + y_pad - top) * resolution / length
148
+ return new_image, new_landmarks
149
+
150
+ def cv_rotate(image, landmarks, heatmap, rot, scale, resolution=256):
151
+ img_mat = cv2.getRotationMatrix2D((resolution//2, resolution//2), rot, scale)
152
+ ones = np.ones(shape=(landmarks.shape[0], 1))
153
+ stacked_landmarks = np.hstack([landmarks, ones])
154
+ new_landmarks = img_mat.dot(stacked_landmarks.T).T
155
+ if np.max(new_landmarks) > 255 or np.min(new_landmarks) < 0:
156
+ return image, landmarks, heatmap
157
+ else:
158
+ new_image = cv2.warpAffine(image, img_mat, (resolution, resolution))
159
+ if heatmap is not None:
160
+ new_heatmap = np.zeros((heatmap.shape[0], 64, 64))
161
+ for i in range(heatmap.shape[0]):
162
+ if new_landmarks[i][0] > 0:
163
+ new_heatmap[i] = draw_gaussian(new_heatmap[i],
164
+ new_landmarks[i]/4.0+1, 1)
165
+ return new_image, new_landmarks, new_heatmap
166
+
167
+ def show_landmarks(image, heatmap, gt_landmarks, gt_heatmap):
168
+ """Show image with pred_landmarks"""
169
+ pred_landmarks = []
170
+ pred_landmarks, _ = get_preds_fromhm(torch.from_numpy(heatmap).unsqueeze(0))
171
+ pred_landmarks = pred_landmarks.squeeze()*4
172
+
173
+ # pred_landmarks2 = get_preds_fromhm2(heatmap)
174
+ heatmap = np.max(gt_heatmap, axis=0)
175
+ heatmap = heatmap / np.max(heatmap)
176
+ # image = ski_transform.resize(image, (64, 64))*255
177
+ image = image.astype(np.uint8)
178
+ heatmap = np.max(gt_heatmap, axis=0)
179
+ heatmap = ski_transform.resize(heatmap, (image.shape[0], image.shape[1]))
180
+ heatmap *= 255
181
+ heatmap = heatmap.astype(np.uint8)
182
+ heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)
183
+ plt.imshow(image)
184
+ plt.scatter(gt_landmarks[:, 0], gt_landmarks[:, 1], s=0.5, marker='.', c='g')
185
+ plt.scatter(pred_landmarks[:, 0], pred_landmarks[:, 1], s=0.5, marker='.', c='r')
186
+ plt.pause(0.001) # pause a bit so that plots are updated
187
+
188
+ def fan_NME(pred_heatmaps, gt_landmarks, num_landmarks=68):
189
+ '''
190
+ Calculate total NME for a batch of data
191
+
192
+ Args:
193
+ pred_heatmaps: torch tensor of size [batch, points, height, width]
194
+ gt_landmarks: torch tesnsor of size [batch, points, x, y]
195
+
196
+ Returns:
197
+ nme: sum of nme for this batch
198
+ '''
199
+ nme = 0
200
+ pred_landmarks, _ = get_preds_fromhm(pred_heatmaps)
201
+ pred_landmarks = pred_landmarks.numpy()
202
+ gt_landmarks = gt_landmarks.numpy()
203
+ for i in range(pred_landmarks.shape[0]):
204
+ pred_landmark = pred_landmarks[i] * 4.0
205
+ gt_landmark = gt_landmarks[i]
206
+
207
+ if num_landmarks == 68:
208
+ left_eye = np.average(gt_landmark[36:42], axis=0)
209
+ right_eye = np.average(gt_landmark[42:48], axis=0)
210
+ norm_factor = np.linalg.norm(left_eye - right_eye)
211
+ # norm_factor = np.linalg.norm(gt_landmark[36]- gt_landmark[45])
212
+ elif num_landmarks == 98:
213
+ norm_factor = np.linalg.norm(gt_landmark[60]- gt_landmark[72])
214
+ elif num_landmarks == 19:
215
+ left, top = gt_landmark[-2, :]
216
+ right, bottom = gt_landmark[-1, :]
217
+ norm_factor = math.sqrt(abs(right - left)*abs(top-bottom))
218
+ gt_landmark = gt_landmark[:-2, :]
219
+ elif num_landmarks == 29:
220
+ # norm_factor = np.linalg.norm(gt_landmark[8]- gt_landmark[9])
221
+ norm_factor = np.linalg.norm(gt_landmark[16]- gt_landmark[17])
222
+ nme += (np.sum(np.linalg.norm(pred_landmark - gt_landmark, axis=1)) / pred_landmark.shape[0]) / norm_factor
223
+ return nme
224
+
225
+ def fan_NME_hm(pred_heatmaps, gt_heatmaps, num_landmarks=68):
226
+ '''
227
+ Calculate total NME for a batch of data
228
+
229
+ Args:
230
+ pred_heatmaps: torch tensor of size [batch, points, height, width]
231
+ gt_landmarks: torch tesnsor of size [batch, points, x, y]
232
+
233
+ Returns:
234
+ nme: sum of nme for this batch
235
+ '''
236
+ nme = 0
237
+ pred_landmarks, _ = get_index_fromhm(pred_heatmaps)
238
+ pred_landmarks = pred_landmarks.numpy()
239
+ gt_landmarks = gt_landmarks.numpy()
240
+ for i in range(pred_landmarks.shape[0]):
241
+ pred_landmark = pred_landmarks[i] * 4.0
242
+ gt_landmark = gt_landmarks[i]
243
+ if num_landmarks == 68:
244
+ left_eye = np.average(gt_landmark[36:42], axis=0)
245
+ right_eye = np.average(gt_landmark[42:48], axis=0)
246
+ norm_factor = np.linalg.norm(left_eye - right_eye)
247
+ else:
248
+ norm_factor = np.linalg.norm(gt_landmark[60]- gt_landmark[72])
249
+ nme += (np.sum(np.linalg.norm(pred_landmark - gt_landmark, axis=1)) / pred_landmark.shape[0]) / norm_factor
250
+ return nme
251
+
252
+ def power_transform(img, power):
253
+ img = np.array(img)
254
+ img_new = np.power((img/255.0), power) * 255.0
255
+ img_new = img_new.astype(np.uint8)
256
+ img_new = Image.fromarray(img_new)
257
+ return img_new
258
+
259
+ def get_preds_fromhm(hm, center=None, scale=None, rot=None):
260
+ max, idx = torch.max(
261
+ hm.view(hm.size(0), hm.size(1), hm.size(2) * hm.size(3)), 2)
262
+ idx += 1
263
+ preds = idx.view(idx.size(0), idx.size(1), 1).repeat(1, 1, 2).float()
264
+ preds[..., 0].apply_(lambda x: (x - 1) % hm.size(3) + 1)
265
+ preds[..., 1].add_(-1).div_(hm.size(2)).floor_().add_(1)
266
+
267
+
268
+ for i in range(preds.size(0)):
269
+ for j in range(preds.size(1)):
270
+ hm_ = hm[i, j, :]
271
+ pX, pY = int(preds[i, j, 0]) - 1, int(preds[i, j, 1]) - 1
272
+ if pX > 0 and pX < 63 and pY > 0 and pY < 63:
273
+ diff = torch.FloatTensor(
274
+ [hm_[pY, pX + 1] - hm_[pY, pX - 1],
275
+ hm_[pY + 1, pX] - hm_[pY - 1, pX]])
276
+ preds[i, j].add_(diff.sign_().mul_(.25))
277
+
278
+ preds.add_(-0.5)
279
+
280
+ preds_orig = torch.zeros(preds.size())
281
+ if center is not None and scale is not None:
282
+ for i in range(hm.size(0)):
283
+ for j in range(hm.size(1)):
284
+ preds_orig[i, j] = transform(
285
+ preds[i, j], center, scale, hm.size(2), rot, True)
286
+
287
+ return preds, preds_orig
288
+
289
+ def get_index_fromhm(hm):
290
+ max, idx = torch.max(
291
+ hm.view(hm.size(0), hm.size(1), hm.size(2) * hm.size(3)), 2)
292
+ preds = idx.view(idx.size(0), idx.size(1), 1).repeat(1, 1, 2).float()
293
+ preds[..., 0].remainder_(hm.size(3))
294
+ preds[..., 1].div_(hm.size(2)).floor_()
295
+
296
+ for i in range(preds.size(0)):
297
+ for j in range(preds.size(1)):
298
+ hm_ = hm[i, j, :]
299
+ pX, pY = int(preds[i, j, 0]), int(preds[i, j, 1])
300
+ if pX > 0 and pX < 63 and pY > 0 and pY < 63:
301
+ diff = torch.FloatTensor(
302
+ [hm_[pY, pX + 1] - hm_[pY, pX - 1],
303
+ hm_[pY + 1, pX] - hm_[pY - 1, pX]])
304
+ preds[i, j].add_(diff.sign_().mul_(.25))
305
+
306
+ return preds
307
+
308
+ def shuffle_lr(parts, num_landmarks=68, pairs=None):
309
+ if num_landmarks == 68:
310
+ if pairs is None:
311
+ pairs = [[0, 16], [1, 15], [2, 14], [3, 13], [4, 12], [5, 11], [6, 10],
312
+ [7, 9], [17, 26], [18, 25], [19, 24], [20, 23], [21, 22], [36, 45],
313
+ [37, 44], [38, 43], [39, 42], [41, 46], [40, 47], [31, 35], [32, 34],
314
+ [50, 52], [49, 53], [48, 54], [61, 63], [60, 64], [67, 65], [59, 55], [58, 56]]
315
+ elif num_landmarks == 98:
316
+ if pairs is None:
317
+ pairs = [[0, 32], [1,31], [2, 30], [3, 29], [4, 28], [5, 27], [6, 26], [7, 25], [8, 24], [9, 23], [10, 22], [11, 21], [12, 20], [13, 19], [14, 18], [15, 17], [33, 46], [34, 45], [35, 44], [36, 43], [37, 42], [38, 50], [39, 49], [40, 48], [41, 47], [60, 72], [61, 71], [62, 70], [63, 69], [64, 68], [65, 75], [66, 74], [67, 73], [96, 97], [55, 59], [56, 58], [76, 82], [77, 81], [78, 80], [88, 92], [89, 91], [95, 93], [87, 83], [86, 84]]
318
+ elif num_landmarks == 19:
319
+ if pairs is None:
320
+ pairs = [[0, 5], [1, 4], [2, 3], [6, 11], [7, 10], [8, 9], [12, 14], [15, 17]]
321
+ elif num_landmarks == 29:
322
+ if pairs is None:
323
+ pairs = [[0, 1], [4, 6], [5, 7], [2, 3], [8, 9], [12, 14], [16, 17], [13, 15], [10, 11], [18, 19], [22, 23]]
324
+ for matched_p in pairs:
325
+ idx1, idx2 = matched_p[0], matched_p[1]
326
+ tmp = np.copy(parts[idx1])
327
+ np.copyto(parts[idx1], parts[idx2])
328
+ np.copyto(parts[idx2], tmp)
329
+ return parts
330
+
331
+
332
+ def generate_weight_map(weight_map,heatmap):
333
+
334
+ k_size = 3
335
+ dilate = ndimage.grey_dilation(heatmap ,size=(k_size,k_size))
336
+ weight_map[np.where(dilate>0.2)] = 1
337
+ return weight_map
338
+
339
+ def fig2data(fig):
340
+ """
341
+ @brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it
342
+ @param fig a matplotlib figure
343
+ @return a numpy 3D array of RGBA values
344
+ """
345
+ # draw the renderer
346
+ fig.canvas.draw ( )
347
+
348
+ # Get the RGB buffer from the figure
349
+ w,h = fig.canvas.get_width_height()
350
+ buf = np.fromstring (fig.canvas.tostring_rgb(), dtype=np.uint8)
351
+ buf.shape = (w, h, 3)
352
+
353
+ # canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
354
+ buf = np.roll (buf, 3, axis=2)
355
+ return buf
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 [yyyy] [name of copyright owner]
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.
SberSwapInference.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
apex/.gitignore ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ apex.egg-info
2
+ dist
3
+ build
4
+ docs/build
5
+ *~
6
+ __pycache__
apex/.gitmodules ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ [submodule "apex/contrib/csrc/multihead_attn/cutlass"]
2
+ path = apex/contrib/csrc/multihead_attn/cutlass
3
+ url = https://github.com/NVIDIA/cutlass.git
4
+ branch = v1.2.0
5
+ [submodule "apex/contrib/csrc/cudnn-frontend"]
6
+ path = apex/contrib/csrc/cudnn-frontend
7
+ url = https://github.com/NVIDIA/cudnn-frontend.git
apex/.nojekyll ADDED
File without changes
apex/LICENSE ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ All rights reserved.
2
+
3
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
4
+
5
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
6
+
7
+ 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
8
+
9
+ 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
10
+
11
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
apex/README.md ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Introduction
2
+
3
+ This repository holds NVIDIA-maintained utilities to streamline
4
+ mixed precision and distributed training in Pytorch.
5
+ Some of the code here will be included in upstream Pytorch eventually.
6
+ The intention of Apex is to make up-to-date utilities available to
7
+ users as quickly as possible.
8
+
9
+ ## Full API Documentation: [https://nvidia.github.io/apex](https://nvidia.github.io/apex)
10
+
11
+ ## [GTC 2019](https://github.com/mcarilli/mixed_precision_references/tree/master/GTC_2019) and [Pytorch DevCon 2019](https://github.com/mcarilli/mixed_precision_references/tree/master/Pytorch_Devcon_2019) Slides
12
+
13
+ # Contents
14
+
15
+ ## 1. Amp: Automatic Mixed Precision
16
+
17
+ `apex.amp` is a tool to enable mixed precision training by changing only 3 lines of your script.
18
+ Users can easily experiment with different pure and mixed precision training modes by supplying
19
+ different flags to `amp.initialize`.
20
+
21
+ [Webinar introducing Amp](https://info.nvidia.com/webinar-mixed-precision-with-pytorch-reg-page.html)
22
+ (The flag `cast_batchnorm` has been renamed to `keep_batchnorm_fp32`).
23
+
24
+ [API Documentation](https://nvidia.github.io/apex/amp.html)
25
+
26
+ [Comprehensive Imagenet example](https://github.com/NVIDIA/apex/tree/master/examples/imagenet)
27
+
28
+ [DCGAN example coming soon...](https://github.com/NVIDIA/apex/tree/master/examples/dcgan)
29
+
30
+ [Moving to the new Amp API](https://nvidia.github.io/apex/amp.html#transition-guide-for-old-api-users) (for users of the deprecated "Amp" and "FP16_Optimizer" APIs)
31
+
32
+ ## 2. Distributed Training
33
+
34
+ `apex.parallel.DistributedDataParallel` is a module wrapper, similar to
35
+ `torch.nn.parallel.DistributedDataParallel`. It enables convenient multiprocess distributed training,
36
+ optimized for NVIDIA's NCCL communication library.
37
+
38
+ [API Documentation](https://nvidia.github.io/apex/parallel.html)
39
+
40
+ [Python Source](https://github.com/NVIDIA/apex/tree/master/apex/parallel)
41
+
42
+ [Example/Walkthrough](https://github.com/NVIDIA/apex/tree/master/examples/simple/distributed)
43
+
44
+ The [Imagenet example](https://github.com/NVIDIA/apex/tree/master/examples/imagenet)
45
+ shows use of `apex.parallel.DistributedDataParallel` along with `apex.amp`.
46
+
47
+ ### Synchronized Batch Normalization
48
+
49
+ `apex.parallel.SyncBatchNorm` extends `torch.nn.modules.batchnorm._BatchNorm` to
50
+ support synchronized BN.
51
+ It allreduces stats across processes during multiprocess (DistributedDataParallel) training.
52
+ Synchronous BN has been used in cases where only a small
53
+ local minibatch can fit on each GPU.
54
+ Allreduced stats increase the effective batch size for the BN layer to the
55
+ global batch size across all processes (which, technically, is the correct
56
+ formulation).
57
+ Synchronous BN has been observed to improve converged accuracy in some of our research models.
58
+
59
+ ### Checkpointing
60
+
61
+ To properly save and load your `amp` training, we introduce the `amp.state_dict()`, which contains all `loss_scalers` and their corresponding unskipped steps,
62
+ as well as `amp.load_state_dict()` to restore these attributes.
63
+
64
+ In order to get bitwise accuracy, we recommend the following workflow:
65
+ ```python
66
+ # Initialization
67
+ opt_level = 'O1'
68
+ model, optimizer = amp.initialize(model, optimizer, opt_level=opt_level)
69
+
70
+ # Train your model
71
+ ...
72
+ with amp.scale_loss(loss, optimizer) as scaled_loss:
73
+ scaled_loss.backward()
74
+ ...
75
+
76
+ # Save checkpoint
77
+ checkpoint = {
78
+ 'model': model.state_dict(),
79
+ 'optimizer': optimizer.state_dict(),
80
+ 'amp': amp.state_dict()
81
+ }
82
+ torch.save(checkpoint, 'amp_checkpoint.pt')
83
+ ...
84
+
85
+ # Restore
86
+ model = ...
87
+ optimizer = ...
88
+ checkpoint = torch.load('amp_checkpoint.pt')
89
+
90
+ model, optimizer = amp.initialize(model, optimizer, opt_level=opt_level)
91
+ model.load_state_dict(checkpoint['model'])
92
+ optimizer.load_state_dict(checkpoint['optimizer'])
93
+ amp.load_state_dict(checkpoint['amp'])
94
+
95
+ # Continue training
96
+ ...
97
+ ```
98
+
99
+ Note that we recommend restoring the model using the same `opt_level`. Also note that we recommend calling the `load_state_dict` methods after `amp.initialize`.
100
+
101
+ # Requirements
102
+
103
+ Python 3
104
+
105
+ CUDA 9 or newer
106
+
107
+ PyTorch 0.4 or newer. The CUDA and C++ extensions require pytorch 1.0 or newer.
108
+
109
+ We recommend the latest stable release, obtainable from
110
+ [https://pytorch.org/](https://pytorch.org/). We also test against the latest master branch, obtainable from [https://github.com/pytorch/pytorch](https://github.com/pytorch/pytorch).
111
+
112
+ It's often convenient to use Apex in Docker containers. Compatible options include:
113
+ * [NVIDIA Pytorch containers from NGC](https://ngc.nvidia.com/catalog/containers/nvidia%2Fpytorch), which come with Apex preinstalled. To use the latest Amp API, you may need to `pip uninstall apex` then reinstall Apex using the **Quick Start** commands below.
114
+ * [official Pytorch -devel Dockerfiles](https://hub.docker.com/r/pytorch/pytorch/tags), e.g. `docker pull pytorch/pytorch:nightly-devel-cuda10.0-cudnn7`, in which you can install Apex using the **Quick Start** commands.
115
+
116
+ See the [Docker example folder](https://github.com/NVIDIA/apex/tree/master/examples/docker) for details.
117
+
118
+ # Quick Start
119
+
120
+ ### Linux
121
+
122
+ For performance and full functionality, we recommend installing Apex with
123
+ CUDA and C++ extensions via
124
+ ```
125
+ git clone https://github.com/NVIDIA/apex
126
+ cd apex
127
+ pip install -v --disable-pip-version-check --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" ./
128
+ ```
129
+
130
+ Apex also supports a Python-only build (required with Pytorch 0.4) via
131
+ ```
132
+ pip install -v --disable-pip-version-check --no-cache-dir ./
133
+ ```
134
+ A Python-only build omits:
135
+ - Fused kernels required to use `apex.optimizers.FusedAdam`.
136
+ - Fused kernels required to use `apex.normalization.FusedLayerNorm`.
137
+ - Fused kernels that improve the performance and numerical stability of `apex.parallel.SyncBatchNorm`.
138
+ - Fused kernels that improve the performance of `apex.parallel.DistributedDataParallel` and `apex.amp`.
139
+ `DistributedDataParallel`, `amp`, and `SyncBatchNorm` will still be usable, but they may be slower.
140
+
141
+ Pyprof support has been moved to its own [dedicated repository](https://github.com/NVIDIA/PyProf).
142
+ The codebase is deprecated in Apex and will be removed soon.
143
+
144
+ ### Windows support
145
+ Windows support is experimental, and Linux is recommended. `pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" .` may work if you were able to build Pytorch from source
146
+ on your system. `pip install -v --no-cache-dir .` (without CUDA/C++ extensions) is more likely to work. If you installed Pytorch in a Conda environment, make sure to install Apex in that same environment.
apex/apex/RNN/README.md ADDED
@@ -0,0 +1 @@
 
 
1
+ Under construction...
apex/apex/RNN/RNNBackend.py ADDED
@@ -0,0 +1,365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torch.autograd import Variable
4
+
5
+ import torch.nn.functional as F
6
+
7
+ import math
8
+
9
+
10
+ def is_iterable(maybe_iterable):
11
+ return isinstance(maybe_iterable, list) or isinstance(maybe_iterable, tuple)
12
+
13
+
14
+ def flatten_list(tens_list):
15
+ """
16
+ flatten_list
17
+ """
18
+ if not is_iterable(tens_list):
19
+ return tens_list
20
+
21
+ return torch.cat(tens_list, dim=0).view(len(tens_list), *tens_list[0].size() )
22
+
23
+
24
+ #These modules always assumes batch_first
25
+ class bidirectionalRNN(nn.Module):
26
+ """
27
+ bidirectionalRNN
28
+ """
29
+ def __init__(self, inputRNN, num_layers=1, dropout = 0):
30
+ super(bidirectionalRNN, self).__init__()
31
+ self.dropout = dropout
32
+ self.fwd = stackedRNN(inputRNN, num_layers=num_layers, dropout = dropout)
33
+ self.bckwrd = stackedRNN(inputRNN.new_like(), num_layers=num_layers, dropout = dropout)
34
+ self.rnns = nn.ModuleList([self.fwd, self.bckwrd])
35
+
36
+ #collect hidden option will return all hidden/cell states from entire RNN
37
+ def forward(self, input, collect_hidden=False):
38
+ """
39
+ forward()
40
+ """
41
+ seq_len = input.size(0)
42
+ bsz = input.size(1)
43
+
44
+ fwd_out, fwd_hiddens = list(self.fwd(input, collect_hidden = collect_hidden))
45
+ bckwrd_out, bckwrd_hiddens = list(self.bckwrd(input, reverse=True, collect_hidden = collect_hidden))
46
+
47
+ output = torch.cat( [fwd_out, bckwrd_out], -1 )
48
+ hiddens = tuple( torch.cat(hidden, -1) for hidden in zip( fwd_hiddens, bckwrd_hiddens) )
49
+
50
+ return output, hiddens
51
+
52
+ def reset_parameters(self):
53
+ """
54
+ reset_parameters()
55
+ """
56
+ for rnn in self.rnns:
57
+ rnn.reset_parameters()
58
+
59
+ def init_hidden(self, bsz):
60
+ """
61
+ init_hidden()
62
+ """
63
+ for rnn in self.rnns:
64
+ rnn.init_hidden(bsz)
65
+
66
+ def detach_hidden(self):
67
+ """
68
+ detach_hidden()
69
+ """
70
+ for rnn in self.rnns:
71
+ rnn.detachHidden()
72
+
73
+ def reset_hidden(self, bsz):
74
+ """
75
+ reset_hidden()
76
+ """
77
+ for rnn in self.rnns:
78
+ rnn.reset_hidden(bsz)
79
+
80
+ def init_inference(self, bsz):
81
+ """
82
+ init_inference()
83
+ """
84
+ for rnn in self.rnns:
85
+ rnn.init_inference(bsz)
86
+
87
+
88
+ #assumes hidden_state[0] of inputRNN is output hidden state
89
+ #constructor either takes an RNNCell or list of RNN layers
90
+ class stackedRNN(nn.Module):
91
+ """
92
+ stackedRNN
93
+ """
94
+ def __init__(self, inputRNN, num_layers=1, dropout=0):
95
+ super(stackedRNN, self).__init__()
96
+
97
+ self.dropout = dropout
98
+
99
+ if isinstance(inputRNN, RNNCell):
100
+ self.rnns = [inputRNN]
101
+ for i in range(num_layers-1):
102
+ self.rnns.append(inputRNN.new_like(inputRNN.output_size))
103
+ elif isinstance(inputRNN, list):
104
+ assert len(inputRNN) == num_layers, "RNN list length must be equal to num_layers"
105
+ self.rnns=inputRNN
106
+ else:
107
+ raise RuntimeError()
108
+
109
+ self.nLayers = len(self.rnns)
110
+
111
+ self.rnns = nn.ModuleList(self.rnns)
112
+
113
+
114
+ '''
115
+ Returns output as hidden_state[0] Tensor([sequence steps][batch size][features])
116
+ If collect hidden will also return Tuple(
117
+ [n_hidden_states][sequence steps] Tensor([layer][batch size][features])
118
+ )
119
+ If not collect hidden will also return Tuple(
120
+ [n_hidden_states] Tensor([layer][batch size][features])
121
+ '''
122
+ def forward(self, input, collect_hidden=False, reverse=False):
123
+ """
124
+ forward()
125
+ """
126
+ seq_len = input.size(0)
127
+ bsz = input.size(1)
128
+ inp_iter = reversed(range(seq_len)) if reverse else range(seq_len)
129
+
130
+ hidden_states = [[] for i in range(self.nLayers)]
131
+ outputs = []
132
+
133
+ for seq in inp_iter:
134
+ for layer in range(self.nLayers):
135
+
136
+ if layer == 0:
137
+ prev_out = input[seq]
138
+
139
+ outs = self.rnns[layer](prev_out)
140
+
141
+ if collect_hidden:
142
+ hidden_states[layer].append(outs)
143
+ elif seq == seq_len-1:
144
+ hidden_states[layer].append(outs)
145
+
146
+ prev_out = outs[0]
147
+
148
+ outputs.append(prev_out)
149
+
150
+ if reverse:
151
+ outputs = list(reversed(outputs))
152
+ '''
153
+ At this point outputs is in format:
154
+ list( [seq_length] x Tensor([bsz][features]) )
155
+ need to convert it to:
156
+ list( Tensor([seq_length][bsz][features]) )
157
+ '''
158
+ output = flatten_list(outputs)
159
+
160
+ '''
161
+ hidden_states at this point is in format:
162
+ list( [layer][seq_length][hidden_states] x Tensor([bsz][features]) )
163
+ need to convert it to:
164
+ For not collect hidden:
165
+ list( [hidden_states] x Tensor([layer][bsz][features]) )
166
+ For collect hidden:
167
+ list( [hidden_states][seq_length] x Tensor([layer][bsz][features]) )
168
+ '''
169
+ if not collect_hidden:
170
+ seq_len = 1
171
+ n_hid = self.rnns[0].n_hidden_states
172
+ new_hidden = [ [ [ None for k in range(self.nLayers)] for j in range(seq_len) ] for i in range(n_hid) ]
173
+
174
+
175
+ for i in range(n_hid):
176
+ for j in range(seq_len):
177
+ for k in range(self.nLayers):
178
+ new_hidden[i][j][k] = hidden_states[k][j][i]
179
+
180
+ hidden_states = new_hidden
181
+ #Now in format list( [hidden_states][seq_length][layer] x Tensor([bsz][features]) )
182
+ #Reverse seq_length if reverse
183
+ if reverse:
184
+ hidden_states = list( list(reversed(list(entry))) for entry in hidden_states)
185
+
186
+ #flatten layer dimension into tensor
187
+ hiddens = list( list(
188
+ flatten_list(seq) for seq in hidden )
189
+ for hidden in hidden_states )
190
+
191
+ #Now in format list( [hidden_states][seq_length] x Tensor([layer][bsz][features]) )
192
+ #Remove seq_length dimension if not collect_hidden
193
+ if not collect_hidden:
194
+ hidden_states = list( entry[0] for entry in hidden_states)
195
+ return output, hidden_states
196
+
197
+ def reset_parameters(self):
198
+ """
199
+ reset_parameters()
200
+ """
201
+ for rnn in self.rnns:
202
+ rnn.reset_parameters()
203
+
204
+ def init_hidden(self, bsz):
205
+ """
206
+ init_hidden()
207
+ """
208
+ for rnn in self.rnns:
209
+ rnn.init_hidden(bsz)
210
+
211
+ def detach_hidden(self):
212
+ """
213
+ detach_hidden()
214
+ """
215
+ for rnn in self.rnns:
216
+ rnn.detach_hidden()
217
+
218
+ def reset_hidden(self, bsz):
219
+ """
220
+ reset_hidden()
221
+ """
222
+ for rnn in self.rnns:
223
+ rnn.reset_hidden(bsz)
224
+
225
+ def init_inference(self, bsz):
226
+ """
227
+ init_inference()
228
+ """
229
+ for rnn in self.rnns:
230
+ rnn.init_inference(bsz)
231
+
232
+ class RNNCell(nn.Module):
233
+ """
234
+ RNNCell
235
+ gate_multiplier is related to the architecture you're working with
236
+ For LSTM-like it will be 4 and GRU-like will be 3.
237
+ Always assumes input is NOT batch_first.
238
+ Output size that's not hidden size will use output projection
239
+ Hidden_states is number of hidden states that are needed for cell
240
+ if one will go directly to cell as tensor, if more will go as list
241
+ """
242
+ def __init__(self, gate_multiplier, input_size, hidden_size, cell, n_hidden_states = 2, bias = False, output_size = None):
243
+ super(RNNCell, self).__init__()
244
+
245
+ self.gate_multiplier = gate_multiplier
246
+ self.input_size = input_size
247
+ self.hidden_size = hidden_size
248
+ self.cell = cell
249
+ self.bias = bias
250
+ self.output_size = output_size
251
+ if output_size is None:
252
+ self.output_size = hidden_size
253
+
254
+ self.gate_size = gate_multiplier * self.hidden_size
255
+ self.n_hidden_states = n_hidden_states
256
+
257
+ self.w_ih = nn.Parameter(torch.Tensor(self.gate_size, self.input_size))
258
+ self.w_hh = nn.Parameter(torch.Tensor(self.gate_size, self.output_size))
259
+
260
+ #Check if there's recurrent projection
261
+ if(self.output_size != self.hidden_size):
262
+ self.w_ho = nn.Parameter(torch.Tensor(self.output_size, self.hidden_size))
263
+
264
+ self.b_ih = self.b_hh = None
265
+ if self.bias:
266
+ self.b_ih = nn.Parameter(torch.Tensor(self.gate_size))
267
+ self.b_hh = nn.Parameter(torch.Tensor(self.gate_size))
268
+
269
+ #hidden states for forward
270
+ self.hidden = [ None for states in range(self.n_hidden_states)]
271
+
272
+ self.reset_parameters()
273
+
274
+ def new_like(self, new_input_size=None):
275
+ """
276
+ new_like()
277
+ """
278
+ if new_input_size is None:
279
+ new_input_size = self.input_size
280
+
281
+ return type(self)(self.gate_multiplier,
282
+ new_input_size,
283
+ self.hidden_size,
284
+ self.cell,
285
+ self.n_hidden_states,
286
+ self.bias,
287
+ self.output_size)
288
+
289
+
290
+ #Use xavier where we can (weights), otherwise use uniform (bias)
291
+ def reset_parameters(self, gain=1):
292
+ """
293
+ reset_parameters()
294
+ """
295
+ stdev = 1.0 / math.sqrt(self.hidden_size)
296
+ for param in self.parameters():
297
+ param.data.uniform_(-stdev, stdev)
298
+ '''
299
+ Xavier reset:
300
+ def reset_parameters(self, gain=1):
301
+ stdv = 1.0 / math.sqrt(self.gate_size)
302
+
303
+ for param in self.parameters():
304
+ if (param.dim() > 1):
305
+ torch.nn.init.xavier_normal(param, gain)
306
+ else:
307
+ param.data.uniform_(-stdv, stdv)
308
+ '''
309
+ def init_hidden(self, bsz):
310
+ """
311
+ init_hidden()
312
+ """
313
+ for param in self.parameters():
314
+ if param is not None:
315
+ a_param = param
316
+ break
317
+
318
+ for i, _ in enumerate(self.hidden):
319
+ if(self.hidden[i] is None or self.hidden[i].data.size()[0] != bsz):
320
+
321
+ if i==0:
322
+ hidden_size = self.output_size
323
+ else:
324
+ hidden_size = self.hidden_size
325
+
326
+ tens = a_param.data.new(bsz, hidden_size).zero_()
327
+ self.hidden[i] = Variable(tens, requires_grad=False)
328
+
329
+
330
+ def reset_hidden(self, bsz):
331
+ """
332
+ reset_hidden()
333
+ """
334
+ for i, _ in enumerate(self.hidden):
335
+ self.hidden[i] = None
336
+ self.init_hidden(bsz)
337
+
338
+ def detach_hidden(self):
339
+ """
340
+ detach_hidden()
341
+ """
342
+ for i, _ in enumerate(self.hidden):
343
+ if self.hidden[i] is None:
344
+ raise RuntimeError("Must initialize hidden state before you can detach it")
345
+ for i, _ in enumerate(self.hidden):
346
+ self.hidden[i] = self.hidden[i].detach()
347
+
348
+ def forward(self, input):
349
+ """
350
+ forward()
351
+ if not inited or bsz has changed this will create hidden states
352
+ """
353
+ self.init_hidden(input.size()[0])
354
+
355
+ hidden_state = self.hidden[0] if self.n_hidden_states == 1 else self.hidden
356
+ self.hidden = self.cell(input, hidden_state, self.w_ih, self.w_hh, b_ih=self.b_ih, b_hh=self.b_hh)
357
+ if(self.n_hidden_states > 1):
358
+ self.hidden = list(self.hidden)
359
+ else:
360
+ self.hidden=[self.hidden]
361
+
362
+ if self.output_size != self.hidden_size:
363
+ self.hidden[0] = F.linear(self.hidden[0], self.w_ho)
364
+
365
+ return tuple(self.hidden)
apex/apex/RNN/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .models import LSTM, GRU, ReLU, Tanh, mLSTM
2
+
3
+ __all__ = ['models']
apex/apex/RNN/cells.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+ from .RNNBackend import RNNCell
6
+
7
+ from torch.nn._functions.thnn import rnnFusedPointwise as fusedBackend
8
+
9
+ import math
10
+
11
+
12
+ class mLSTMRNNCell(RNNCell):
13
+ """
14
+ mLSTMRNNCell
15
+ """
16
+
17
+ def __init__(self, input_size, hidden_size, bias = False, output_size = None):
18
+ gate_multiplier = 4
19
+ super(mLSTMRNNCell, self).__init__(gate_multiplier, input_size, hidden_size, mLSTMCell, n_hidden_states = 2, bias = bias, output_size = output_size)
20
+
21
+ self.w_mih = nn.Parameter(torch.Tensor(self.output_size, self.input_size))
22
+ self.w_mhh = nn.Parameter(torch.Tensor(self.output_size, self.output_size))
23
+
24
+ self.reset_parameters()
25
+
26
+ def forward(self, input):
27
+ """
28
+ mLSTMRNNCell.forward()
29
+ """
30
+ #if not inited or bsz has changed this will create hidden states
31
+ self.init_hidden(input.size()[0])
32
+
33
+ hidden_state = self.hidden[0] if self.n_hidden_states == 1 else self.hidden
34
+
35
+ self.hidden = list(
36
+ self.cell(input, hidden_state, self.w_ih, self.w_hh, self.w_mih, self.w_mhh,
37
+ b_ih=self.b_ih, b_hh=self.b_hh)
38
+ )
39
+
40
+ if self.output_size != self.hidden_size:
41
+ self.hidden[0] = F.linear(self.hidden[0], self.w_ho)
42
+ return tuple(self.hidden)
43
+
44
+
45
+ def new_like(self, new_input_size=None):
46
+ if new_input_size is None:
47
+ new_input_size = self.input_size
48
+
49
+ return type(self)(
50
+ new_input_size,
51
+ self.hidden_size,
52
+ self.bias,
53
+ self.output_size)
54
+
55
+ def mLSTMCell(input, hidden, w_ih, w_hh, w_mih, w_mhh, b_ih=None, b_hh=None):
56
+ """
57
+ mLSTMCell
58
+ """
59
+
60
+ if input.is_cuda:
61
+ igates = F.linear(input, w_ih)
62
+ m = F.linear(input, w_mih) * F.linear(hidden[0], w_mhh)
63
+ hgates = F.linear(m, w_hh)
64
+
65
+ state = fusedBackend.LSTMFused.apply
66
+ return state(igates, hgates, hidden[1], b_ih, b_hh)
67
+
68
+ hx, cx = hidden
69
+
70
+ m = F.linear(input, w_mih) * F.linear(hidden[0], w_mhh)
71
+ gates = F.linear(input, w_ih, b_ih) + F.linear(m, w_hh, b_hh)
72
+
73
+ ingate, forgetgate, cellgate, outgate = gates.chunk(4, 1)
74
+
75
+ ingate = F.sigmoid(ingate)
76
+ forgetgate = F.sigmoid(forgetgate)
77
+ cellgate = F.tanh(cellgate)
78
+ outgate = F.sigmoid(outgate)
79
+
80
+ cy = (forgetgate * cx) + (ingate * cellgate)
81
+ hy = outgate * F.tanh(cy)
82
+
83
+ return hy, cy
84
+
apex/apex/RNN/models.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ from torch.nn._functions.rnn import LSTMCell, RNNReLUCell, RNNTanhCell, GRUCell
4
+
5
+ from .RNNBackend import bidirectionalRNN, stackedRNN, RNNCell
6
+ from .cells import mLSTMRNNCell, mLSTMCell
7
+
8
+ def toRNNBackend(inputRNN, num_layers, bidirectional=False, dropout = 0):
9
+ """
10
+ :class:`toRNNBackend`
11
+ """
12
+
13
+ if bidirectional:
14
+ return bidirectionalRNN(inputRNN, num_layers, dropout = dropout)
15
+ else:
16
+ return stackedRNN(inputRNN, num_layers, dropout = dropout)
17
+
18
+
19
+ def LSTM(input_size, hidden_size, num_layers, bias=True, batch_first=False, dropout=0, bidirectional=False, output_size = None):
20
+ """
21
+ :class:`LSTM`
22
+ """
23
+ inputRNN = RNNCell(4, input_size, hidden_size, LSTMCell, 2, bias, output_size)
24
+ return toRNNBackend(inputRNN, num_layers, bidirectional, dropout=dropout)
25
+
26
+ def GRU(input_size, hidden_size, num_layers, bias=True, batch_first=False, dropout=0, bidirectional=False, output_size = None):
27
+ """
28
+ :class:`GRU`
29
+ """
30
+ inputRNN = RNNCell(3, input_size, hidden_size, GRUCell, 1, bias, output_size)
31
+ return toRNNBackend(inputRNN, num_layers, bidirectional, dropout=dropout)
32
+
33
+ def ReLU(input_size, hidden_size, num_layers, bias=True, batch_first=False, dropout=0, bidirectional=False, output_size = None):
34
+ """
35
+ :class:`ReLU`
36
+ """
37
+ inputRNN = RNNCell(1, input_size, hidden_size, RNNReLUCell, 1, bias, output_size)
38
+ return toRNNBackend(inputRNN, num_layers, bidirectional, dropout=dropout)
39
+
40
+ def Tanh(input_size, hidden_size, num_layers, bias=True, batch_first=False, dropout=0, bidirectional=False, output_size = None):
41
+ """
42
+ :class:`Tanh`
43
+ """
44
+ inputRNN = RNNCell(1, input_size, hidden_size, RNNTanhCell, 1, bias, output_size)
45
+ return toRNNBackend(inputRNN, num_layers, bidirectional, dropout=dropout)
46
+
47
+ def mLSTM(input_size, hidden_size, num_layers, bias=True, batch_first=False, dropout=0, bidirectional=False, output_size = None):
48
+ """
49
+ :class:`mLSTM`
50
+ """
51
+ inputRNN = mLSTMRNNCell(input_size, hidden_size, bias=bias, output_size=output_size)
52
+ return toRNNBackend(inputRNN, num_layers, bidirectional, dropout=dropout)
53
+
54
+
apex/apex/__init__.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # May help avoid undefined symbol errors https://pytorch.org/cppdocs/notes/faq.html#undefined-symbol-errors-from-pytorch-aten
2
+ import torch
3
+ import warnings
4
+
5
+ if torch.distributed.is_available():
6
+ from . import parallel
7
+
8
+ from . import amp
9
+ from . import fp16_utils
10
+
11
+ # For optimizers and normalization there is no Python fallback.
12
+ # Absence of cuda backend is a hard error.
13
+ # I would like the errors from importing fused_adam_cuda or fused_layer_norm_cuda
14
+ # to be triggered lazily, because if someone has installed with --cpp_ext and --cuda_ext
15
+ # so they expect those backends to be available, but for some reason they actually aren't
16
+ # available (for example because they built improperly in a way that isn't revealed until
17
+ # load time) the error message is timely and visible.
18
+ from . import optimizers
19
+ from . import normalization
20
+ from . import pyprof
apex/apex/amp/README.md ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # amp: Automatic Mixed Precision
2
+
3
+ ## Annotating User Functions
4
+
5
+ Nearly all PyTorch user code needs nothing more than the two steps
6
+ above to use amp. After all, custom layers are built out of simpler
7
+ PyTorch components, and amp already can see those.
8
+
9
+ However, any custom C++ or CUDA code is outside of amp's (default)
10
+ view of things. For example, suppose I implemented a new recurrent
11
+ cell called a "forgetful recurrent unit" that calls directly into a
12
+ CUDA backend:
13
+
14
+ ```python
15
+ from backend import FRUBackend
16
+
17
+ def fru(input, hidden, weight, bias):
18
+ # call to CUDA code
19
+ FRUBackend(input, hidden, weight, bias)
20
+ ```
21
+
22
+ In this case, it is possible to get a runtime type mismatch. For
23
+ example, you might have `input` in fp16, and `weight` in fp32, and amp
24
+ doesn't have the visibility to insert an appropriate cast.
25
+
26
+ amp exposes two ways to handle "invisible" backend code: function
27
+ annotations and explicit registration.
28
+
29
+ #### Function annotation
30
+
31
+ The first way to handle backend code is a set of function annotations:
32
+
33
+ - `@amp.half_function`
34
+ - `@amp.float_function`
35
+ - `@amp.promote_function`
36
+
37
+ These correspond to:
38
+
39
+ - Cast all arguments to fp16
40
+ - Cast all argumnets fo fp32
41
+ - If there are any type mismatches, cast everything to the widest type
42
+
43
+ In our example, we believe that the FRU unit is fp16-safe and will get
44
+ performance gains from casting its arguments to fp16, so we write:
45
+
46
+ ```python
47
+ @amp.half_function
48
+ def fru(input, hidden, weight, bias):
49
+ #...
50
+ ```
51
+
52
+ #### Explicit registration
53
+
54
+ The other way to handle backend code is with explicit function
55
+ registration:
56
+
57
+ - `amp.register_half_function(module, function_name)`
58
+ - `amp.register_float_function(module, function_name)`
59
+ - `amp.register_promote_function(module, function_name)`
60
+
61
+ When using this API, `module` is the containing class or module for
62
+ the function, and `function_name` is the _string_ name of the
63
+ function. Note that the function must be registered before the call to
64
+ `amp.initalize()`.
65
+
66
+ For our FRU unit, we can register the backend function directly:
67
+
68
+ ```python
69
+ import backend
70
+
71
+ amp.register_half_function(backend, 'FRUBackend')
72
+ ```
apex/apex/amp/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from .amp import init, half_function, float_function, promote_function,\
2
+ register_half_function, register_float_function, register_promote_function
3
+ from .handle import scale_loss, disable_casts
4
+ from .frontend import initialize, state_dict, load_state_dict
5
+ from ._amp_state import master_params, _amp_state
apex/apex/amp/__version__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ VERSION = (0, 1, 0)
2
+ __version__ = '.'.join(map(str, VERSION))
apex/apex/amp/_amp_state.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This is a "header object" that allows different amp modules to communicate.
2
+ # I'm a C++ guy, not a python guy. I decided this approach because it seemed most C++-like.
3
+ # But apparently it's ok:
4
+ # http://effbot.org/pyfaq/how-do-i-share-global-variables-across-modules.htm
5
+ import os
6
+ import torch
7
+
8
+ TORCH_MAJOR = int(torch.__version__.split('.')[0])
9
+ TORCH_MINOR = int(torch.__version__.split('.')[1])
10
+
11
+
12
+ if TORCH_MAJOR == 1 and TORCH_MINOR < 8:
13
+ from torch._six import container_abcs
14
+ else:
15
+ import collections.abc as container_abcs
16
+
17
+
18
+ class AmpState(object):
19
+ def __init__(self):
20
+ self.hard_override=False
21
+ self.allow_incoming_model_not_fp32 = False
22
+ self.verbosity=1
23
+
24
+
25
+ # Attribute stash. Could also just stash things as global module attributes.
26
+ _amp_state = AmpState()
27
+
28
+
29
+ def warn_or_err(msg):
30
+ if _amp_state.hard_override:
31
+ print("Warning: " + msg)
32
+ else:
33
+ raise RuntimeError(msg)
34
+ # I'm not sure if allowing hard_override is a good idea.
35
+ # + " If you're sure you know what you're doing, supply " +
36
+ # "hard_override=True to amp.initialize.")
37
+
38
+
39
+ def maybe_print(msg, rank0=False):
40
+ distributed = torch.distributed.is_available() and \
41
+ torch.distributed.is_initialized() and \
42
+ torch.distributed.get_world_size() > 1
43
+ if _amp_state.verbosity > 0:
44
+ if rank0:
45
+ if distributed:
46
+ if torch.distributed.get_rank() == 0:
47
+ print(msg)
48
+ else:
49
+ print(msg)
50
+ else:
51
+ print(msg)
52
+
53
+
54
+ # def iter_params(param_groups):
55
+ # for group in param_groups:
56
+ # for p in group['params']:
57
+ # yield p
58
+
59
+
60
+ def master_params(optimizer):
61
+ """
62
+ Generator expression that iterates over the params owned by ``optimizer``.
63
+
64
+ Args:
65
+ optimizer: An optimizer previously returned from ``amp.initialize``.
66
+ """
67
+ for group in optimizer.param_groups:
68
+ for p in group['params']:
69
+ yield p
apex/apex/amp/_initialize.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch._six import string_classes
3
+ import functools
4
+ import numpy as np
5
+ import sys
6
+ from types import MethodType
7
+ import warnings
8
+ from ._amp_state import _amp_state, warn_or_err, container_abcs
9
+ from .handle import disable_casts
10
+ from .scaler import LossScaler
11
+ from ._process_optimizer import _process_optimizer
12
+ from apex.fp16_utils import convert_network
13
+ from ..fp16_utils import FP16_Optimizer as FP16_Optimizer_general
14
+ from ..contrib.optimizers import FP16_Optimizer as FP16_Optimizer_for_fused
15
+
16
+ if torch.distributed.is_available():
17
+ from ..parallel import DistributedDataParallel as apex_DDP
18
+ from ..parallel.LARC import LARC
19
+
20
+
21
+ def to_type(dtype, t):
22
+ if isinstance(t, torch.Tensor):
23
+ if not t.is_cuda:
24
+ # This should not be a hard error, since it may be legitimate.
25
+ warnings.warn("An input tensor was not cuda.")
26
+ # GANs require this.
27
+ # if t.requires_grad:
28
+ # warn_or_err("input data requires grad. Since input data is not a model parameter,\n"
29
+ # "its gradients will not be properly allreduced by DDP.")
30
+ if t.is_floating_point():
31
+ return t.to(dtype)
32
+ return t
33
+ else:
34
+ # Trust the user's custom batch type, that's all I can do here.
35
+ return t.to(dtype)
36
+
37
+
38
+ # Modified from torch.optim.optimizer.py. This is a bit more general than casted_args in utils.py.
39
+ def applier(value, fn):
40
+ if isinstance(value, torch.Tensor):
41
+ return fn(value)
42
+ elif isinstance(value, string_classes):
43
+ return value
44
+ elif isinstance(value, np.ndarray):
45
+ return value
46
+ elif hasattr(value, "to"): # Allow handling of custom batch classes
47
+ return fn(value)
48
+ elif isinstance(value, container_abcs.Mapping):
49
+ return {applier(k, fn) : applier(v, fn) for k, v in value.items()}
50
+ elif isinstance(value, container_abcs.Iterable):
51
+ return type(value)(applier(v, fn) for v in value)
52
+ else:
53
+ # Do I want this to fire off even if someone chooses to pass something ordinary like
54
+ # an int or float? May be more annoying than it's worth.
55
+ # print("Warning: unrecognized type in applier. If your input data is a custom class, "
56
+ # "provide it with a .to(dtype) method which converts its floating-point Tensors to dtype. "
57
+ # "Amp will check for your custom to() and invoke it to cast the batch's "
58
+ # "floating-point Tensors to the appropriate type. "
59
+ # "Also, if your data is a custom class, it is your responsibility to ensure that "
60
+ # "any Tensors you want to be cuda are already cuda."
61
+ return value
62
+
63
+
64
+ def check_models(models):
65
+ for model in models:
66
+ parallel_type = None
67
+ if isinstance(model, torch.nn.parallel.DistributedDataParallel):
68
+ parallel_type = "torch.nn.parallel.DistributedDataParallel"
69
+ if ('apex_DDP' in sys.modules) and isinstance(model, apex_DDP):
70
+ parallel_type = "apex.parallel.DistributedDataParallel"
71
+ if isinstance(model, torch.nn.parallel.DataParallel):
72
+ parallel_type = "torch.nn.parallel.DataParallel"
73
+ if parallel_type is not None:
74
+ raise RuntimeError("Incoming model is an instance of {}. ".format(parallel_type) +
75
+ "Parallel wrappers should only be applied to the model(s) AFTER \n"
76
+ "the model(s) have been returned from amp.initialize.")
77
+
78
+
79
+ def check_params_fp32(models):
80
+ for model in models:
81
+ for name, param in model.named_parameters():
82
+ if param.is_floating_point():
83
+ if 'Half' in param.type():
84
+ warn_or_err("Found param {} with type {}, expected torch.cuda.FloatTensor.\n"
85
+ "When using amp.initialize, you do not need to call .half() on your model\n"
86
+ "before passing it, no matter what optimization level you choose.".format(
87
+ name, param.type()))
88
+ elif not param.is_cuda:
89
+ warn_or_err("Found param {} with type {}, expected torch.cuda.FloatTensor.\n"
90
+ "When using amp.initialize, you need to provide a model with parameters\n"
91
+ "located on a CUDA device before passing it no matter what optimization level\n"
92
+ "you chose. Use model.to('cuda') to use the default device.".format(
93
+ name, param.type()))
94
+
95
+ # Backward compatibility for PyTorch 0.4
96
+ if hasattr(model, 'named_buffers'):
97
+ buf_iter = model.named_buffers()
98
+ else:
99
+ buf_iter = model._buffers
100
+ for obj in buf_iter:
101
+ if type(obj)==tuple:
102
+ name, buf = obj
103
+ else:
104
+ name, buf = obj, buf_iter[obj]
105
+ if buf.is_floating_point():
106
+ if 'Half' in buf.type():
107
+ warn_or_err("Found buffer {} with type {}, expected torch.cuda.FloatTensor.\n"
108
+ "When using amp.initialize, you do not need to call .half() on your model\n"
109
+ "before passing it, no matter what optimization level you choose.".format(
110
+ name, buf.type()))
111
+ elif not buf.is_cuda:
112
+ warn_or_err("Found buffer {} with type {}, expected torch.cuda.FloatTensor.\n"
113
+ "When using amp.initialize, you need to provide a model with buffers\n"
114
+ "located on a CUDA device before passing it no matter what optimization level\n"
115
+ "you chose. Use model.to('cuda') to use the default device.".format(
116
+ name, buf.type()))
117
+
118
+
119
+ def check_optimizers(optimizers):
120
+ for optim in optimizers:
121
+ bad_optim_type = None
122
+ if isinstance(optim, FP16_Optimizer_general):
123
+ bad_optim_type = "apex.fp16_utils.FP16_Optimizer"
124
+ if isinstance(optim, FP16_Optimizer_for_fused):
125
+ bad_optim_type = "apex.optimizers.FP16_Optimizer"
126
+ if bad_optim_type is not None:
127
+ raise RuntimeError("An incoming optimizer is an instance of {}. ".format(bad_optim_type) +
128
+ "The optimizer(s) passed to amp.initialize() must be bare \n"
129
+ "instances of either ordinary Pytorch optimizers, or Apex fused \n"
130
+ "optimizers.\n")
131
+
132
+
133
+ class O2StateDictHook(object):
134
+ def __init__(self, fn):
135
+ self.fn = fn
136
+
137
+ def __call__(self, module, state_dict, prefix, local_metadata):
138
+ for key in state_dict:
139
+ param = state_dict[key]
140
+ if 'Half' in param.type():
141
+ param = param.to(torch.float32)
142
+ state_dict[key] = param
143
+
144
+
145
+ def _initialize(models, optimizers, properties, num_losses=1, cast_model_outputs=None):
146
+ from .amp import init as amp_init
147
+
148
+ optimizers_was_list = False
149
+ if isinstance(optimizers, torch.optim.Optimizer) or ('LARC' in globals() and isinstance(optimizers, LARC)):
150
+ optimizers = [optimizers]
151
+ elif optimizers is None:
152
+ optimizers = []
153
+ elif isinstance(optimizers, list):
154
+ optimizers_was_list = True
155
+ check_optimizers(optimizers)
156
+ else:
157
+ check_optimizers([optimizers])
158
+ raise TypeError("optimizers must be either a single optimizer or a list of optimizers.")
159
+
160
+ if isinstance(models, torch.nn.Module):
161
+ models_was_list = False
162
+ models = [models]
163
+ elif isinstance(models, list):
164
+ models_was_list = True
165
+ else:
166
+ raise TypeError("models must be either a single model or a list of models.")
167
+
168
+ check_models(models)
169
+
170
+ if not _amp_state.allow_incoming_model_not_fp32:
171
+ check_params_fp32(models)
172
+
173
+ # In the future, when FP16_Optimizer can be deprecated and master weights can
174
+ # become an attribute, remember to stash master weights before casting the model.
175
+
176
+ if properties.cast_model_type:
177
+ if properties.keep_batchnorm_fp32:
178
+ for model in models:
179
+ convert_network(model, properties.cast_model_type)
180
+ else:
181
+ for model in models:
182
+ model.to(properties.cast_model_type)
183
+
184
+ input_caster = functools.partial(to_type, properties.cast_model_type)
185
+ if cast_model_outputs is not None:
186
+ output_caster = functools.partial(to_type, cast_model_outputs)
187
+ else:
188
+ output_caster = functools.partial(to_type, torch.float32)
189
+
190
+ for model in models:
191
+ # Patch the forward method to cast incoming data to the correct type, and
192
+ # outgoing data to float32, so "the user never needs to call .half()."
193
+ # I like writing things explicitly more than decorators.
194
+ def patch_forward(old_fwd):
195
+ def new_fwd(*args, **kwargs):
196
+ output = old_fwd(*applier(args, input_caster),
197
+ **applier(kwargs, input_caster))
198
+ return applier(output, output_caster)
199
+ return new_fwd
200
+
201
+ model.forward = patch_forward(model.forward)
202
+
203
+ # State dict trick to recast any preexisting per-param state tensors
204
+ for optimizer in optimizers:
205
+ optimizer.load_state_dict(optimizer.state_dict())
206
+
207
+ # patch model.state_dict() to return float32 params
208
+ for model in models:
209
+ for module in model.modules():
210
+ module._register_state_dict_hook(O2StateDictHook(functools.partial(to_type, torch.float32)))
211
+
212
+ elif cast_model_outputs is not None:
213
+ output_caster = functools.partial(to_type, cast_model_outputs)
214
+
215
+ for model in models:
216
+ def patch_forward(old_fwd):
217
+ def new_fwd(*args, **kwargs):
218
+ output = old_fwd(*args, **kwargs)
219
+ return applier(output, output_caster)
220
+ return new_fwd
221
+
222
+ model.forward = patch_forward(model.forward)
223
+
224
+ for i, optimizer in enumerate(optimizers):
225
+ optimizers[i] = _process_optimizer(optimizer, properties)
226
+
227
+ _amp_state.loss_scalers = []
228
+ for _ in range(num_losses):
229
+ _amp_state.loss_scalers.append(LossScaler(properties.loss_scale,
230
+ min_loss_scale=_amp_state.min_loss_scale,
231
+ max_loss_scale=_amp_state.max_loss_scale))
232
+
233
+ if properties.patch_torch_functions:
234
+ # handle is unused here. It's accessible later through a global value anyway.
235
+ handle = amp_init(loss_scale=properties.loss_scale, verbose=(_amp_state.verbosity == 2))
236
+ for optimizer in optimizers:
237
+ # Disable Amp casting for the optimizer step, because it should only be
238
+ # applied to FP32 master params anyway.
239
+ def patch_step(old_step):
240
+ def new_step(self, *args, **kwargs):
241
+ with disable_casts():
242
+ output = old_step(*args, **kwargs)
243
+ return output
244
+ return new_step
245
+
246
+ optimizer.step = MethodType(patch_step(optimizer.step), optimizer)
247
+
248
+ if optimizers_was_list:
249
+ if models_was_list:
250
+ return models, optimizers
251
+ else:
252
+ return models[0], optimizers
253
+ else:
254
+ if models_was_list:
255
+ if len(optimizers) == 0:
256
+ return models
257
+ else:
258
+ return models, optimizers[0]
259
+ else:
260
+ if len(optimizers) == 0:
261
+ return models[0]
262
+ else:
263
+ return models[0], optimizers[0]
apex/apex/amp/_process_optimizer.py ADDED
@@ -0,0 +1,489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import types
2
+ from ..fp16_utils import master_params_to_model_params
3
+ from ..multi_tensor_apply import multi_tensor_applier
4
+ from ._amp_state import maybe_print
5
+ import torch
6
+ from ..optimizers import FusedSGD
7
+
8
+
9
+ class AmpOptimizerState(object):
10
+ def __init__(self):
11
+ pass
12
+
13
+
14
+ def _master_params_to_model_params(self):
15
+ stash = self._amp_stash
16
+ if multi_tensor_applier.available:
17
+ if len(stash.all_fp16_params) > 0:
18
+ multi_tensor_applier(
19
+ stash.multi_tensor_scale,
20
+ stash.dummy_overflow_buf,
21
+ [stash.all_fp32_from_fp16_params, stash.all_fp16_params],
22
+ 1.0)
23
+ else:
24
+ for fp16_group, fp32_from_fp16_group in zip(stash.fp16_groups, stash.fp32_from_fp16_groups):
25
+ master_params_to_model_params(fp16_group, fp32_from_fp16_group)
26
+
27
+
28
+ def lazy_init_with_master_weights(self):
29
+ stash = self._amp_stash
30
+ stash.fp16_groups = []
31
+ stash.fp32_from_fp16_groups = []
32
+ stash.fp32_from_fp32_groups = []
33
+ for i, param_group in enumerate(self.param_groups):
34
+ # maybe_print("FP16_Optimizer processing param group {}:".format(i))
35
+ fp16_params_this_group = []
36
+ fp32_params_this_group = []
37
+ fp32_from_fp16_params_this_group = []
38
+ for i, param in enumerate(param_group['params']):
39
+ if param.requires_grad:
40
+ if param.type() == 'torch.cuda.HalfTensor':
41
+ # maybe_print("FP16_Optimizer received torch.cuda.HalfTensor with {}"
42
+ # .format(param.size()))
43
+ fp16_params_this_group.append(param)
44
+ master_param = param.detach().clone().float()
45
+ master_param.requires_grad = True
46
+ param_group['params'][i] = master_param
47
+ fp32_from_fp16_params_this_group.append(master_param)
48
+ # Reset existing state dict key to the new master param.
49
+ # We still need to recast per-param state tensors, if any, to FP32.
50
+ if param in self.state:
51
+ self.state[master_param] = self.state.pop(param)
52
+ elif param.type() == 'torch.cuda.FloatTensor':
53
+ # maybe_print("FP16_Optimizer received torch.cuda.FloatTensor with {}"
54
+ # .format(param.size()))
55
+ fp32_params_this_group.append(param)
56
+ param_group['params'][i] = param
57
+ else:
58
+ raise TypeError("Optimizer's parameters must be either "
59
+ "torch.cuda.FloatTensor or torch.cuda.HalfTensor. "
60
+ "Received {}".format(param.type()))
61
+
62
+ stash.fp16_groups.append(fp16_params_this_group)
63
+ stash.fp32_from_fp16_groups.append(fp32_from_fp16_params_this_group)
64
+ stash.fp32_from_fp32_groups.append(fp32_params_this_group)
65
+
66
+ stash.all_fp16_params = []
67
+ for group in stash.fp16_groups:
68
+ stash.all_fp16_params += group
69
+
70
+ stash.all_fp32_from_fp16_params = []
71
+ for group in stash.fp32_from_fp16_groups:
72
+ stash.all_fp32_from_fp16_params += group
73
+
74
+ stash.all_fp32_from_fp32_params = []
75
+ for group in stash.fp32_from_fp32_groups:
76
+ stash.all_fp32_from_fp32_params += group
77
+
78
+ # all_fp16_grad_stash is only needed for fused optimizers.
79
+ stash.all_fp16_grad_stash = [None for _ in stash.all_fp16_params]
80
+ # stash.all_fp32_from_fp16_grad_stash = [None for _ in stash.all_fp32_from_fp16_params]
81
+ stash.all_fp32_from_fp32_grad_stash = [None for _ in stash.all_fp32_from_fp32_params]
82
+
83
+ for param in stash.all_fp32_from_fp16_params:
84
+ param.grad = None
85
+
86
+ for param in stash.all_fp32_from_fp32_params:
87
+ param.grad = None
88
+
89
+ # Leverage state_dict() and load_state_dict() to recast preexisting per-param state tensors
90
+ self.load_state_dict(self.state_dict())
91
+
92
+
93
+ def post_backward_models_are_masters(scaler, params, stashed_grads, scale_override=None):
94
+ grads_have_scale, stashed_have_scale, out_scale = scaler.loss_scale(), 1.0, 1.0
95
+
96
+ # not much to do if scale == 1.0 and static scaling
97
+ if scaler.loss_scale() == 1.0 and not scaler.dynamic:
98
+ # Clear the stash.
99
+ for i in range(len(stashed_grads)):
100
+ stashed_grads[i] = None
101
+ return
102
+
103
+ if scale_override is not None:
104
+ grads_have_scale, stashed_have_scale, out_scale = scale_override
105
+
106
+ # This is a lot of python overhead...
107
+ grads_needing_unscale = []
108
+ grads_needing_unscale_with_stash = []
109
+ stashed = []
110
+ for param, stashed_grad in zip(params, stashed_grads):
111
+ if param.grad is None and stashed_grad is not None:
112
+ param.grad = stashed_grad
113
+ elif param.grad is not None and stashed_grad is None:
114
+ grads_needing_unscale.append(param.grad)
115
+ elif param.grad is not None and stashed_grad is not None:
116
+ grads_needing_unscale_with_stash.append(param.grad)
117
+ stashed.append(stashed_grad)
118
+ else: # param.grad is None and stashed_grad is None
119
+ continue
120
+
121
+ # unscale() implements grads*(1/scale), so "scale" should be grads_have_scale/out_scale.
122
+ if len(grads_needing_unscale) > 0:
123
+ scaler.unscale(
124
+ grads_needing_unscale,
125
+ grads_needing_unscale,
126
+ None, # unused_scale, currently present to avoid API breakage elsewhere
127
+ models_are_masters=True,
128
+ scale_override=grads_have_scale/out_scale)
129
+
130
+ if len(grads_needing_unscale_with_stash) > 0:
131
+ scaler.unscale_with_stashed(
132
+ grads_needing_unscale_with_stash,
133
+ stashed,
134
+ grads_needing_unscale_with_stash,
135
+ scale_override=(grads_have_scale, stashed_have_scale, out_scale))
136
+
137
+ # Clear the stash.
138
+ for i in range(len(stashed_grads)):
139
+ stashed_grads[i] = None
140
+
141
+
142
+ def prepare_backward_with_master_weights(self):
143
+ stash = self._amp_stash
144
+
145
+ self._amp_lazy_init()
146
+
147
+ for i, param in enumerate(stash.all_fp16_params):
148
+ # Set up to leverage grad copy elision.
149
+ # This may behave differently from an unpatched optimizer if zero_grad is used and the param is unused.
150
+ param.grad = None
151
+
152
+ # for i, param in enumerate(stash.all_fp32_from_fp16_params):
153
+ # stash.all_fp32_from_fp16_grad_stash[i] = param.grad
154
+
155
+ for i, param in enumerate(stash.all_fp32_from_fp32_params):
156
+ stash.all_fp32_from_fp32_grad_stash[i] = param.grad
157
+ # Set up to leverage grad copy elision:
158
+ param.grad = None
159
+
160
+
161
+ def post_backward_with_master_weights(self, scaler):
162
+ stash = self._amp_stash
163
+
164
+ self._amp_lazy_init()
165
+
166
+ # This is a lot of python overhead...
167
+ fp16_grads_needing_unscale = []
168
+ new_fp32_grads = []
169
+ fp16_grads_needing_unscale_with_stash = []
170
+ preexisting_fp32_grads = []
171
+ for fp16_param, fp32_param in zip(stash.all_fp16_params,
172
+ stash.all_fp32_from_fp16_params):
173
+ if fp16_param.grad is None and fp32_param.grad is not None:
174
+ continue
175
+ elif fp16_param.grad is not None and fp32_param.grad is None:
176
+ fp32_param.grad = torch.empty_like(fp32_param)
177
+ fp16_grads_needing_unscale.append(fp16_param.grad)
178
+ new_fp32_grads.append(fp32_param.grad)
179
+ elif fp16_param.grad is not None and fp32_param.grad is not None:
180
+ fp16_grads_needing_unscale_with_stash.append(fp16_param.grad)
181
+ preexisting_fp32_grads.append(fp32_param.grad)
182
+ else: # fp16_param.grad is None and fp32_param.grad is None:
183
+ continue
184
+
185
+ if len(fp16_grads_needing_unscale) > 0:
186
+ scaler.unscale(
187
+ fp16_grads_needing_unscale,
188
+ new_fp32_grads,
189
+ scaler.loss_scale(),
190
+ models_are_masters=False)
191
+
192
+ if len(fp16_grads_needing_unscale_with_stash) > 0:
193
+ scaler.unscale_with_stashed(
194
+ fp16_grads_needing_unscale_with_stash,
195
+ preexisting_fp32_grads,
196
+ preexisting_fp32_grads)
197
+
198
+ # fp32 params can be treated as they would be in the "no_master_weights" case.
199
+ post_backward_models_are_masters(
200
+ scaler,
201
+ stash.all_fp32_from_fp32_params,
202
+ stash.all_fp32_from_fp32_grad_stash)
203
+
204
+
205
+ def lazy_init_no_master_weights(self):
206
+ stash = self._amp_stash
207
+ stash.all_fp16_params = []
208
+ stash.all_fp32_params = []
209
+ for i, param_group in enumerate(self.param_groups):
210
+ for i, param in enumerate(param_group['params']):
211
+ if param.type() == 'torch.cuda.HalfTensor':
212
+ stash.all_fp16_params.append(param)
213
+ elif param.type() == 'torch.cuda.FloatTensor':
214
+ stash.all_fp32_params.append(param)
215
+ else:
216
+ raise TypeError("Optimizer's parameters must be either "
217
+ "torch.cuda.FloatTensor or torch.cuda.HalfTensor. "
218
+ "Received {}".format(param.type()))
219
+
220
+ stash.all_fp16_grad_stash = [None for _ in stash.all_fp16_params]
221
+ stash.all_fp32_grad_stash = [None for _ in stash.all_fp32_params]
222
+
223
+
224
+ def prepare_backward_no_master_weights(self):
225
+ stash = self._amp_stash
226
+
227
+ self._amp_lazy_init()
228
+
229
+ for i, param in enumerate(stash.all_fp16_params):
230
+ stash.all_fp16_grad_stash[i] = param.grad
231
+ # Set up to leverage grad copy elision:
232
+ param.grad = None
233
+
234
+ for i, param in enumerate(stash.all_fp32_params):
235
+ stash.all_fp32_grad_stash[i] = param.grad
236
+ # Set up to leverage grad copy elision:
237
+ param.grad = None
238
+
239
+
240
+ def post_backward_no_master_weights(self, scaler):
241
+ stash = self._amp_stash
242
+
243
+ self._amp_lazy_init()
244
+
245
+ split_types = ((stash.all_fp16_params, stash.all_fp16_grad_stash),
246
+ (stash.all_fp32_params, stash.all_fp32_grad_stash))
247
+
248
+ for params, stashed_grads in split_types:
249
+ post_backward_models_are_masters(scaler, params, stashed_grads)
250
+
251
+
252
+ #####################################################################################
253
+ # FusedSGD versions
254
+ #####################################################################################
255
+
256
+ # FusedSGD never explicitly materializes the fp32 gradients for "fp32 from fp16" master params
257
+ # outside the kernel, so we must accumulate directly into the model grads.
258
+ def prepare_backward_with_master_weights_FusedSGD(self):
259
+ if self.materialize_master_grads:
260
+ prepare_backward_with_master_weights(self)
261
+ else:
262
+ stash = self._amp_stash
263
+
264
+ self._amp_lazy_init()
265
+
266
+ for i, param in enumerate(stash.all_fp16_params):
267
+ stash.all_fp16_grad_stash[i] = param.grad
268
+ # Set up to leverage grad copy elision:
269
+ param.grad = None
270
+
271
+ for i, param in enumerate(stash.all_fp32_from_fp32_params):
272
+ stash.all_fp32_from_fp32_grad_stash[i] = param.grad
273
+ # Set up to leverage grad copy elision:
274
+ param.grad = None
275
+
276
+
277
+ def post_backward_with_master_weights_FusedSGD(self, scaler):
278
+ if self.materialize_master_grads:
279
+ post_backward_with_master_weights(self, scaler)
280
+ else:
281
+ stash = self._amp_stash
282
+
283
+ self._amp_lazy_init()
284
+
285
+ grads_have_scale = scaler.loss_scale()
286
+ stashed_have_scale = self.most_recent_scale
287
+ out_scale = grads_have_scale
288
+ if self.scale_set_by_backward:
289
+ out_scale = min(grads_have_scale, self.most_recent_scale)
290
+
291
+ split_types = ((stash.all_fp16_params, stash.all_fp16_grad_stash),
292
+ (stash.all_fp32_from_fp32_params, stash.all_fp32_from_fp32_grad_stash))
293
+
294
+
295
+ # unscale_with_stashed() implements grads*1/scale + stashed_grads*1.
296
+ # stashed_grads are scaled by self.most_recent_scale.
297
+ for params, stashed_grads in split_types:
298
+ post_backward_models_are_masters(scaler, params, stashed_grads,
299
+ (grads_have_scale, stashed_have_scale, out_scale))
300
+
301
+ self.most_recent_scale = out_scale
302
+ self.scale_set_by_backward = True
303
+
304
+
305
+ def prepare_backward_no_master_weights_FusedSGD(self):
306
+ prepare_backward_no_master_weights(self)
307
+
308
+
309
+ def post_backward_no_master_weights_FusedSGD(self, scaler):
310
+ post_backward_no_master_weights(self, scaler)
311
+
312
+
313
+ def _amp_lazy_init(self):
314
+ stash = self._amp_stash
315
+
316
+ if not stash.lazy_init_called:
317
+ self._lazy_init_maybe_master_weights()
318
+ stash.lazy_init_called = True
319
+
320
+
321
+ def _process_optimizer(optimizer, properties):
322
+ if hasattr(optimizer, "_amp_stash"):
323
+ raise RuntimeError("A given optimizer should only be passed through amp.initialize once.")
324
+ else:
325
+ optimizer._amp_stash = AmpOptimizerState()
326
+
327
+ optimizer._amp_stash.lazy_init_called = False
328
+ optimizer._amp_stash.already_patched = False
329
+ optimizer._amp_stash.params_have_scaled_gradients = False
330
+
331
+ for name in ("_lazy_init_maybe_master_weights",
332
+ "_master_params_to_model_params",
333
+ "_prepare_amp_backward",
334
+ "_post_amp_backward",
335
+ "_amp_lazy_init"):
336
+ if hasattr(optimizer, name):
337
+ raise RuntimeError("Incoming optimizer already has {} defined.".format(name))
338
+
339
+ # TODO: Centralize exposure and import error checking for the C backend.
340
+ if multi_tensor_applier.available:
341
+ import amp_C
342
+ optimizer._amp_stash.multi_tensor_scale = amp_C.multi_tensor_scale
343
+ optimizer._amp_stash.multi_tensor_l2norm = amp_C.multi_tensor_l2norm
344
+ optimizer._amp_stash.dummy_overflow_buf = torch.cuda.IntTensor([0]);
345
+
346
+ if properties.master_weights:
347
+ optimizer._lazy_init_maybe_master_weights = types.MethodType(
348
+ lazy_init_with_master_weights, optimizer)
349
+
350
+ optimizer._master_params_to_model_params = types.MethodType(
351
+ _master_params_to_model_params, optimizer)
352
+
353
+ old_step = optimizer.step
354
+ def new_step(self, closure=None):
355
+ if closure is not None:
356
+ raise RuntimeError("Currently, Amp does not support closure use with optimizers.")
357
+ retval = old_step()
358
+ if not isinstance(self, FusedSGD):
359
+ self._master_params_to_model_params()
360
+ # Clear the master grads that wouldn't be zeroed by model.zero_grad()
361
+ for param in self._amp_stash.all_fp32_from_fp16_params:
362
+ param.grad = None
363
+ return retval
364
+ optimizer.step = types.MethodType(new_step, optimizer)
365
+
366
+ old_zero_grad = optimizer.zero_grad
367
+ def new_zero_grad(self):
368
+ stash = self._amp_stash
369
+ self._amp_lazy_init()
370
+ # Zero the model grads.
371
+ for param in stash.all_fp16_params:
372
+ if param.grad is not None:
373
+ param.grad.detach_()
374
+ param.grad.zero_()
375
+ for param in stash.all_fp32_from_fp32_params:
376
+ if param.grad is not None:
377
+ param.grad.detach_()
378
+ param.grad.zero_()
379
+ # Clear the master grads that are independent of model grads
380
+ for param in self._amp_stash.all_fp32_from_fp16_params:
381
+ param.grad = None
382
+ optimizer.zero_grad = types.MethodType(new_zero_grad, optimizer)
383
+
384
+ if isinstance(optimizer, FusedSGD):
385
+ optimizer._prepare_amp_backward = types.MethodType(
386
+ prepare_backward_with_master_weights_FusedSGD, optimizer)
387
+ optimizer._post_amp_backward = types.MethodType(
388
+ post_backward_with_master_weights_FusedSGD, optimizer)
389
+ else:
390
+ optimizer._prepare_amp_backward = types.MethodType(
391
+ prepare_backward_with_master_weights, optimizer)
392
+ optimizer._post_amp_backward = types.MethodType(
393
+ post_backward_with_master_weights, optimizer)
394
+ else:
395
+ optimizer._lazy_init_maybe_master_weights = types.MethodType(
396
+ lazy_init_no_master_weights, optimizer)
397
+
398
+ if isinstance(optimizer, FusedSGD):
399
+ optimizer._prepare_amp_backward = types.MethodType(
400
+ prepare_backward_no_master_weights_FusedSGD, optimizer)
401
+ optimizer._post_amp_backward = types.MethodType(
402
+ post_backward_no_master_weights_FusedSGD, optimizer)
403
+ else:
404
+ optimizer._prepare_amp_backward = types.MethodType(
405
+ prepare_backward_no_master_weights, optimizer)
406
+ optimizer._post_amp_backward = types.MethodType(
407
+ post_backward_no_master_weights, optimizer)
408
+
409
+ optimizer._amp_lazy_init = types.MethodType(_amp_lazy_init, optimizer)
410
+
411
+ old_add_param_group = optimizer.add_param_group
412
+
413
+ def new_add_param_group(self, new_group):
414
+ stash = self._amp_stash
415
+
416
+ if not stash.lazy_init_called:
417
+ self._lazy_init_maybe_master_weights()
418
+ stash.lazy_init_called = True
419
+
420
+ assert isinstance(new_group, dict), "param group must be a dict"
421
+
422
+ new_params = new_group['params']
423
+ if isinstance(new_params, torch.Tensor):
424
+ new_group['params'] = [new_params]
425
+ elif isinstance(new_params, set):
426
+ raise TypeError('optimizer parameters need to be organized in ordered collections, but '
427
+ 'the ordering of tensors in sets will change between runs. Please use a list instead.')
428
+ else:
429
+ new_group['params'] = list(new_params)
430
+
431
+ if properties.master_weights:
432
+ # Mutate new_group in-place to use FP32 master params
433
+ fp16_params_this_group = []
434
+ fp32_params_this_group = []
435
+ fp32_from_fp16_params_this_group = []
436
+ for i, param in enumerate(new_group['params']):
437
+ if param.requires_grad:
438
+ if param.type() == 'torch.cuda.HalfTensor':
439
+ fp16_params_this_group.append(param)
440
+ master_param = param.detach().clone().float()
441
+ master_param.requires_grad = True
442
+ new_group['params'][i] = master_param
443
+ fp32_from_fp16_params_this_group.append(master_param)
444
+ elif param.type() == 'torch.cuda.FloatTensor':
445
+ fp32_params_this_group.append(param)
446
+ new_group['params'][i] = param
447
+ else:
448
+ raise TypeError("Optimizer's parameters must be either "
449
+ "torch.cuda.FloatTensor or torch.cuda.HalfTensor. "
450
+ "Received {}".format(param.type()))
451
+
452
+ stash.fp16_groups.append(fp16_params_this_group)
453
+ stash.fp32_from_fp16_groups.append(fp32_from_fp16_params_this_group)
454
+ stash.fp32_from_fp32_groups.append(fp32_params_this_group)
455
+
456
+ stash.all_fp16_params += fp16_params_this_group
457
+ stash.all_fp32_from_fp16_params += fp32_from_fp16_params_this_group
458
+ stash.all_fp32_from_fp32_params += fp32_params_this_group
459
+
460
+ # stash.all_fp32_from_fp16_grad_stash = [None for _ in stash.all_fp32_from_fp16_params]
461
+ stash.all_fp32_from_fp32_grad_stash += [None for _ in fp32_params_this_group]
462
+
463
+ # It should be ok to let params be added with existing .grad attributes.
464
+ # for param in fp16_params_this_group:
465
+ # param.grad = None
466
+
467
+ # for param in fp32_from_fp16_params_this_group:
468
+ # param.grad = None
469
+
470
+ # for param in stash.fp32_params_this_group:
471
+ # param.grad = None
472
+ else:
473
+ for param in new_group['params']:
474
+ if param.type() == 'torch.cuda.HalfTensor':
475
+ stash.all_fp16_params.append(param)
476
+ stash.all_fp16_grad_stash.append(None)
477
+ elif param.type() == 'torch.cuda.FloatTensor':
478
+ stash.all_fp32_params.append(param)
479
+ stash.all_fp32_grad_stash.append(None)
480
+ else:
481
+ raise TypeError("Optimizer's parameters must be either "
482
+ "torch.cuda.FloatTensor or torch.cuda.HalfTensor. "
483
+ "Received {}".format(param.type()))
484
+
485
+ old_add_param_group(new_group)
486
+
487
+ optimizer.add_param_group = types.MethodType(new_add_param_group, optimizer)
488
+
489
+ return optimizer
apex/apex/amp/amp.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from . import compat, rnn_compat, utils, wrap
2
+ from .handle import AmpHandle, NoOpHandle
3
+ from .lists import functional_overrides, torch_overrides, tensor_overrides
4
+ from ._amp_state import _amp_state
5
+ from .frontend import *
6
+
7
+ import functools
8
+ import itertools
9
+
10
+ import torch
11
+
12
+
13
+ _DECORATOR_HANDLE = None
14
+ _USER_CAST_REGISTRY = set()
15
+ _USER_PROMOTE_REGISTRY = set()
16
+
17
+
18
+ def _decorator_helper(orig_fn, cast_fn, wrap_fn):
19
+ def wrapper(*args, **kwargs):
20
+ handle = _DECORATOR_HANDLE
21
+ if handle is None or not handle.is_active():
22
+ return orig_fn(*args, **kwargs)
23
+ inner_cast_fn = utils.verbosify(cast_fn, orig_fn.__name__,
24
+ handle.verbose)
25
+ return wrap_fn(orig_fn, inner_cast_fn, handle)(*args, **kwargs)
26
+ return wrapper
27
+
28
+
29
+ # Decorator form
30
+ def half_function(fn):
31
+ wrap_fn = functools.partial(wrap.make_cast_wrapper, try_caching=True)
32
+ return _decorator_helper(fn, utils.maybe_half, wrap_fn)
33
+
34
+
35
+ def float_function(fn):
36
+ wrap_fn = functools.partial(wrap.make_cast_wrapper, try_caching=False)
37
+ return _decorator_helper(fn, utils.maybe_float, wrap_fn)
38
+
39
+
40
+ def promote_function(fn):
41
+ wrap_fn = functools.partial(wrap.make_promote_wrapper)
42
+ return _decorator_helper(fn, utils.maybe_float, wrap_fn)
43
+
44
+
45
+ # Registry form
46
+ def register_half_function(module, name):
47
+ if not hasattr(module, name):
48
+ raise ValueError('No function named {} in module {}.'.format(
49
+ name, module))
50
+ _USER_CAST_REGISTRY.add((module, name, utils.maybe_half))
51
+
52
+
53
+ def register_float_function(module, name):
54
+ if not hasattr(module, name):
55
+ raise ValueError('No function named {} in module {}.'.format(
56
+ name, module))
57
+ _USER_CAST_REGISTRY.add((module, name, utils.maybe_float))
58
+
59
+
60
+ def register_promote_function(module, name):
61
+ if not hasattr(module, name):
62
+ raise ValueError('No function named {} in module {}.'.format(
63
+ name, module))
64
+ _USER_PROMOTE_REGISTRY.add((module, name))
65
+
66
+
67
+ # Top-level function to insert _all_ the hooks.
68
+ def init(enabled=True, loss_scale="dynamic", enable_caching=True, verbose=False, allow_banned=False):
69
+ global _DECORATOR_HANDLE
70
+
71
+ if not enabled:
72
+ handle = NoOpHandle()
73
+ _DECORATOR_HANDLE = handle
74
+ return handle
75
+
76
+ handle = AmpHandle(loss_scale, enable_caching, verbose)
77
+
78
+ # 0) Force-{fp16, fp32} for user-annotated functions
79
+ for mod, fn, cast_fn in _USER_CAST_REGISTRY:
80
+ try_caching = (cast_fn == utils.maybe_half)
81
+ wrap.cached_cast(mod, fn, cast_fn, handle,
82
+ try_caching, verbose)
83
+ _USER_CAST_REGISTRY.clear()
84
+
85
+ # 0.5) Force-promote for user-annotated functions
86
+ for mod, fn in _USER_PROMOTE_REGISTRY:
87
+ wrap.promote(mod, fn, handle, verbose)
88
+ _USER_PROMOTE_REGISTRY.clear()
89
+
90
+ # 1) Force-{fp16, fp32} on white- / black-list functions
91
+ override_modules = [functional_overrides,
92
+ torch_overrides,
93
+ tensor_overrides]
94
+ cast_table = [('FP16_FUNCS', utils.maybe_half),
95
+ ('FP32_FUNCS', utils.maybe_float)]
96
+ for module, (list_name, cast_fn) in itertools.product(override_modules,
97
+ cast_table):
98
+ for fn in getattr(module, list_name):
99
+ try_caching = (cast_fn == utils.maybe_half)
100
+ wrap.cached_cast(module.MODULE, fn, cast_fn, handle,
101
+ try_caching, verbose)
102
+
103
+ # 1.5) Pre-0.4, put the blacklist methods on HalfTensor and whitelist
104
+ # methods on FloatTensor, since they're distinct types.
105
+ if compat.tensor_is_float_tensor():
106
+ for fn in tensor_overrides.FP16_FUNCS:
107
+ wrap.cached_cast(torch.cuda.FloatTensor, fn, utils.maybe_half,
108
+ handle, try_caching=True, verbose=verbose)
109
+ for fn in tensor_overrides.FP32_FUNCS:
110
+ wrap.cached_cast(torch.cuda.HalfTensor, fn, utils.maybe_float,
111
+ handle, try_caching=False, verbose=verbose)
112
+
113
+ # 2) Enable type-promotion on multi-arg functions and methods.
114
+ # NB: special handling for sequence fns (e.g. `torch.cat`).
115
+ promote_modules = [torch_overrides, tensor_overrides]
116
+ promote_table = [('CASTS', wrap.promote),
117
+ ('SEQUENCE_CASTS', wrap.sequence_promote)]
118
+ for promote_mod, (list_name, promote_fn) in itertools.product(promote_modules,
119
+ promote_table):
120
+ for fn in getattr(promote_mod, list_name):
121
+ promote_fn(promote_mod.MODULE, fn, handle, verbose)
122
+
123
+ # 2.5) Pre-0.4, add blacklist methods directly to HalfTensor and FloatTensor types
124
+ if compat.tensor_is_float_tensor():
125
+ for cls, (list_name, promote_fn) in itertools.product([torch.cuda.FloatTensor,
126
+ torch.cuda.HalfTensor],
127
+ promote_table):
128
+ for fn in getattr(tensor_overrides, list_name):
129
+ promote_fn(cls, fn, handle, verbose)
130
+
131
+ # 3) For any in-place version of a blacklist function, error if any input is fp16.
132
+ # NB: this is overly conservative.
133
+ for fn in utils.as_inplace(torch_overrides.FP32_FUNCS):
134
+ wrap.err_if_any_half(torch_overrides.MODULE, fn, handle)
135
+
136
+ # 3.5) For any in-place blacklist method, error if called on fp16 tensor
137
+ for fn in utils.as_inplace(tensor_overrides.FP32_FUNCS):
138
+ wrap.err_if_arg0_half(tensor_overrides.MODULE, fn, handle, verbose)
139
+ if compat.tensor_is_float_tensor():
140
+ wrap.err_if_arg0_half(torch.cuda.HalfTensor, fn, handle, verbose)
141
+
142
+ # 4) For other in-place methods, match the type of self tensor
143
+ for fn in utils.as_inplace(itertools.chain(
144
+ tensor_overrides.FP16_FUNCS,
145
+ tensor_overrides.CASTS)):
146
+ wrap.promote_match_arg0(tensor_overrides.MODULE, fn, handle, verbose)
147
+ if compat.tensor_is_float_tensor():
148
+ wrap.promote_match_arg0(torch.cuda.HalfTensor, fn, handle, verbose)
149
+ wrap.promote_match_arg0(torch.cuda.FloatTensor, fn, handle, verbose)
150
+
151
+ # 5) RNNs + RNN cells are whitelisted specially
152
+ if rnn_compat.has_old_rnns():
153
+ wrap.rnn_cast(torch.nn.backends.thnn.backend, 'RNN', handle, verbose)
154
+ if not rnn_compat.has_old_rnns():
155
+ # Patch in our own indirection of `_VF` in modules/rnn s.t. it is mutable.
156
+ torch.nn.modules.rnn._VF = rnn_compat.VariableFunctionsShim()
157
+ # Wrap all the rnns
158
+ for x in rnn_compat.RNN_NAMES:
159
+ wrap.new_rnn_cast(x.upper(), handle, verbose)
160
+
161
+ # Wrap all the RNN cells
162
+ rnn_compat.whitelist_rnn_cells(handle, verbose)
163
+
164
+ # 6) Place error+print message on banned functions.
165
+ # Or, if allow_banned, then cast to FP32.
166
+ for fn, err_msg in functional_overrides.BANNED_FUNCS:
167
+ if allow_banned:
168
+ wrap.cached_cast(functional_overrides.MODULE, fn, utils.maybe_float,
169
+ handle, try_caching=True, verbose=verbose)
170
+ else:
171
+ wrap.err_if_any_half(functional_overrides.MODULE, fn, handle, err_msg)
172
+
173
+ _DECORATOR_HANDLE = handle
174
+
175
+ _amp_state.handle = handle
176
+
177
+ return handle
apex/apex/amp/compat.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ # True for post-0.4, when Variables/Tensors merged.
4
+ def variable_is_tensor():
5
+ v = torch.autograd.Variable()
6
+ return isinstance(v, torch.Tensor)
7
+
8
+ def tensor_is_variable():
9
+ x = torch.Tensor()
10
+ return type(x) == torch.autograd.Variable
11
+
12
+ # False for post-0.4
13
+ def tensor_is_float_tensor():
14
+ x = torch.Tensor()
15
+ return type(x) == torch.FloatTensor
16
+
17
+ # Akin to `torch.is_tensor`, but returns True for Variable
18
+ # objects in pre-0.4.
19
+ def is_tensor_like(x):
20
+ return torch.is_tensor(x) or isinstance(x, torch.autograd.Variable)
21
+
22
+ # Wraps `torch.is_floating_point` if present, otherwise checks
23
+ # the suffix of `x.type()`.
24
+ def is_floating_point(x):
25
+ if hasattr(torch, 'is_floating_point'):
26
+ return torch.is_floating_point(x)
27
+ try:
28
+ torch_type = x.type()
29
+ return torch_type.endswith('FloatTensor') or \
30
+ torch_type.endswith('HalfTensor') or \
31
+ torch_type.endswith('DoubleTensor')
32
+ except AttributeError:
33
+ return False
34
+
35
+ def scalar_python_val(x):
36
+ if hasattr(x, 'item'):
37
+ return x.item()
38
+ else:
39
+ if isinstance(x, torch.autograd.Variable):
40
+ return x.data[0]
41
+ else:
42
+ return x[0]
43
+
44
+ # Accounts for the possibility that some ops may be removed from a namespace.
45
+ def filter_attrs(module, attrs):
46
+ return list(attrname for attrname in attrs if hasattr(module, attrname))
apex/apex/amp/frontend.py ADDED
@@ -0,0 +1,442 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from ._initialize import _initialize
3
+ from ._amp_state import _amp_state, warn_or_err, maybe_print
4
+ from collections import OrderedDict
5
+
6
+
7
+ class Properties(object):
8
+ """
9
+ This class has two purposes: to establish a set of default properties,
10
+ and to route setting of these attributes through __setattr__ so that (in theory)
11
+ they can be checked for consistency with other existing args.
12
+ """
13
+ def __init__(self):
14
+ self.options = {
15
+ "enabled" : False,
16
+ "opt_level" : None,
17
+ "cast_model_type" : None,
18
+ "patch_torch_functions" : False,
19
+ "keep_batchnorm_fp32" : None,
20
+ "master_weights" : None,
21
+ "loss_scale" : 1.0,
22
+ # Reserved for future functionality
23
+ # "fused_optimizer" : False,
24
+ # "enable_ddp_interop" : False,
25
+ }
26
+
27
+ """
28
+ This function allows updating several options at a time without routing through
29
+ __setattr__ checks, to avoid "you can't get there from here" scenarios.
30
+ Currently not intended to be exposed; users are expected to select an opt_level
31
+ and apply consistent modifications.
32
+ """
33
+ def _update_options_dict(self, new_options):
34
+ for k, v in new_options:
35
+ if k in self.options:
36
+ self.options[k] = v
37
+ else:
38
+ raise ValueError("Tried to set unexpected option {}".format(k))
39
+ """
40
+ The members of "options" are not direct attributes of self, so access attempts
41
+ will roll down to __getattr__. This borrows from the logic in torch.nn.Module.
42
+ """
43
+ def __getattr__(self, name):
44
+ if "options" in self.__dict__:
45
+ options = self.__dict__["options"]
46
+ if name in options:
47
+ return options[name]
48
+ raise AttributeError("'{}' object has no attribute '{}'".format(
49
+ type(self).__name__, name))
50
+
51
+ def __setattr__(self, name, value):
52
+ if "options" in self.__dict__:
53
+ if name in self.options:
54
+ # print("setting {} {}".format(name, value))
55
+ if name == "cast_model_type":
56
+ if self.opt_level == "O1" and value is not None:
57
+ if value is not False:
58
+ if value is not torch.float32:
59
+ warn_or_err("O1 inserts casts around Torch functions rather than "
60
+ "model weights, so with O1, the model weights themselves "
61
+ "should remain FP32. If you wish to cast the model to a "
62
+ "different type, use opt_level='O2' or 'O3'. " +
63
+ "cast_model_type was {}".format(value))
64
+ self.options[name] = value
65
+ elif name == "patch_torch_functions":
66
+ if self.opt_level != "O1" and value:
67
+ warn_or_err("Currently, patch_torch_functions=True should only be set by "
68
+ "selecting opt_level='O1'.")
69
+ self.options[name] = value
70
+ elif name == "keep_batchnorm_fp32":
71
+ if self.opt_level == "O1" and value is not None:
72
+ warn_or_err("With opt_level O1, batchnorm functions are automatically patched "
73
+ "to run in FP32, so keep_batchnorm_fp32 should be None." +
74
+ " keep_batchnorm_fp32 was {}".format(value))
75
+ if value == "False":
76
+ self.options[name] = False
77
+ elif value == "True":
78
+ self.options[name] = True
79
+ else:
80
+ assert (value is True or value is False or value is None),\
81
+ "keep_batchnorm_fp32 must be a boolean, the string 'True' or 'False', "\
82
+ "or None, found keep_batchnorm_fp32={}".format(value)
83
+ self.options[name] = value
84
+ elif name == "master_weights":
85
+ if self.opt_level == "O1" and value is not None:
86
+ warn_or_err("It doesn't make sense to use master_weights with O1. "
87
+ "With O1, your model weights themselves should be FP32.")
88
+ self.options[name] = value
89
+ elif name == "loss_scale":
90
+ if value == "dynamic":
91
+ self.options[name] = value
92
+ else:
93
+ self.options[name] = float(value)
94
+ else:
95
+ self.options[name] = value
96
+ else:
97
+ super(Properties, self).__setattr__(name, value)
98
+
99
+
100
+ """ O0-O3 are convenience wrappers to establish defaults for typically used mixed precision options. """
101
+
102
+ class O3:
103
+ brief = "O3: Pure FP16 training."
104
+ more = "Calls .half() on your model, converting the entire model to FP16.\n"\
105
+ "A casting operation is also inserted to cast incoming Tensors to FP16,\n"\
106
+ "so you don't need to change your data pipeline.\n"\
107
+ "This mode is useful for establishing a performance ceiling.\n"\
108
+ "It's also possible training may 'just work' in this mode.\n"\
109
+ "If not, try other optimization levels."
110
+
111
+ def __call__(self, properties):
112
+ properties.enabled = True
113
+ properties.opt_level = "O3"
114
+ properties.cast_model_type = torch.float16
115
+ properties.patch_torch_functions = False
116
+ properties.keep_batchnorm_fp32 = False
117
+ properties.master_weights = False
118
+ properties.loss_scale = 1.0
119
+ # properties.fused_optimizer = False
120
+ # properties.enable_ddp_interop = False
121
+ return properties # modified in place so this isn't really necessary
122
+
123
+
124
+ class O2:
125
+ brief = "O2: FP16 training with FP32 batchnorm and FP32 master weights.\n"
126
+ more = "Calls .half() on your model, converting the entire model (except for batchnorms)\n"\
127
+ "to FP16. Batchnorms are retained in FP32 for additional stability.\n"\
128
+ "The forward pass is patched to cast incoming Tensors to FP16, so you don't need to change\n"\
129
+ "your data pipeline.\n"\
130
+ "O2 creates FP32 master weights outside the model and patches any optimizers to update\n"\
131
+ "these master weights, then copy the master weights into the FP16 model weights.\n"\
132
+ "Master weights can also improve convergence and stability."
133
+
134
+ def __call__(self, properties):
135
+ properties.enabled = True
136
+ properties.opt_level = "O2"
137
+ properties.cast_model_type = torch.float16
138
+ properties.patch_torch_functions = False
139
+ properties.keep_batchnorm_fp32 = True
140
+ properties.master_weights = True
141
+ properties.loss_scale = "dynamic"
142
+ # properties.fused_optimizer = False
143
+ # properties.enable_ddp_interop = False
144
+ return properties # modified in place so this isn't really necessary
145
+
146
+
147
+ class O1:
148
+ brief = "O1: Insert automatic casts around Pytorch functions and Tensor methods.\n"
149
+ more = "The type of your model's weights is not altered. However, internally,\n"\
150
+ "Pytorch functions are patched to cast any Tensor Core-friendly ops to FP16 for speed,\n"\
151
+ "while operations that might benefit from the additional stability of FP32 are patched\n"\
152
+ "to cast their inputs to fp32.\n"\
153
+ "O1 is the safest way to try mixed precision training, and is recommended when\n"\
154
+ "trying mixed precision training for the first time."
155
+
156
+ def __call__(self, properties):
157
+ properties.enabled = True
158
+ properties.opt_level = "O1"
159
+ properties.cast_model_type = None
160
+ properties.patch_torch_functions = True
161
+ properties.keep_batchnorm_fp32 = None
162
+ properties.master_weights = None
163
+ properties.loss_scale = "dynamic"
164
+ # properties.fused_optimizer = False
165
+ # properties.enable_ddp_interop = False
166
+ return properties # modified in place so this isn't really necessary
167
+
168
+
169
+ class O0:
170
+ brief = "O0: Pure FP32 training.\n"
171
+ more = "Your models are checked to make sure parameters are FP32, but otherwise the\n"\
172
+ "types of weights and internal Pytorch operations are not altered. This mode disables any\n"\
173
+ "FP16 arithmetic, although other optimizations like DDP interop may still be requested.\n"
174
+
175
+ def __call__(self, properties):
176
+ properties.enabled = True
177
+ properties.opt_level = "O0"
178
+ properties.cast_model_type = torch.float32
179
+ properties.patch_torch_functions = False
180
+ properties.keep_batchnorm_fp32 = None
181
+ properties.master_weights = False
182
+ properties.loss_scale = 1.0
183
+ # properties.fused_optimizer = False
184
+ # properties.enable_ddp_interop = False
185
+ return properties # modified in place so this isn't really necessary
186
+
187
+
188
+ opt_levels = {"O3": O3(),
189
+ "O2": O2(),
190
+ "O1": O1(),
191
+ "O0": O0()}
192
+
193
+
194
+ # allow user to directly pass Properties struct as well?
195
+ def initialize(
196
+ models,
197
+ optimizers=None,
198
+ enabled=True,
199
+ opt_level="O1",
200
+ cast_model_type=None,
201
+ patch_torch_functions=None,
202
+ keep_batchnorm_fp32=None,
203
+ master_weights=None,
204
+ loss_scale=None,
205
+ cast_model_outputs=None,
206
+ num_losses=1,
207
+ verbosity=1,
208
+ min_loss_scale=None,
209
+ max_loss_scale=2.**24
210
+ ):
211
+ """
212
+ Initialize your models, optimizers, and the Torch tensor and functional namespace according to the
213
+ chosen ``opt_level`` and overridden properties, if any.
214
+
215
+ ``amp.initialize`` should be called **after** you have finished
216
+ constructing your model(s) and
217
+ optimizer(s), but **before** you send your model through any DistributedDataParallel wrapper.
218
+ See `Distributed training`_ in the Imagenet example.
219
+
220
+ Currently, ``amp.initialize`` should only be called **once**,
221
+ although it can process an arbitrary number of
222
+ models and optimizers (see the corresponding `Advanced Amp Usage topic`_).
223
+ If you think your use case requires ``amp.initialize`` to be called more than once,
224
+ `let us know`_.
225
+
226
+ Any property keyword argument that is not ``None`` will be interpreted as a manual override.
227
+
228
+ To prevent having to rewrite anything else in your script, name the returned models/optimizers
229
+ to replace the passed models/optimizers, as in the code sample below.
230
+
231
+ Args:
232
+ models (torch.nn.Module or list of torch.nn.Modules): Models to modify/cast.
233
+ optimizers (optional, torch.optim.Optimizer or list of torch.optim.Optimizers): Optimizers to modify/cast.
234
+ REQUIRED for training, optional for inference.
235
+ enabled (bool, optional, default=True): If False, renders all Amp calls no-ops, so your script
236
+ should run as if Amp were not present.
237
+ opt_level (str, optional, default="O1"): Pure or mixed precision optimization level. Accepted values are
238
+ "O0", "O1", "O2", and "O3", explained in detail above.
239
+ cast_model_type (``torch.dtype``, optional, default=None): Optional property override, see
240
+ above.
241
+ patch_torch_functions (bool, optional, default=None): Optional property override.
242
+ keep_batchnorm_fp32 (bool or str, optional, default=None): Optional property override. If
243
+ passed as a string, must be the string "True" or "False".
244
+ master_weights (bool, optional, default=None): Optional property override.
245
+ loss_scale (float or str, optional, default=None): Optional property override. If passed as a string,
246
+ must be a string representing a number, e.g., "128.0", or the string "dynamic".
247
+ cast_model_outputs (torch.dtype, optional, default=None): Option to ensure that the outputs
248
+ of your model(s) are always cast to a particular type regardless of ``opt_level``.
249
+ num_losses (int, optional, default=1): Option to tell Amp in advance how many losses/backward
250
+ passes you plan to use. When used in conjunction with the ``loss_id`` argument to
251
+ ``amp.scale_loss``, enables Amp to use a different loss scale per loss/backward pass,
252
+ which can improve stability. See "Multiple models/optimizers/losses"
253
+ under `Advanced Amp Usage`_ for examples. If ``num_losses`` is left to 1, Amp will still
254
+ support multiple losses/backward passes, but use a single global loss scale
255
+ for all of them.
256
+ verbosity (int, default=1): Set to 0 to suppress Amp-related output.
257
+ min_loss_scale (float, default=None): Sets a floor for the loss scale values that can be chosen by dynamic
258
+ loss scaling. The default value of None means that no floor is imposed.
259
+ If dynamic loss scaling is not used, `min_loss_scale` is ignored.
260
+ max_loss_scale (float, default=2.**24): Sets a ceiling for the loss scale values that can be chosen by
261
+ dynamic loss scaling. If dynamic loss scaling is not used, `max_loss_scale` is ignored.
262
+
263
+ Returns:
264
+ Model(s) and optimizer(s) modified according to the ``opt_level``.
265
+ If either the ``models`` or ``optimizers`` args were lists, the corresponding return value will
266
+ also be a list.
267
+
268
+ Permissible invocations::
269
+
270
+ model, optim = amp.initialize(model, optim,...)
271
+ model, [optim1, optim2] = amp.initialize(model, [optim1, optim2],...)
272
+ [model1, model2], optim = amp.initialize([model1, model2], optim,...)
273
+ [model1, model2], [optim1, optim2] = amp.initialize([model1, model2], [optim1, optim2],...)
274
+
275
+ # This is not an exhaustive list of the cross product of options that are possible,
276
+ # just a set of examples.
277
+ model, optim = amp.initialize(model, optim, opt_level="O0")
278
+ model, optim = amp.initialize(model, optim, opt_level="O0", loss_scale="dynamic"|128.0|"128.0")
279
+
280
+ model, optim = amp.initialize(model, optim, opt_level="O1") # uses "loss_scale="dynamic" default
281
+ model, optim = amp.initialize(model, optim, opt_level="O1", loss_scale=128.0|"128.0")
282
+
283
+ model, optim = amp.initialize(model, optim, opt_level="O2") # uses "loss_scale="dynamic" default
284
+ model, optim = amp.initialize(model, optim, opt_level="O2", loss_scale=128.0|"128.0")
285
+ model, optim = amp.initialize(model, optim, opt_level="O2", keep_batchnorm_fp32=True|False|"True"|"False")
286
+
287
+ model, optim = amp.initialize(model, optim, opt_level="O3") # uses loss_scale=1.0 default
288
+ model, optim = amp.initialize(model, optim, opt_level="O3", loss_scale="dynamic"|128.0|"128.0")
289
+ model, optim = amp.initialize(model, optim, opt_level="O3", keep_batchnorm_fp32=True|False|"True"|"False")
290
+
291
+ The `Imagenet example`_ demonstrates live use of various opt_levels and overrides.
292
+
293
+ .. _`Distributed training`:
294
+ https://github.com/NVIDIA/apex/tree/master/examples/imagenet#distributed-training
295
+
296
+ .. _`Imagenet example`:
297
+ https://github.com/NVIDIA/apex/tree/master/examples/imagenet
298
+
299
+ .. _`Advanced Amp Usage`:
300
+ https://nvidia.github.io/apex/advanced.html
301
+
302
+ .. _`Advanced Amp Usage topic`:
303
+ https://nvidia.github.io/apex/advanced.html#multiple-models-optimizers-losses
304
+
305
+ .. _`let us know`:
306
+ https://github.com/NVIDIA/apex/issues
307
+ """
308
+ _amp_state.opt_properties = Properties()
309
+ _amp_state.verbosity = verbosity
310
+
311
+ if not enabled:
312
+ if optimizers is None:
313
+ return models
314
+ else:
315
+ return models, optimizers
316
+
317
+ if not torch.backends.cudnn.enabled:
318
+ raise RuntimeError(
319
+ "Amp requires torch.backends.cudnn.enabled = True")
320
+
321
+ if opt_level not in opt_levels:
322
+ raise RuntimeError(
323
+ "Unexpected optimization level {}. ".format(opt_level) +
324
+ "Options are 'O0', 'O1', 'O2', 'O3'. Note that in `O0`, `O1`, etc., the prefix O is the letter O, " +
325
+ "not the number zero.")
326
+ else:
327
+ _amp_state.opt_properties = opt_levels[opt_level](_amp_state.opt_properties)
328
+ maybe_print("Selected optimization level {}".format(opt_levels[opt_level].brief), True)
329
+ maybe_print("Defaults for this optimization level are:", True)
330
+ for k, v in _amp_state.opt_properties.options.items():
331
+ maybe_print("{:22} : {}".format(k, v), True)
332
+
333
+ _amp_state.min_loss_scale = min_loss_scale
334
+ _amp_state.max_loss_scale = max_loss_scale
335
+
336
+ maybe_print("Processing user overrides (additional kwargs that are not None)...", True)
337
+ # I chose to have the keyword arguments listed directly in the argument list,
338
+ # instead of **kwargs, so I can't use kwargs.items() here.
339
+ if enabled is not None:
340
+ _amp_state.opt_properties.enabled = enabled
341
+ if opt_level is not None:
342
+ _amp_state.opt_properties.opt_level = opt_level
343
+ if cast_model_type is not None:
344
+ _amp_state.opt_properties.cast_model_type = cast_model_type
345
+ if patch_torch_functions is not None:
346
+ _amp_state.opt_properties.patch_torch_functions = patch_torch_functions
347
+ if keep_batchnorm_fp32 is not None:
348
+ _amp_state.opt_properties.keep_batchnorm_fp32 = keep_batchnorm_fp32
349
+ if master_weights is not None:
350
+ _amp_state.opt_properties.master_weights = master_weights
351
+ if loss_scale is not None:
352
+ _amp_state.opt_properties.loss_scale = loss_scale
353
+
354
+ maybe_print("After processing overrides, optimization options are:", True)
355
+ for k, v in _amp_state.opt_properties.options.items():
356
+ maybe_print("{:22} : {}".format(k, v), True)
357
+
358
+ return _initialize(models, optimizers, _amp_state.opt_properties, num_losses, cast_model_outputs)
359
+
360
+
361
+ def state_dict(destination=None):
362
+ if destination is None:
363
+ destination = OrderedDict()
364
+
365
+ for idx, loss_scaler in enumerate(_amp_state.loss_scalers):
366
+ destination['loss_scaler%d' % idx] = {
367
+ 'loss_scale': loss_scaler.loss_scale(),
368
+ 'unskipped': loss_scaler._unskipped,
369
+ }
370
+ return destination
371
+
372
+
373
+ def load_state_dict(state_dict):
374
+ # Check if state_dict containes the same number of loss_scalers as current setup
375
+ if len(state_dict) != len(_amp_state.loss_scalers):
376
+ print('Warning: state_dict contains {} entries, while {} loss_scalers are used'.format(
377
+ len(state_dict), len(_amp_state.loss_scalers)))
378
+
379
+ state_dict = state_dict.copy()
380
+
381
+ nb_loss_scalers = len(_amp_state.loss_scalers)
382
+ unexpected_keys = []
383
+ # Initialize idx outside, since unexpected_keys will increase it if enumerate is used
384
+ idx = 0
385
+ for key in state_dict:
386
+ if 'loss_scaler' not in key:
387
+ unexpected_keys.append(key)
388
+ else:
389
+ if idx > (nb_loss_scalers - 1):
390
+ print('Skipping loss_scaler[{}], since num_losses was set to {}'.format(
391
+ idx, nb_loss_scalers))
392
+ break
393
+ _amp_state.loss_scalers[idx]._loss_scale = state_dict[key]['loss_scale']
394
+ _amp_state.loss_scalers[idx]._unskipped = state_dict[key]['unskipped']
395
+ idx += 1
396
+
397
+ if len(unexpected_keys) > 0:
398
+ raise RuntimeError(
399
+ 'Error(s) in loading state_dict. Unexpected key(s) in state_dict: {}. '.format(
400
+ ', '.join('"{}"'.format(k) for k in unexpected_keys)))
401
+
402
+
403
+ # TODO: is this necessary/useful?
404
+ # def check_option_consistency(enabled=True,
405
+ # opt_level=None,
406
+ # cast_model_type=None,
407
+ # patch_torch_functions=None,
408
+ # keep_batchnorm_fp32=None,
409
+ # master_weights=None,
410
+ # loss_scale=None,
411
+ # enable_ddp_interop=None,
412
+ # hard_override=False):
413
+ # """
414
+ # Utility function that enables users to quickly check if the option combination they intend
415
+ # to use is permitted. ``check_option_consistency`` does not require models or optimizers
416
+ # to be constructed, and can be called at any point in the script. ``check_option_consistency``
417
+ # is totally self-contained; it does not set any amp global state or affect anything outside
418
+ # of itself.
419
+ # """
420
+ #
421
+ # if not enabled:
422
+ # return
423
+ #
424
+ # if opt_level not in opt_levels:
425
+ # raise RuntimeError("Unexpected optimization level. Options are 'O0', 'O1', 'O2', 'O3'.")
426
+ # else:
427
+ # opt_properties = opt_levels[opt_level](Properties())
428
+ # print("Selected optimization level {}", opt_levels[opt_level].brief)
429
+ # print("Defaults for this optimization level are:")
430
+ # for k, v in opt_properties.options:
431
+ # print("{:22} : {}".format(k, v))
432
+ #
433
+ # print("Processing user overrides (additional kwargs that are not None)...")
434
+ # for k, v in kwargs:
435
+ # if k not in _amp_state.opt_properties.options:
436
+ # raise RuntimeError("Unexpected kwarg {}".format(k))
437
+ # if v is not None:
438
+ # setattr(opt_properties, k, v)
439
+ #
440
+ # print("After processing overrides, optimization options are:")
441
+ # for k, v in opt_properties.options:
442
+ # print("{:22} : {}".format(k, v))
apex/apex/amp/handle.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import warnings
3
+ import sys
4
+ import torch
5
+
6
+ from . import utils
7
+ from .opt import OptimWrapper
8
+ from .scaler import LossScaler
9
+ from ._amp_state import _amp_state, master_params, maybe_print
10
+
11
+ if torch.distributed.is_available():
12
+ from ..parallel.LARC import LARC
13
+
14
+
15
+ # There's no reason to expose the notion of a "handle". Everything can happen through amp.* calls.
16
+ @contextlib.contextmanager
17
+ def scale_loss(loss,
18
+ optimizers,
19
+ loss_id=0,
20
+ model=None,
21
+ delay_unscale=False,
22
+ delay_overflow_check=False):
23
+ """
24
+ On context manager entrance, creates ``scaled_loss = (loss.float())*current loss scale``.
25
+ ``scaled_loss`` is yielded so that the user can call ``scaled_loss.backward()``::
26
+
27
+ with amp.scale_loss(loss, optimizer) as scaled_loss:
28
+ scaled_loss.backward()
29
+
30
+ On context manager exit (if ``delay_unscale=False``), the gradients are checked for infs/NaNs
31
+ and unscaled, so that ``optimizer.step()`` can be called.
32
+
33
+ .. note::
34
+ If Amp is using explicit FP32 master params (which is the default for ``opt_level=O2``, and
35
+ can also be manually enabled by supplying ``master_weights=True`` to ``amp.initialize``)
36
+ any FP16 gradients are copied to FP32 master gradients before being unscaled.
37
+ ``optimizer.step()`` will then apply the unscaled master gradients to the master params.
38
+
39
+ .. warning::
40
+ If Amp is using explicit FP32 master params, only the FP32 master gradients will be
41
+ unscaled. The direct ``.grad`` attributes of any FP16
42
+ model params will remain scaled after context manager exit.
43
+ This subtlety affects gradient clipping. See "Gradient clipping" under
44
+ `Advanced Amp Usage`_ for best practices.
45
+
46
+ Args:
47
+ loss(Tensor): Typically a scalar Tensor. The ``scaled_loss`` that the context
48
+ manager yields is simply ``loss.float()*loss_scale``, so in principle
49
+ ``loss`` could have more than one element, as long as you call
50
+ ``backward()`` on ``scaled_loss`` appropriately within the context manager body.
51
+ optimizers: All optimizer(s) for which the current backward pass is creating gradients.
52
+ Must be an optimizer or list of optimizers returned from an earlier call
53
+ to ``amp.initialize``. For example use with multiple optimizers, see
54
+ "Multiple models/optimizers/losses" under `Advanced Amp Usage`_.
55
+ loss_id(int, optional, default=0): When used in conjunction with the ``num_losses`` argument
56
+ to ``amp.initialize``, enables Amp to use a different loss scale per loss. ``loss_id``
57
+ must be an integer between 0 and ``num_losses`` that tells Amp which loss is
58
+ being used for the current backward pass. See "Multiple models/optimizers/losses"
59
+ under `Advanced Amp Usage`_ for examples. If ``loss_id`` is left unspecified, Amp
60
+ will use the default global loss scaler for this backward pass.
61
+ model(torch.nn.Module, optional, default=None): Currently unused, reserved to enable future
62
+ optimizations.
63
+ delay_unscale(bool, optional, default=False): ``delay_unscale`` is never necessary, and
64
+ the default value of ``False`` is strongly recommended.
65
+ If ``True``, Amp will not unscale the gradients or perform model->master
66
+ gradient copies on context manager exit.
67
+ ``delay_unscale=True`` is a minor ninja performance optimization and can result
68
+ in weird gotchas (especially with multiple models/optimizers/losses),
69
+ so only use it if you know what you're doing.
70
+ "Gradient accumulation across iterations" under `Advanced Amp Usage`_
71
+ illustrates a situation where this CAN (but does not need to) be used.
72
+
73
+ .. warning::
74
+ If ``delay_unscale`` is ``True`` for a given backward pass, ``optimizer.step()`` cannot be
75
+ called yet after context manager exit, and must wait for another, later backward context
76
+ manager invocation with ``delay_unscale`` left to False.
77
+
78
+ .. _`Advanced Amp Usage`:
79
+ https://nvidia.github.io/apex/advanced.html
80
+ """
81
+ if not hasattr(_amp_state, "opt_properties"):
82
+ raise RuntimeError("Invoked 'with amp.scale_loss`, but internal Amp state has not been initialized. "
83
+ "model, optimizer = amp.initialize(model, optimizer, opt_level=...) must be called "
84
+ "before `with amp.scale_loss`.")
85
+
86
+ if not _amp_state.opt_properties.enabled:
87
+ yield loss
88
+ return
89
+
90
+ if isinstance(optimizers, torch.optim.Optimizer) or ('LARC' in globals() and isinstance(optimizers, LARC)):
91
+ optimizers = [optimizers]
92
+
93
+ loss_scaler = _amp_state.loss_scalers[loss_id]
94
+ loss_scale = loss_scaler.loss_scale()
95
+
96
+ if ((not _amp_state.opt_properties.master_weights)
97
+ and (not loss_scaler.dynamic)
98
+ and loss_scale == 1.0):
99
+ yield loss.float()
100
+ # Needing to drop the cache here as well is an ugly gotcha.
101
+ # But for now I think it's necessary to short-circuit.
102
+ # Probably ok to skip this if not delay_unscale
103
+ if _amp_state.opt_properties.patch_torch_functions:
104
+ _amp_state.handle._clear_cache()
105
+ return
106
+
107
+ if not delay_unscale:
108
+ if isinstance(optimizers, list):
109
+ for optimizer in optimizers:
110
+ if not optimizer._amp_stash.params_have_scaled_gradients:
111
+ optimizer._prepare_amp_backward()
112
+
113
+ yield (loss.float())*loss_scale
114
+
115
+ if delay_unscale:
116
+ for optimizer in optimizers:
117
+ optimizer._amp_stash.params_have_scaled_gradients = True
118
+ else:
119
+ # FusedSGD may take care of unscaling as part of their step() methods.
120
+ # if not isinstance(optimizers, FP16_Optimizer_for_fused):
121
+ loss_scaler.clear_overflow_state()
122
+ for optimizer in optimizers:
123
+ optimizer._post_amp_backward(loss_scaler)
124
+ optimizer._amp_stash.params_have_scaled_gradients = False
125
+ # For future fused optimizers that enable sync-free dynamic loss scaling,
126
+ # should_skip will always be False.
127
+ should_skip = False if delay_overflow_check else loss_scaler.update_scale()
128
+ if should_skip:
129
+ for optimizer in optimizers:
130
+ if not optimizer._amp_stash.already_patched:
131
+ # Close on loss_scaler and loss_id as well, to be safe. Probably not
132
+ # necessary because amp.scale_loss is already creating a temporary scope.
133
+ def patch_step(opt, loss_scaler, loss_id):
134
+ opt_step = opt.step
135
+ def skip_step(closure=None):
136
+ if closure is not None:
137
+ raise RuntimeError("Currently, Amp does not support closure use with optimizers.")
138
+ maybe_print(("Gradient overflow. Skipping step, loss scaler " +
139
+ "{} reducing loss scale to {}").format(loss_id,
140
+ loss_scaler.loss_scale()))
141
+ # TODO: I don't like the special casing for different optimizer implementations.
142
+ # Maybe skip should delegate to a method owned by the optimizers themselves.
143
+ if hasattr(opt._amp_stash, "all_fp32_from_fp16_params"):
144
+ # Clear the master grads that wouldn't be zeroed by model.zero_grad()
145
+ for param in opt._amp_stash.all_fp32_from_fp16_params:
146
+ param.grad = None
147
+ if hasattr(opt, "most_recent_scale"):
148
+ opt.most_recent_scale = 1.0
149
+ opt.scale_set_by_backward = False
150
+ opt.step = opt_step
151
+ opt._amp_stash.already_patched = False
152
+ return skip_step
153
+ optimizer.step = patch_step(optimizer, loss_scaler, loss_id)
154
+ optimizer._amp_stash.already_patched = True
155
+
156
+ # Probably ok to skip this if not delay_unscale
157
+ if _amp_state.opt_properties.patch_torch_functions:
158
+ _amp_state.handle._clear_cache()
159
+
160
+
161
+ # Free function version of AmpHandle.disable_casts, another step on the
162
+ # path to removing the concept of "AmpHandle"
163
+ @contextlib.contextmanager
164
+ def disable_casts():
165
+ _amp_state.handle._is_active = False
166
+ yield
167
+ _amp_state.handle._is_active = True
168
+
169
+
170
+ class AmpHandle(object):
171
+ def __init__(self, loss_scale="dynamic", enable_caching=True, verbose=False):
172
+ self._enable_caching = enable_caching
173
+ self._verbose = verbose
174
+ self._cache = dict()
175
+ self._default_scaler = LossScaler(loss_scale)
176
+ self._is_active = True
177
+ self._all_wrappers = []
178
+
179
+ def is_active(self):
180
+ return self._is_active
181
+
182
+ @contextlib.contextmanager
183
+ def _disable_casts(self):
184
+ self._is_active = False
185
+ yield
186
+ self._is_active = True
187
+
188
+ def wrap_optimizer(self, optimizer, num_loss=1):
189
+ self._default_scaler = None
190
+ return OptimWrapper(optimizer, self, num_loss)
191
+
192
+ @contextlib.contextmanager
193
+ def scale_loss(self, loss, optimizer):
194
+ raise RuntimeError("The old Amp API is no longer supported. Please move to the new API, "
195
+ "documented here: https://nvidia.github.io/apex/amp.html. Transition guide: "
196
+ "https://nvidia.github.io/apex/amp.html#transition-guide-for-old-api-users")
197
+
198
+ if not self.is_active():
199
+ yield loss
200
+ return
201
+
202
+ if self._default_scaler is None:
203
+ raise RuntimeError(
204
+ 'After calling `handle.wrap_optimizer()`, you must explicitly ' +
205
+ 'use `optimizer.scale_loss(loss)`.')
206
+
207
+ # TODO: this code block is duplicated here and `opt.py`. Unify.
208
+ loss_scale = self._default_scaler.loss_scale()
209
+ yield loss * loss_scale
210
+
211
+ self._default_scaler.clear_overflow_state()
212
+ self._default_scaler.unscale(
213
+ master_params(optimizer),
214
+ master_params(optimizer),
215
+ loss_scale)
216
+ should_skip = self._default_scaler.update_scale()
217
+ if should_skip:
218
+ optimizer_step = optimizer.step
219
+ def skip_step():
220
+ maybe_print('Gradient overflow, skipping update')
221
+ optimizer.step = optimizer_step
222
+ optimizer.step = skip_step
223
+
224
+ self._clear_cache()
225
+
226
+ def _clear_cache(self):
227
+ self._cache.clear()
228
+
229
+ # Experimental support for saving / restoring uncasted versions of functions
230
+ def _save_func(self, mod, fn, func):
231
+ self._all_wrappers.append((mod, fn, func))
232
+
233
+ def _deactivate(self):
234
+ for mod, fn, func in self._all_wrappers:
235
+ utils.set_func(mod, fn, func)
236
+ self._all_wrappers = []
237
+
238
+ @property
239
+ def has_cache(self):
240
+ return self._enable_caching
241
+
242
+ @property
243
+ def cache(self):
244
+ return self._cache
245
+
246
+ def remove_cache(self, param):
247
+ if self.has_cache and param in self.cache:
248
+ del self.cache[param]
249
+
250
+ @property
251
+ def verbose(self):
252
+ return self._verbose
253
+
254
+ class NoOpHandle(object):
255
+ def is_active(self):
256
+ return False
257
+
258
+ @contextlib.contextmanager
259
+ def _disable_casts(self):
260
+ yield
261
+
262
+ def wrap_optimizer(self, optimizer, num_loss=1):
263
+ return OptimWrapper(optimizer, self, num_loss)
264
+
265
+ @contextlib.contextmanager
266
+ def scale_loss(self, loss, optimizer):
267
+ yield loss
268
+
269
+ @property
270
+ def has_cache(self):
271
+ return False
272
+
273
+ @property
274
+ def verbose(self):
275
+ return False
276
+
277
+ def _clear_cache(self):
278
+ pass
279
+
280
+ def _deactivate(self):
281
+ pass
apex/apex/amp/lists/__init__.py ADDED
File without changes
apex/apex/amp/lists/functional_overrides.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # TODO: think about the following two. They do weird things.
3
+ # - torch.nn.utils.clip_grad (but it should always be fp32 anyway)
4
+ # - torch.nn.utils.weight_norm
5
+
6
+ # Notes:
7
+ # F.instance_norm uses batch_norm internally. Which correctly handles
8
+ # fp16 in/out with fp32 weights. So we shouldn't do anything for
9
+ # either of these.
10
+ # F.normalize calls `input.norm()` internally, so it's redundant, but
11
+ # kept here in case impl. changes.
12
+ # F.cosine_similarity is same: calls `x.norm()` internally.
13
+
14
+ import torch.nn.functional
15
+
16
+ MODULE = torch.nn.functional
17
+
18
+ FP16_FUNCS = [
19
+ 'conv1d',
20
+ 'conv2d',
21
+ 'conv3d',
22
+ 'conv_transpose1d',
23
+ 'conv_transpose2d',
24
+ 'conv_transpose3d',
25
+ 'conv_tbc', # Undocumented / maybe new?
26
+ 'linear',
27
+ ]
28
+
29
+ FP32_FUNCS = [
30
+
31
+ # Interpolation/Upsampling TODO: Remove for 1.2
32
+ 'interpolate',
33
+ 'grid_sample',
34
+
35
+ # Pointwise
36
+ 'softplus',
37
+ 'softmin',
38
+ 'log_softmax',
39
+ 'softmax',
40
+ 'gelu',
41
+
42
+ # Normalization
43
+ 'layer_norm',
44
+ 'group_norm',
45
+ 'local_response_norm',
46
+ 'normalize',
47
+ 'cosine_similarity',
48
+
49
+ # Loss functions
50
+ # TODO: which of these can be fp16?
51
+ 'poisson_nll_loss',
52
+ 'cosine_embedding_loss',
53
+ 'cross_entropy',
54
+ 'hinge_embedding_loss',
55
+ 'kl_div',
56
+ 'l1_loss',
57
+ 'mse_loss',
58
+ 'margin_ranking_loss',
59
+ 'multilabel_margin_loss',
60
+ 'multilabel_soft_margin_loss',
61
+ 'multi_margin_loss',
62
+ 'nll_loss',
63
+ 'binary_cross_entropy_with_logits',
64
+ 'smooth_l1_loss',
65
+ 'soft_margin_loss',
66
+ 'triplet_margin_loss',
67
+ 'ctc_loss'
68
+ ]
69
+
70
+ BANNED_FUNCS = [
71
+ ('binary_cross_entropy',
72
+ ("\namp does not work out-of-the-box with `F.binary_cross_entropy` or `torch.nn.BCELoss.` "
73
+ "It requires that the output of the previous function be already a FloatTensor. \n\n"
74
+ "Most models have a Sigmoid right before BCELoss. In that case, you can use\n"
75
+ " torch.nn.BCEWithLogitsLoss\nto combine Sigmoid+BCELoss into a single layer "
76
+ "that is compatible with amp.\nAnother option is to add\n"
77
+ " amp.register_float_function(torch, 'sigmoid')\nbefore calling `amp.init()`.\n"
78
+ "If you _really_ know what you are doing, you can disable this warning by passing "
79
+ "allow_banned=True to `amp.init()`."))
80
+ ]
apex/apex/amp/lists/tensor_overrides.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .. import compat
2
+ from . import torch_overrides
3
+
4
+ import importlib
5
+
6
+ import torch
7
+
8
+ # if compat.variable_is_tensor() and not compat.tensor_is_variable():
9
+ MODULE = torch.Tensor
10
+ # else:
11
+ # MODULE = torch.autograd.Variable
12
+
13
+
14
+ FP16_FUNCS = compat.filter_attrs(MODULE, [
15
+ '__matmul__',
16
+ ])
17
+
18
+ FP32_FUNCS = compat.filter_attrs(MODULE, [
19
+ '__ipow__',
20
+ '__pow__',
21
+ '__rpow__',
22
+
23
+ # Cast to fp32 before transfer to CPU
24
+ 'cpu',
25
+ ])
26
+
27
+ CASTS = compat.filter_attrs(MODULE, [
28
+ '__add__',
29
+ '__div__',
30
+ '__eq__',
31
+ '__ge__',
32
+ '__gt__',
33
+ '__iadd__',
34
+ '__idiv__',
35
+ '__imul__',
36
+ '__isub__',
37
+ '__itruediv__',
38
+ '__le__',
39
+ '__lt__',
40
+ '__mul__',
41
+ '__ne__',
42
+ '__radd__',
43
+ '__rdiv__',
44
+ '__rmul__',
45
+ '__rsub__',
46
+ '__rtruediv__',
47
+ '__sub__',
48
+ '__truediv__',
49
+ ])
50
+
51
+ # None of these, but here to make code cleaner.
52
+ SEQUENCE_CASTS = []
53
+
54
+ # We need to grab all the methods from torch_overrides and add them to
55
+ # the Tensor lists as well, as almost all methods are duplicated
56
+ # between `torch` and `torch.Tensor` (and check with `hasattr`,
57
+ # because a few random ones aren't defined on Tensor)
58
+ _self_mod = importlib.import_module(__name__)
59
+ for attrname in ['FP16_FUNCS', 'FP32_FUNCS', 'CASTS', 'SEQUENCE_CASTS']:
60
+ lst = getattr(_self_mod, attrname)
61
+ for fn in getattr(torch_overrides, attrname):
62
+ if hasattr(MODULE, fn):
63
+ lst.append(fn)
apex/apex/amp/lists/torch_overrides.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ from .. import utils
4
+
5
+ MODULE = torch
6
+
7
+ FP16_FUNCS = [
8
+ # Low level functions wrapped by torch.nn layers.
9
+ # The wrapper layers contain the weights which are then passed in as a parameter
10
+ # to these functions.
11
+ 'conv1d',
12
+ 'conv2d',
13
+ 'conv3d',
14
+ 'conv_transpose1d',
15
+ 'conv_transpose2d',
16
+ 'conv_transpose3d',
17
+ 'conv_tbc',
18
+ 'prelu',
19
+
20
+ # BLAS
21
+ 'addmm',
22
+ 'addmv',
23
+ 'addr',
24
+ 'matmul',
25
+ 'mm',
26
+ 'mv',
27
+ ]
28
+
29
+ FP32_FUNCS = [
30
+ # Pointwise
31
+ 'acos',
32
+ 'asin',
33
+ 'cosh',
34
+ 'erfinv',
35
+ 'exp',
36
+ 'expm1',
37
+ 'log',
38
+ 'log10',
39
+ 'log2',
40
+ 'reciprocal',
41
+ 'rsqrt',
42
+ 'sinh',
43
+ 'tan',
44
+
45
+ # Other math
46
+ 'pow',
47
+
48
+ # Reduction
49
+ 'cumprod',
50
+ 'cumsum',
51
+ 'dist',
52
+ # 'mean',
53
+ 'norm',
54
+ 'prod',
55
+ 'std',
56
+ 'sum',
57
+ 'var',
58
+
59
+ # Misc
60
+ 'renorm'
61
+ ]
62
+
63
+ version_strings = torch.__version__.split('.')
64
+ version_major = version_strings[0]
65
+ version_minor = version_strings[1]
66
+ version_num = float(version_major + "." + version_minor)
67
+ # Before torch 1.1, mean must be blacklisted.
68
+ if version_num < 1.1:
69
+ FP32_FUNCS.append('mean')
70
+
71
+ # Before CUDA 9.1, batched matmul was missing fast FP16 kernels. We
72
+ # check the CUDA version -- if at least 9.1, then put the bmm
73
+ # functions on the fp16 list. Otherwise, put them on the fp32 list.
74
+ _bmms = ['addbmm',
75
+ 'baddbmm',
76
+ 'bmm']
77
+
78
+ if utils.is_cuda_enabled():
79
+ # workaround https://github.com/facebookresearch/maskrcnn-benchmark/issues/802
80
+ if utils.get_cuda_version() >= (9, 1, 0):
81
+ FP16_FUNCS.extend(_bmms)
82
+ else:
83
+ FP32_FUNCS.extend(_bmms)
84
+
85
+ # Multi-tensor fns that may need type promotion
86
+ CASTS = [
87
+ # Multi-tensor math
88
+ 'addcdiv',
89
+ 'addcmul',
90
+ 'atan2',
91
+ 'cross',
92
+ 'bilinear',
93
+ 'dot',
94
+
95
+ # Element-wise _or_ tensor-wise math
96
+ 'add',
97
+ 'div',
98
+ 'mul',
99
+
100
+ # Comparison
101
+ 'eq',
102
+ 'equal',
103
+ 'ge',
104
+ 'gt',
105
+ 'le',
106
+ 'lt',
107
+ 'ne'
108
+ ]
109
+
110
+ # Functions that take sequence arguments. We need to inspect the whole
111
+ # sequence and cast to the widest type.
112
+ SEQUENCE_CASTS = [
113
+ 'cat',
114
+ 'stack'
115
+ ]
apex/apex/amp/opt.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import warnings
3
+
4
+ from .scaler import LossScaler, master_params
5
+ from ._amp_state import maybe_print
6
+
7
+ import numpy as np
8
+
9
+ class OptimWrapper(object):
10
+ def __init__(self, optimizer, amp_handle, num_loss):
11
+ self._optimizer = optimizer
12
+ self._amp_handle = amp_handle
13
+ self._num_loss = num_loss
14
+ self._loss_idx = 0
15
+ self._skip_next = [False] * num_loss
16
+ self._loss_scaler = [LossScaler('dynamic') for _ in range(num_loss)]
17
+
18
+ @contextlib.contextmanager
19
+ def scale_loss(self, loss):
20
+ if not self._amp_handle.is_active():
21
+ yield loss
22
+ return
23
+
24
+ # When there are multiple losses per-optimizer, we need
25
+ # to save out current grad accumulation, since we won't be
26
+ # able to unscale this particulare loss once the grads are
27
+ # all mixed together.
28
+ cached_grads = []
29
+ if self._loss_idx > 0:
30
+ for p in master_params(self._optimizer):
31
+ if p.grad is not None:
32
+ cached_grads.append(p.grad.data.detach().clone())
33
+ else:
34
+ cached_grads.append(None)
35
+ self._optimizer.zero_grad()
36
+
37
+ loss_scale = self._cur_loss_scaler().loss_scale()
38
+ yield loss * loss_scale
39
+
40
+ self._cur_loss_scaler().clear_overflow_state()
41
+ self._cur_loss_scaler().unscale(
42
+ master_params(self._optimizer),
43
+ master_params(self._optimizer),
44
+ loss_scale)
45
+ self._skip_next[self._loss_idx] = self._cur_loss_scaler().update_scale()
46
+ self._loss_idx += 1
47
+
48
+ if len(cached_grads) > 0:
49
+ for p, cached_grad in zip(master_params(self._optimizer),
50
+ cached_grads):
51
+ if cached_grad is not None:
52
+ p.grad.data.add_(cached_grad)
53
+ cached_grads = []
54
+
55
+ def _cur_loss_scaler(self):
56
+ assert 0 <= self._loss_idx < self._num_loss
57
+ return self._loss_scaler[self._loss_idx]
58
+
59
+ def step(self, closure=None):
60
+ if not self._amp_handle.is_active():
61
+ return self._optimizer.step(closure=closure)
62
+
63
+ self._loss_idx = 0
64
+
65
+ for group in self._optimizer.param_groups:
66
+ for p in group['params']:
67
+ self._amp_handle.remove_cache(p)
68
+
69
+ if closure is not None:
70
+ raise NotImplementedError(
71
+ 'The `closure` argument is unsupported by the amp ' +
72
+ 'optimizer wrapper.')
73
+ if any(self._skip_next):
74
+ maybe_print('Gradient overflow, skipping update')
75
+ self._skip_next = [False] * self._num_loss
76
+ else:
77
+ return self._optimizer.step(closure=closure)
78
+
79
+ # Forward any attribute lookups
80
+ def __getattr__(self, attr):
81
+ return getattr(self._optimizer, attr)
82
+
83
+ # Forward all torch.optim.Optimizer methods
84
+ def __getstate__(self):
85
+ return self._optimizer.__getstate__()
86
+
87
+ def __setstate__(self):
88
+ return self._optimizer.__setstate__()
89
+
90
+ def __repr__(self):
91
+ return self._optimizer.__repr__()
92
+
93
+ def state_dict(self):
94
+ return self._optimizer.state_dict()
95
+
96
+ def load_state_dict(self, state_dict):
97
+ return self._optimizer.load_state_dict(state_dict)
98
+
99
+ def zero_grad(self):
100
+ return self._optimizer.zero_grad()
101
+
102
+ def add_param_group(self, param_group):
103
+ return self._optimizer.add_param_group(param_group)
apex/apex/amp/rnn_compat.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from . import utils, wrap
2
+
3
+ import torch
4
+ _VF = torch._C._VariableFunctions
5
+ RNN_NAMES = ['rnn_relu', 'rnn_tanh', 'gru', 'lstm']
6
+
7
+ def _gen_VF_wrapper(name):
8
+ def wrapper(*args, **kwargs):
9
+ return getattr(_VF, name)(*args, **kwargs)
10
+ return wrapper
11
+
12
+ # Some python magic to generate an object that has the rnn cell functions
13
+ # defined on it, all of which call into corresponding _VF version.
14
+ # Intended to patch torch.nn.modules.rnn._VF (aka, the ref named "_VF"
15
+ # imported at module scope within torch.nn.modules.rnn). This should
16
+ # not affect third-party importers of _VF.py.
17
+ class VariableFunctionsShim(object):
18
+ def __init__(self):
19
+ for name in RNN_NAMES:
20
+ for suffix in ['', '_cell']:
21
+ fn_name = name + suffix
22
+ setattr(self, fn_name, _gen_VF_wrapper(fn_name))
23
+
24
+ def has_old_rnns():
25
+ try:
26
+ torch.nn.backends.thnn.backend.LSTMCell
27
+ return True
28
+ except:
29
+ return False
30
+
31
+ def whitelist_rnn_cells(handle, verbose):
32
+ # Different module + function names in old/new RNN cases
33
+ if has_old_rnns():
34
+ fn_names = ['RNNReLUCell', 'RNNTanhCell', 'LSTMCell', 'GRUCell']
35
+ mod = torch.nn.backends.thnn.backend
36
+ else:
37
+ fn_names = [x + '_cell' for x in RNN_NAMES]
38
+ mod = torch.nn.modules.rnn._VF
39
+ assert isinstance(mod, VariableFunctionsShim)
40
+
41
+ # Insert casts on cell functions
42
+ for fn in fn_names:
43
+ wrap.cached_cast(mod, fn, utils.maybe_half, handle,
44
+ try_caching=True, verbose=verbose)
45
+
46
+ if has_old_rnns():
47
+ # Special handling of `backward` for fused gru / lstm:
48
+ # The `backward` method calls Tensor.sum() (blacklist) internally,
49
+ # and then the resulting grad_input has the wrong type.
50
+ # TODO: where else is this a problem?
51
+ for rnn_type in ['GRUFused', 'LSTMFused']:
52
+ mod = getattr(torch.nn._functions.thnn.rnnFusedPointwise, rnn_type)
53
+ wrap.disable_casts(mod, 'backward', handle)
apex/apex/amp/scaler.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from ..multi_tensor_apply import multi_tensor_applier
3
+ from ._amp_state import _amp_state, master_params, maybe_print
4
+ from itertools import product
5
+
6
+ def scale_check_overflow_python(model_grad, master_grad, scale, check_overflow=False):
7
+ # Exception handling for 18.04 compatibility
8
+ if check_overflow:
9
+ cpu_sum = float(model_grad.float().sum())
10
+ if cpu_sum == float('inf') or cpu_sum == -float('inf') or cpu_sum != cpu_sum:
11
+ return True
12
+
13
+ if master_grad is not model_grad: # copy_ probably internally short-circuits this
14
+ master_grad.copy_(model_grad)
15
+ if scale != 1.0:
16
+ master_grad.mul_(scale)
17
+ return False
18
+
19
+ def axpby_check_overflow_python(model_grad, stashed_grad, master_grad, a, b, check_overflow=False):
20
+ # Exception handling for 18.04 compatibility
21
+ if check_overflow:
22
+ cpu_sum = float(model_grad.float().sum())
23
+ if cpu_sum == float('inf') or cpu_sum == -float('inf') or cpu_sum != cpu_sum:
24
+ return True
25
+
26
+ # if master_grad is not model_grad: # copy_ probably internally short-circuits this
27
+ # master_grad.copy_(model_grad)
28
+ assert stashed_grad.dtype == master_grad.dtype
29
+ converted_model_grad = model_grad.data.to(master_grad.dtype)
30
+ master_grad.data = a*converted_model_grad.data + b*stashed_grad.data
31
+ return False
32
+
33
+ class LossScaler(object):
34
+ warned_no_fused_kernel = False
35
+ warned_unscaling_non_fp32_grad = False
36
+ has_fused_kernel = False
37
+
38
+ def __init__(self,
39
+ loss_scale,
40
+ init_scale=2.**16,
41
+ scale_factor=2.,
42
+ scale_window=2000,
43
+ min_loss_scale=None,
44
+ max_loss_scale=2.**24):
45
+ if loss_scale == "dynamic":
46
+ self.dynamic = True
47
+ self._loss_scale = min(max_loss_scale, init_scale)
48
+ else:
49
+ self.dynamic = False
50
+ self._loss_scale = loss_scale
51
+ self._max_loss_scale = max_loss_scale
52
+ self._min_loss_scale = min_loss_scale
53
+ self._scale_seq_len = scale_window
54
+ self._unskipped = 0
55
+ self._has_overflow = False
56
+ self._overflow_buf = torch.cuda.IntTensor([0])
57
+ if multi_tensor_applier.available:
58
+ import amp_C
59
+ LossScaler.has_fused_kernel = multi_tensor_applier.available
60
+ LossScaler.multi_tensor_scale_cuda = amp_C.multi_tensor_scale
61
+ LossScaler.multi_tensor_axpby_cuda = amp_C.multi_tensor_axpby
62
+ else:
63
+ if not LossScaler.warned_no_fused_kernel:
64
+ maybe_print(
65
+ "Warning: multi_tensor_applier fused unscale kernel is unavailable, "
66
+ "possibly because apex was installed without --cuda_ext --cpp_ext. "
67
+ "Using Python fallback. Original ImportError was: " +
68
+ repr(multi_tensor_applier.import_err),
69
+ True)
70
+ LossScaler.has_fused_kernel = False
71
+ LossScaler.warned_no_fused_kernel = True
72
+
73
+ def loss_scale(self):
74
+ return self._loss_scale
75
+
76
+ def unscale_python(self, model_grads, master_grads, scale):
77
+ for model, master in zip(model_grads, master_grads):
78
+ if model is not None:
79
+ if not LossScaler.warned_unscaling_non_fp32_grad:
80
+ if master.dtype != torch.float32:
81
+ maybe_print(
82
+ "Attempting to unscale a grad with type {} ".format(master.type()) +
83
+ "Unscaling non-fp32 grads may indicate an error. "
84
+ "When using Amp, you don't need to call .half() on your model.")
85
+ LossScaler.warned_unscaling_non_fp32_grad = True
86
+ self._has_overflow = scale_check_overflow_python(model,
87
+ master,
88
+ 1./scale,
89
+ self.dynamic)
90
+ if self._has_overflow and self.dynamic:
91
+ break
92
+
93
+ # unused_scale keeps some of the old API alive for hopefully a short time.
94
+ def unscale(self, model_grads, master_grads, unused_scale, models_are_masters=False, scale_override=None):
95
+ if self._has_overflow:
96
+ return
97
+
98
+ scale = self._loss_scale
99
+ if scale_override is not None:
100
+ scale = scale_override
101
+
102
+ if scale == 1.0 and models_are_masters and not self.dynamic:
103
+ return
104
+
105
+ if LossScaler.has_fused_kernel:
106
+ # if (not LossScaler.warned_unscaling_non_fp32_grad
107
+ # and master_grads[0].dtype == torch.float16):
108
+ # print("Warning: unscaling grads that are not FP32. "
109
+ # "Unscaling non-fp32 grads may indicate an error. "
110
+ # "When using Amp, you don't need to call .half() on your model.")
111
+ # # Setting this to True unconditionally allows the possibility of an escape
112
+ # # if never-before-seen non-fp32 grads are created in some later iteration.
113
+ # LossScaler.warned_unscaling_non_fp32_grad = True
114
+ multi_tensor_applier(LossScaler.multi_tensor_scale_cuda,
115
+ self._overflow_buf,
116
+ [model_grads, master_grads],
117
+ 1./scale)
118
+ else:
119
+ self.unscale_python(model_grads, master_grads, scale)
120
+
121
+ # Defer to update_scale
122
+ # If the fused kernel is available, we only need one D2H memcopy and sync.
123
+ # if LossScaler.has_fused_kernel and self.dynamic and not self._has_overflow:
124
+ # self._has_overflow = self._overflow_buf.item()
125
+
126
+ def unscale_with_stashed_python(self,
127
+ model_grads,
128
+ stashed_master_grads,
129
+ master_grads,
130
+ a,
131
+ b):
132
+ for model, stashed, master in zip(model_grads, stashed_master_grads, master_grads):
133
+ if model is None and stashed is None:
134
+ continue
135
+ else:
136
+ if not LossScaler.warned_unscaling_non_fp32_grad:
137
+ if master.dtype != torch.float32:
138
+ maybe_print(
139
+ "Attempting to unscale a grad with type {} ".format(master.type()) +
140
+ "Unscaling non-fp32 grads may indicate an error. "
141
+ "When using Amp, you don't need to call .half() on your model.")
142
+ LossScaler.warned_unscaling_non_fp32_grad = True
143
+ self._has_overflow = axpby_check_overflow_python(model,
144
+ stashed,
145
+ master,
146
+ a,
147
+ b,
148
+ self.dynamic)
149
+ if self._has_overflow and self.dynamic:
150
+ break
151
+
152
+ def unscale_with_stashed(self,
153
+ model_grads,
154
+ stashed_master_grads,
155
+ master_grads,
156
+ scale_override=None):
157
+ if self._has_overflow:
158
+ return
159
+
160
+ grads_have_scale, stashed_have_scale, out_scale = self._loss_scale, 1.0, 1.0
161
+ if scale_override is not None:
162
+ grads_have_scale, stashed_have_scale, out_scale = scale_override
163
+
164
+ if LossScaler.has_fused_kernel:
165
+ if (not LossScaler.warned_unscaling_non_fp32_grad
166
+ and master_grads[0].dtype == torch.float16):
167
+ print("Warning: unscaling grads that are not FP32. "
168
+ "Unscaling non-fp32 grads may indicate an error. "
169
+ "When using Amp, you don't need to call .half() on your model.")
170
+ # Setting this to True unconditionally allows the possibility of an escape
171
+ # if never-before-seen non-fp32 grads are created in some later iteration.
172
+ LossScaler.warned_unscaling_non_fp32_grad = True
173
+ multi_tensor_applier(LossScaler.multi_tensor_axpby_cuda,
174
+ self._overflow_buf,
175
+ [model_grads, stashed_master_grads, master_grads],
176
+ out_scale/grads_have_scale, # 1./scale,
177
+ out_scale/stashed_have_scale, # 1.0,
178
+ 0) # check only arg 0, aka the incoming model grads, for infs
179
+ else:
180
+ self.unscale_with_stashed_python(model_grads,
181
+ stashed_master_grads,
182
+ master_grads,
183
+ out_scale/grads_have_scale,
184
+ out_scale/stashed_have_scale)
185
+
186
+ # Defer to update_scale
187
+ # If the fused kernel is available, we only need one D2H memcopy and sync.
188
+ # if LossScaler.has_fused_kernel and self.dynamic and not self._has_overflow:
189
+ # self._has_overflow = self._overflow_buf.item()
190
+
191
+ def clear_overflow_state(self):
192
+ self._has_overflow = False
193
+ if self.has_fused_kernel:
194
+ self._overflow_buf.zero_()
195
+
196
+ # Separate so unscale() can be called more that once before updating.
197
+ def update_scale(self):
198
+ # If the fused kernel is available, we only need one D2H memcopy and sync.
199
+ if LossScaler.has_fused_kernel and self.dynamic and not self._has_overflow:
200
+ self._has_overflow = self._overflow_buf.item()
201
+
202
+ if self._has_overflow and self.dynamic:
203
+ should_skip = True
204
+ if(self._min_loss_scale):
205
+ self._loss_scale = max(self._min_loss_scale, self._loss_scale/2.)
206
+ else:
207
+ self._loss_scale = self._loss_scale/2.
208
+ self._unskipped = 0
209
+ else:
210
+ should_skip = False
211
+ self._unskipped += 1
212
+
213
+ if self._unskipped == self._scale_seq_len and self.dynamic:
214
+ self._loss_scale = min(self._max_loss_scale, self._loss_scale*2.)
215
+ self._unskipped = 0
216
+
217
+ return should_skip
apex/apex/amp/utils.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from . import compat
2
+
3
+ import functools
4
+ import itertools
5
+
6
+ import torch
7
+
8
+ def is_cuda_enabled():
9
+ return torch.version.cuda is not None
10
+
11
+ def get_cuda_version():
12
+ return tuple(int(x) for x in torch.version.cuda.split('.'))
13
+
14
+ def is_fp_tensor(x):
15
+ if is_nested(x):
16
+ # Fast-fail version of all(is_fp_tensor)
17
+ for y in x:
18
+ if not is_fp_tensor(y):
19
+ return False
20
+ return True
21
+ return compat.is_tensor_like(x) and compat.is_floating_point(x)
22
+
23
+ def is_nested(x):
24
+ return isinstance(x, tuple) or isinstance(x, list)
25
+
26
+ def should_cache(x):
27
+ if is_nested(x):
28
+ # Fast-fail version of all(should_cache)
29
+ for y in x:
30
+ if not should_cache(y):
31
+ return False
32
+ return True
33
+ return isinstance(x, torch.nn.parameter.Parameter) and \
34
+ type_string(x) == 'FloatTensor'
35
+
36
+ def collect_fp_tensor_types(args, kwargs):
37
+ def collect_types(x, types):
38
+ if is_nested(x):
39
+ for y in x:
40
+ collect_types(y, types)
41
+ else:
42
+ types.add(type_string(x))
43
+
44
+ all_args = itertools.chain(args, kwargs.values())
45
+ types = set()
46
+ for x in all_args:
47
+ if is_fp_tensor(x):
48
+ collect_types(x, types)
49
+ return types
50
+
51
+ def type_string(x):
52
+ return x.type().split('.')[-1]
53
+
54
+ def maybe_half(x, name='', verbose=False):
55
+ if is_nested(x):
56
+ return type(x)([maybe_half(y) for y in x])
57
+
58
+ if not x.is_cuda or type_string(x) == 'HalfTensor':
59
+ return x
60
+ else:
61
+ if verbose:
62
+ print('Float->Half ({})'.format(name))
63
+ return x.half()
64
+
65
+ def maybe_float(x, name='', verbose=False):
66
+ if is_nested(x):
67
+ return type(x)([maybe_float(y) for y in x])
68
+
69
+ if not x.is_cuda or type_string(x) == 'FloatTensor':
70
+ return x
71
+ else:
72
+ if verbose:
73
+ print('Half->Float ({})'.format(name))
74
+ return x.float()
75
+
76
+ # NB: returneds casted `args`, mutates `kwargs` in-place
77
+ def casted_args(cast_fn, args, kwargs):
78
+ new_args = []
79
+ for x in args:
80
+ if is_fp_tensor(x):
81
+ new_args.append(cast_fn(x))
82
+ else:
83
+ new_args.append(x)
84
+ for k in kwargs:
85
+ val = kwargs[k]
86
+ if is_fp_tensor(val):
87
+ kwargs[k] = cast_fn(val)
88
+ return new_args
89
+
90
+ def cached_cast(cast_fn, x, cache):
91
+ if is_nested(x):
92
+ return type(x)([cached_cast(y) for y in x])
93
+ if x in cache:
94
+ cached_x = cache[x]
95
+ if x.requires_grad and cached_x.requires_grad:
96
+ # Make sure x is actually cached_x's autograd parent.
97
+ if cached_x.grad_fn.next_functions[1][0].variable is not x:
98
+ raise RuntimeError("x and cache[x] both require grad, but x is not "
99
+ "cache[x]'s parent. This is likely an error.")
100
+ # During eval, it's possible to end up caching casted weights with
101
+ # requires_grad=False. On the next training iter, if cached_x is found
102
+ # and reused from the cache, it will not actually have x as its parent.
103
+ # Therefore, we choose to invalidate the cache (and force refreshing the cast)
104
+ # if x.requires_grad and cached_x.requires_grad do not match.
105
+ #
106
+ # During eval (i.e. running under with torch.no_grad()) the invalidation
107
+ # check would cause the cached value to be dropped every time, because
108
+ # cached_x would always be created with requires_grad=False, while x would
109
+ # still have requires_grad=True. This would render the cache effectively
110
+ # useless during eval. Therefore, if we are running under the no_grad()
111
+ # context manager (torch.is_grad_enabled=False) we elide the invalidation
112
+ # check, and use the cached value even though its requires_grad flag doesn't
113
+ # match. During eval, we don't care that there's no autograd-graph
114
+ # connection between x and cached_x.
115
+ if torch.is_grad_enabled() and x.requires_grad != cached_x.requires_grad:
116
+ del cache[x]
117
+ else:
118
+ return cached_x
119
+
120
+ casted_x = cast_fn(x)
121
+ cache[x] = casted_x
122
+ return casted_x
123
+
124
+ def verbosify(cast_fn, fn_name, verbose):
125
+ if verbose:
126
+ return functools.partial(cast_fn, name=fn_name, verbose=verbose)
127
+ else:
128
+ return cast_fn
129
+
130
+ def as_inplace(fns):
131
+ for x in fns:
132
+ yield x + '_'
133
+
134
+ def has_func(mod, fn):
135
+ if isinstance(mod, dict):
136
+ return fn in mod
137
+ else:
138
+ return hasattr(mod, fn)
139
+
140
+ def get_func(mod, fn):
141
+ if isinstance(mod, dict):
142
+ return mod[fn]
143
+ else:
144
+ return getattr(mod, fn)
145
+
146
+ def set_func(mod, fn, new_fn):
147
+ if isinstance(mod, dict):
148
+ mod[fn] = new_fn
149
+ else:
150
+ setattr(mod, fn, new_fn)
151
+
152
+ def set_func_save(handle, mod, fn, new_fn):
153
+ cur_fn = get_func(mod, fn)
154
+ handle._save_func(mod, fn, cur_fn)
155
+ set_func(mod, fn, new_fn)
156
+
157
+ # A couple problems get solved here:
158
+ # - The flat_weight buffer is disconnected from autograd graph,
159
+ # so the fp16 weights need to be derived from the input weights
160
+ # to this forward call, not the flat buffer.
161
+ # - The ordering of weights in the flat buffer is...idiosyncratic.
162
+ # First problem is solved with combination of set_ (to set up
163
+ # correct storage) and copy_ (so the fp16 weight derives from the
164
+ # fp32 one in autograd.
165
+ # Second is solved by doing ptr arithmetic on the fp32 weights
166
+ # to derive the correct offset.
167
+ #
168
+ # TODO: maybe this should actually use
169
+ # `torch._cudnn_rnn_flatten_weight`? But then I need to call
170
+ # on first iter and cache the right offsets. Ugh.
171
+ def synthesize_flattened_rnn_weights(fp32_weights,
172
+ fp16_flat_tensor,
173
+ rnn_fn='',
174
+ verbose=False):
175
+ fp16_weights = []
176
+ fp32_base_ptr = fp32_weights[0][0].data_ptr()
177
+ for layer_weights in fp32_weights:
178
+ fp16_layer_weights = []
179
+ for w_fp32 in layer_weights:
180
+ w_fp16 = w_fp32.new().half()
181
+ offset = (w_fp32.data_ptr() - fp32_base_ptr) // w_fp32.element_size()
182
+ w_fp16.set_(fp16_flat_tensor.storage(),
183
+ offset,
184
+ w_fp32.shape)
185
+ w_fp16.copy_(w_fp32)
186
+ if verbose:
187
+ print('Float->Half ({})'.format(rnn_fn))
188
+ fp16_layer_weights.append(w_fp16)
189
+ fp16_weights.append(fp16_layer_weights)
190
+ return fp16_weights
191
+
192
+ # Roughly same as above, just the `fp32_weights` aren't nested.
193
+ # Code kept separate for readability.
194
+ def new_synthesize_flattened_rnn_weights(fp32_weights,
195
+ fp16_flat_tensor,
196
+ rnn_fn='',
197
+ verbose=False):
198
+ fp16_weights = []
199
+ fp32_base_ptr = fp32_weights[0].data_ptr()
200
+ for w_fp32 in fp32_weights:
201
+ w_fp16 = w_fp32.new().half()
202
+ offset = (w_fp32.data_ptr() - fp32_base_ptr) // w_fp32.element_size()
203
+ w_fp16.set_(fp16_flat_tensor.storage(),
204
+ offset,
205
+ w_fp32.shape)
206
+ w_fp16.copy_(w_fp32)
207
+ if verbose:
208
+ print('Float->Half ({})'.format(rnn_fn))
209
+ fp16_weights.append(w_fp16)
210
+ return fp16_weights
apex/apex/amp/wrap.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from . import compat
2
+ from . import utils
3
+ from ._amp_state import _amp_state
4
+ from . import rnn_compat
5
+
6
+ import functools
7
+
8
+ import torch
9
+
10
+ def make_cast_wrapper(orig_fn, cast_fn, handle,
11
+ try_caching=False):
12
+ @functools.wraps(orig_fn)
13
+ def wrapper(*args, **kwargs):
14
+ if not handle.is_active():
15
+ return orig_fn(*args, **kwargs)
16
+
17
+ if try_caching and handle.has_cache:
18
+ args = list(args)
19
+ for i in range(len(args)):
20
+ if utils.should_cache(args[i]):
21
+ args[i] = utils.cached_cast(cast_fn, args[i], handle.cache)
22
+ for k in kwargs:
23
+ if utils.should_cache(kwargs[k]):
24
+ kwargs[k] = utils.cached_cast(cast_fn, kwargs[k], handle.cache)
25
+ new_args = utils.casted_args(cast_fn,
26
+ args,
27
+ kwargs)
28
+ return orig_fn(*new_args, **kwargs)
29
+ return wrapper
30
+
31
+ def cached_cast(mod, fn, cast_fn, handle,
32
+ try_caching=False, verbose=False):
33
+ if not utils.has_func(mod, fn):
34
+ return
35
+
36
+ orig_fn = utils.get_func(mod, fn)
37
+ cast_fn = utils.verbosify(cast_fn, fn, verbose)
38
+ wrapper = make_cast_wrapper(orig_fn, cast_fn, handle, try_caching)
39
+ utils.set_func_save(handle, mod, fn, wrapper)
40
+
41
+ # `handle` arg is unused, but simplifies API to make `make_cast_wrapper`
42
+ # Annoyingly, make_promote_wrapper still uses the global handle. Once everyone
43
+ # is on the new API and I am free to get rid of handle, I can clean this up.
44
+ def make_promote_wrapper(orig_fn, cast_fn, handle=None):
45
+ @functools.wraps(orig_fn)
46
+ def wrapper(*args, **kwargs):
47
+ if not _amp_state.handle.is_active():
48
+ return orig_fn(*args, **kwargs)
49
+
50
+ types = utils.collect_fp_tensor_types(args, kwargs)
51
+
52
+ if len(types) <= 1:
53
+ return orig_fn(*args, **kwargs)
54
+ elif len(types) == 2 and types == set(['HalfTensor', 'FloatTensor']):
55
+ new_args = utils.casted_args(cast_fn,
56
+ args,
57
+ kwargs)
58
+ return orig_fn(*new_args, **kwargs)
59
+ else:
60
+ raise NotImplementedError('Do not know how to handle ' +
61
+ 'these types to promote: {}'
62
+ .format(types))
63
+ return wrapper
64
+
65
+ def promote(mod, fn, handle, verbose=False):
66
+ orig_fn = utils.get_func(mod, fn)
67
+ maybe_float = utils.verbosify(utils.maybe_float, fn, verbose)
68
+ wrapper = make_promote_wrapper(orig_fn, maybe_float)
69
+ utils.set_func_save(handle, mod, fn, wrapper)
70
+
71
+ def sequence_promote(mod, fn, handle, verbose=False):
72
+ orig_fn = utils.get_func(mod, fn)
73
+ maybe_float = utils.verbosify(utils.maybe_float, fn, verbose)
74
+ @functools.wraps(orig_fn)
75
+ def wrapper(seq, *args, **kwargs):
76
+ if not _amp_state.handle.is_active():
77
+ return orig_fn(seq, *args, **kwargs)
78
+
79
+ types = set([utils.type_string(x) for x in seq])
80
+ if len(types) <= 1:
81
+ return orig_fn(seq, *args, **kwargs)
82
+ elif types == set(['HalfTensor', 'FloatTensor']):
83
+ cast_seq = utils.casted_args(maybe_float,
84
+ seq, {})
85
+ return orig_fn(cast_seq, *args, **kwargs)
86
+ else:
87
+ # TODO: other mixed-type cases aren't due to amp.
88
+ # Just pass through?
89
+ return orig_fn(seq, *args, **kwargs)
90
+ utils.set_func_save(handle, mod, fn, wrapper)
91
+
92
+ def promote_match_arg0(mod, fn, handle, verbose=False):
93
+ if not utils.has_func(mod, fn):
94
+ return
95
+
96
+ orig_fn = utils.get_func(mod, fn)
97
+ @functools.wraps(orig_fn)
98
+ def wrapper(arg0, *args, **kwargs):
99
+ assert compat.is_tensor_like(arg0)
100
+ if not _amp_state.handle.is_active():
101
+ return orig_fn(arg0, *args, **kwargs)
102
+
103
+ if utils.type_string(arg0) == 'HalfTensor':
104
+ cast_fn = utils.maybe_half
105
+ elif utils.type_string(arg0) == 'FloatTensor':
106
+ cast_fn = utils.maybe_float
107
+ else:
108
+ return orig_fn(arg0, *args, **kwargs)
109
+ cast_fn = utils.verbosify(cast_fn, fn, verbose)
110
+ new_args = utils.casted_args(cast_fn, args, kwargs)
111
+ return orig_fn(arg0, *new_args, **kwargs)
112
+ utils.set_func_save(handle, mod, fn, wrapper)
113
+
114
+ def err_if_any_half(mod, fn, handle, custom_err_msg=None):
115
+ if not utils.has_func(mod, fn):
116
+ return
117
+
118
+ orig_fn = utils.get_func(mod, fn)
119
+ @functools.wraps(orig_fn)
120
+ def wrapper(*args, **kwargs):
121
+ types = utils.collect_fp_tensor_types(args, kwargs)
122
+ if 'HalfTensor' in types:
123
+ if custom_err_msg:
124
+ raise NotImplementedError(custom_err_msg)
125
+ else:
126
+ raise NotImplementedError('Cannot call in-place function ' +
127
+ '{} with fp16 arguments.'.format(fn))
128
+ else:
129
+ return orig_fn(*args, **kwargs)
130
+ utils.set_func_save(handle, mod, fn, wrapper)
131
+
132
+ def err_if_arg0_half(mod, fn, handle, verbose=False):
133
+ if not utils.has_func(mod, fn):
134
+ return
135
+
136
+ orig_fn = utils.get_func(mod, fn)
137
+ @functools.wraps(orig_fn)
138
+ def wrapper(arg0, *args, **kwargs):
139
+ assert compat.is_tensor_like(arg0)
140
+ if utils.type_string(arg0) == 'HalfTensor':
141
+ raise NotImplementedError('Cannot call in-place method ' +
142
+ '{} on fp16 Tensors.'.format(fn))
143
+ else:
144
+ cast_fn = utils.verbosify(utils.maybe_float, fn, verbose)
145
+ new_args = utils.casted_args(cast_fn, args, kwargs)
146
+ return orig_fn(arg0, *new_args, **kwargs)
147
+ utils.set_func_save(handle, mod, fn, wrapper)
148
+
149
+ # Current RNN approach:
150
+ # - Wrap top-level `RNN` function in thnn backend
151
+ # - Will call into either CudnnRNN or AutogradRNN
152
+ # - Each of these are factory functions that return a per-iter
153
+ # `forward` function
154
+ # - We interpose on the factory function to:
155
+ # 1) Interpose on the actual forward function and put in casts
156
+ # 2) Insert an fp16 `flat_weight` if necessary
157
+ def rnn_cast(backend, fn, handle, verbose=False):
158
+ orig_rnn = utils.get_func(backend, fn)
159
+ @functools.wraps(orig_rnn)
160
+ def rnn_wrapper(*args, **kwargs):
161
+ flat_weight = kwargs.get('flat_weight')
162
+ if flat_weight is not None:
163
+ # We replace `flat_weight` with an uninitialized fp16
164
+ # Tensor. The "actual" weight tensors (provided in `forward`),
165
+ # will then be set up as ptrs into the buffer and have the
166
+ # corresponding fp32 values copied in.
167
+ # We need to call `copy` on the "actual" weights so that the
168
+ # autograd graph correctly backprops from the wgrads computed
169
+ # inside cuDNN (on fp16 weights) into the fp32 weights.
170
+ assert utils.type_string(flat_weight) == 'FloatTensor'
171
+ if compat.tensor_is_float_tensor() or compat.tensor_is_variable():
172
+ # Pre-0.4. A little slower, since it zeros out memory.
173
+ flat_weight_fp16 = flat_weight.new().half().resize_(flat_weight.shape)
174
+ else:
175
+ flat_weight_fp16 = torch.empty_like(flat_weight,
176
+ dtype=torch.float16)
177
+ kwargs['flat_weight'] = flat_weight_fp16
178
+ else:
179
+ flat_weight_fp16 = None
180
+
181
+ forward = orig_rnn(*args, **kwargs)
182
+ @functools.wraps(forward)
183
+ def fwd_wrapper(*fargs, **fkwargs):
184
+ assert len(fargs) == 3 or len(fargs) == 4
185
+ inputs, weights, hiddens = fargs[:3]
186
+ assert utils.is_fp_tensor(inputs)
187
+ assert isinstance(weights, list)
188
+ cast_fn = utils.verbosify(utils.maybe_half,
189
+ fn,
190
+ verbose)
191
+ new_args = []
192
+
193
+ # 0) Inputs
194
+ new_args.append(cast_fn(inputs))
195
+
196
+ # 1) Weights
197
+ if flat_weight_fp16 is not None:
198
+ fp16_weights = utils.synthesize_flattened_rnn_weights(
199
+ weights, flat_weight_fp16, fn, verbose)
200
+ else:
201
+ fp16_weights = [[cast_fn(w) for w in layer]
202
+ for layer in weights]
203
+ new_args.append(fp16_weights)
204
+
205
+ # 2) Inputs: either a tuple (for LSTM) or single tensor
206
+ if isinstance(hiddens, tuple):
207
+ new_args.append(tuple(cast_fn(x) for x in hiddens))
208
+ elif utils.is_fp_tensor(hiddens):
209
+ new_args.append(cast_fn(hiddens))
210
+ else:
211
+ # Hiddens can, in principle, be `None` -- pass through
212
+ new_args.append(hiddens)
213
+
214
+ # 3) Batch sizes (0.4 or later only)
215
+ if len(fargs) == 4:
216
+ new_args.append(fargs[3])
217
+
218
+ return forward(*new_args, **fkwargs)
219
+ return fwd_wrapper
220
+ utils.set_func_save(handle, backend, fn, rnn_wrapper)
221
+
222
+ def new_rnn_cast(fn, handle, verbose=False):
223
+ # Forward+backward compatibility around https://github.com/pytorch/pytorch/pull/15744
224
+ # For rnn backend calls that route through _rnn_impls, we must patch the ref
225
+ # that _rnn_impls stashed. For rnn backend calls that directly invoke
226
+ # _VF.<backend>, e.g. _VF.lstm, we can patch onto VariableFunctionsShim,
227
+ # which in turn has patched the ref named "_VF" in torch.nn.modules.rnn.
228
+ if utils.has_func(torch.nn.modules.rnn._rnn_impls, fn):
229
+ mod = torch.nn.modules.rnn._rnn_impls
230
+ else:
231
+ mod = torch.nn.modules.rnn._VF
232
+ assert isinstance(mod, rnn_compat.VariableFunctionsShim)
233
+ fn = fn.lower()
234
+ orig_fn = utils.get_func(mod, fn)
235
+ cast_fn = utils.verbosify(utils.maybe_half, fn, verbose)
236
+ @functools.wraps(orig_fn)
237
+ def wrapper(*args, **kwargs):
238
+ # Exact call signature from modules/rnn.py
239
+ assert len(args) == 9
240
+ assert len(kwargs) == 0
241
+
242
+ if not _amp_state.handle.is_active():
243
+ return orig_fn(*args, **kwargs)
244
+
245
+ if isinstance(args[6], bool):
246
+ params_idx = 2 # Not PackedSequence case
247
+ else:
248
+ params_idx = 3 # PackedSequence case
249
+
250
+ new_args = []
251
+ for i, arg in enumerate(args):
252
+ if i == params_idx:
253
+ num_params = sum([x.numel() for x in arg])
254
+ fp16_weight_buf = args[0].new_empty((num_params,),
255
+ dtype=torch.half)
256
+ casted_weights = utils.new_synthesize_flattened_rnn_weights(
257
+ arg, fp16_weight_buf, fn, verbose)
258
+ new_args.append(casted_weights)
259
+ elif utils.is_fp_tensor(arg):
260
+ new_args.append(cast_fn(arg))
261
+ else:
262
+ new_args.append(arg)
263
+
264
+ return orig_fn(*new_args)
265
+ utils.set_func_save(handle, mod, fn, wrapper)
266
+
267
+ def disable_casts(mod, fn, handle):
268
+ if not utils.has_func(mod, fn):
269
+ return
270
+
271
+ orig_fn = utils.get_func(mod, fn)
272
+ @functools.wraps(orig_fn)
273
+ def wrapper(*args, **kwargs):
274
+ with handle._disable_casts():
275
+ return orig_fn(*args, **kwargs)
276
+ utils.set_func_save(handle, mod, fn, wrapper)
apex/apex/contrib/__init__.py ADDED
File without changes
apex/apex/contrib/bottleneck/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .bottleneck import Bottleneck
apex/apex/contrib/bottleneck/bottleneck.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ import fast_bottleneck
4
+
5
+ def kaiming_uniform_(tensor, a=0, mode='fan_in', nonlinearity='leaky_relu'):
6
+ weight_tensor_nchw = tensor
7
+ nn.init.kaiming_uniform_(weight_tensor_nchw, a=a, mode=mode, nonlinearity=nonlinearity)
8
+
9
+ class FrozenBatchNorm2d(torch.nn.Module):
10
+ """
11
+ BatchNorm2d where the batch statistics and the affine parameters are fixed
12
+ """
13
+ def __init__(self, n):
14
+ super(FrozenBatchNorm2d, self).__init__()
15
+ self.register_buffer("weight", torch.ones(n))
16
+ self.register_buffer("bias", torch.zeros(n))
17
+ self.register_buffer("running_mean", torch.zeros(n))
18
+ self.register_buffer("running_var", torch.ones(n))
19
+
20
+ def get_scale_bias(self, nhwc=False):
21
+ scale = self.weight * self.running_var.rsqrt()
22
+ bias = self.bias - self.running_mean * scale
23
+ if nhwc:
24
+ scale = scale.reshape(1, 1, 1, -1)
25
+ bias = bias.reshape(1, 1, 1, -1)
26
+ else:
27
+ scale = scale.reshape(1, -1, 1, 1)
28
+ bias = bias.reshape(1, -1, 1, 1)
29
+ return scale, bias
30
+
31
+ def forward(self, x):
32
+ scale, bias = self.get_scale_bias()
33
+ return x * scale + bias
34
+
35
+
36
+ @torch.jit.script
37
+ def drelu_dscale1(grad_o, output, scale1):
38
+ relu_mask = (output>0).half()
39
+ dx_relu = relu_mask * grad_o
40
+ g1 = dx_relu * scale1
41
+ return g1, dx_relu
42
+
43
+ @torch.jit.script
44
+ def drelu_dscale2(grad_o, output, scale1, scale2):
45
+ relu_mask = (output>0).half()
46
+ dx_relu = relu_mask * grad_o
47
+ g1 = dx_relu * scale1
48
+ g2 = dx_relu * scale2
49
+ return g1, g2
50
+
51
+ class BottleneckFunction(torch.autograd.Function):
52
+ @staticmethod
53
+ def forward(ctx, nhwc, stride_1x1, scale, bias, x, *conv):
54
+ # TODO: clean up order of tensors
55
+ args = [x, *conv[0:3], *scale[0:3], *bias[0:3]]
56
+ ctx.downsample = len(conv) > 3
57
+ if ctx.downsample:
58
+ args.append(conv[3])
59
+ args.append(scale[3])
60
+ args.append(bias[3])
61
+
62
+ # weight buffers are always in nhwc while shape can be nhwc or channels_last
63
+ # here we pass in flag and let c++ handle it
64
+ # alternatively, we can put all sizes into a fixed format and pass it in
65
+ outputs = fast_bottleneck.forward(nhwc, stride_1x1, args)
66
+ ctx.save_for_backward(*(args+outputs))
67
+ # save relu outputs for drelu
68
+ ctx.nhwc = nhwc
69
+ ctx.stride_1x1 = stride_1x1
70
+ return outputs[2]
71
+
72
+ # backward relu is not exposed, MUL with mask used now
73
+ # only support dgrad
74
+ @staticmethod
75
+ def backward(ctx, grad_o):
76
+ outputs = ctx.saved_tensors[-3:]
77
+
78
+ if ctx.downsample:
79
+ grad_conv3, grad_conv4 = drelu_dscale2(grad_o, outputs[2], ctx.saved_tensors[6], ctx.saved_tensors[11])
80
+ else:
81
+ grad_conv3, grad_conv4 = drelu_dscale1(grad_o, outputs[2], ctx.saved_tensors[6])
82
+
83
+ # create input vector for backward
84
+ t_list = [*ctx.saved_tensors[0:10]]
85
+ t_list.append(grad_conv3)
86
+ t_list.append(grad_conv4)
87
+
88
+ # outputs used for wgrad and generating drelu mask
89
+ t_list.append(outputs[0])
90
+ t_list.append(outputs[1])
91
+
92
+ # in case there is downsample
93
+ if ctx.downsample:
94
+ t_list.append(ctx.saved_tensors[10])
95
+
96
+ grads = fast_bottleneck.backward(ctx.nhwc, ctx.stride_1x1, t_list)
97
+
98
+ return (None, None, None, None, *grads)
99
+
100
+ bottleneck_function = BottleneckFunction.apply
101
+
102
+ def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
103
+ """3x3 convolution with padding"""
104
+ return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
105
+ padding=dilation, groups=groups, bias=False, dilation=dilation)
106
+
107
+ def conv1x1(in_planes, out_planes, stride=1):
108
+ """1x1 convolution"""
109
+ return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
110
+
111
+ class Bottleneck(torch.nn.Module):
112
+ # Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2)
113
+ # while original implementation places the stride at the first 1x1 convolution(self.conv1)
114
+ # according to "Deep residual learning for image recognition"https://arxiv.org/abs/1512.03385.
115
+ # This variant is also known as ResNet V1.5 and improves accuracy according to
116
+ # https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch.
117
+ # here we put it at 1x1
118
+
119
+ def __init__(self, in_channels, bottleneck_channels, out_channels, stride=1, groups=1,
120
+ dilation=1, norm_func=None, use_cudnn=False, explicit_nhwc=False):
121
+ super(Bottleneck, self).__init__()
122
+ if groups != 1:
123
+ raise RuntimeError('Only support groups == 1')
124
+ if dilation != 1:
125
+ raise RuntimeError('Only support dilation == 1')
126
+ if norm_func == None:
127
+ norm_func = FrozenBatchNorm2d
128
+ else:
129
+ raise RuntimeError('Only support frozen BN now.')
130
+
131
+ if stride != 1 or in_channels != out_channels:
132
+ self.downsample = nn.Sequential(
133
+ conv1x1(in_channels, out_channels, stride),
134
+ norm_func(out_channels),
135
+ )
136
+ else:
137
+ self.downsample = None
138
+
139
+ # Both self.conv2 and self.downsample layers downsample the input when stride != 1
140
+ self.conv1 = conv1x1(in_channels, bottleneck_channels, stride)
141
+ self.conv2 = conv3x3(bottleneck_channels, bottleneck_channels)
142
+ self.conv3 = conv1x1(bottleneck_channels, out_channels)
143
+ self.relu = nn.ReLU(inplace=True)
144
+ self.stride = stride
145
+
146
+ self.bn1 = norm_func(bottleneck_channels)
147
+ self.bn2 = norm_func(bottleneck_channels)
148
+ self.bn3 = norm_func(out_channels)
149
+
150
+ self.use_cudnn = use_cudnn
151
+
152
+ # setup conv weights
153
+ self.w_conv = [self.conv1.weight, self.conv2.weight, self.conv3.weight]
154
+ if self.downsample is not None:
155
+ self.w_conv.append(self.downsample[0].weight)
156
+
157
+ # init weight in nchw format before possible transpose
158
+ for w in self.w_conv:
159
+ kaiming_uniform_(w, a=1)
160
+
161
+ # TODO: prevent unsupported case usage
162
+ # support cases
163
+ # native cudnn
164
+ # normal yes no
165
+ # channel_last yes yes
166
+ # explicit_nhwc no yes
167
+ self.explicit_nhwc = explicit_nhwc
168
+ if self.explicit_nhwc:
169
+ for p in self.parameters():
170
+ with torch.no_grad():
171
+ p.data = p.data.permute(0,2,3,1).contiguous()
172
+ return
173
+
174
+ def forward(self, x):
175
+ if self.use_cudnn:
176
+ # calculate scale/bias from registered buffers
177
+ # TODO: make this better
178
+ s1, b1 = self.bn1.get_scale_bias(self.explicit_nhwc)
179
+ s2, b2 = self.bn2.get_scale_bias(self.explicit_nhwc)
180
+ s3, b3 = self.bn3.get_scale_bias(self.explicit_nhwc)
181
+ w_scale = [s1, s2, s3]
182
+ w_bias = [b1, b2, b3]
183
+ if self.downsample is not None:
184
+ s4, b4 = self.downsample[1].get_scale_bias(self.explicit_nhwc)
185
+ w_scale.append(s4)
186
+ w_bias.append(b4)
187
+
188
+ out = bottleneck_function(self.explicit_nhwc, self.stride, w_scale, w_bias, x, *self.w_conv)
189
+ return out
190
+
191
+ if self.explicit_nhwc:
192
+ raise RuntimeError('explicit nhwc with native ops is not supported.')
193
+
194
+ # fallback to native ops
195
+ identity = x
196
+
197
+ out = self.conv1(x)
198
+ out = self.bn1(out)
199
+ out = self.relu(out)
200
+
201
+ out = self.conv2(out)
202
+ out = self.bn2(out)
203
+ out = self.relu(out)
204
+
205
+ out = self.conv3(out)
206
+ out = self.bn3(out)
207
+
208
+ if self.downsample is not None:
209
+ identity = self.downsample(x)
210
+
211
+ out += identity
212
+ out = self.relu(out)
213
+
214
+ return out
apex/apex/contrib/bottleneck/test.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from bottleneck import Bottleneck
3
+ torch.manual_seed(23337)
4
+
5
+ # use True to print layerwise sum for all outputs in reference code path
6
+ DEBUG = False#True
7
+
8
+ for stride, o_channel in [(1,32), (1,128), (2,32)]:
9
+ print("testing stride ==", stride, ", in_channel == 32 , out_channel ==", o_channel)
10
+ a_ = torch.randn(17,32,28,28)
11
+
12
+ a = a_.cuda().half().to(memory_format=torch.channels_last).requires_grad_()
13
+ model = Bottleneck(32,8,o_channel,stride=stride).cuda().half().to(memory_format=torch.channels_last)
14
+
15
+ # test model
16
+ b = model(a)
17
+ b.mean().backward()
18
+ d_grad = a.grad.float()
19
+ a.grad = None
20
+ torch.cuda.synchronize()
21
+
22
+ if DEBUG:
23
+ print("[DEBUG] ref dx :", d_grad.sum().item())
24
+ # print wgrad. we don't need to reset since later cpp print before accumulation
25
+ for i, w in enumerate(model.w_conv):
26
+ print("[DEBUG] ref wgrad{} :".format(i+1), w.grad.sum().item())
27
+
28
+ wgrads = []
29
+ for w in model.w_conv:
30
+ wgrads.append(w.grad.float())
31
+
32
+ model.use_cudnn = True
33
+ model.zero_grad()
34
+ c = model(a)
35
+ c.mean().backward()
36
+
37
+ torch.cuda.synchronize()
38
+ print("comparing native and channels_last:")
39
+ print("max error fprop:", (b-c).abs().max().item(), "max elem:", b.abs().max().item())
40
+ print("max error dgrad:", (d_grad-a.grad.float()).abs().max().item(), "max elem:", d_grad.abs().max().item())
41
+ for i, (w, wgrad) in enumerate(zip(model.w_conv, wgrads)):
42
+ print("max error wgrad{}:".format(i+1), (wgrad - w.grad.float()).abs().max().item(), "max elem:", wgrad.abs().max().item())
43
+
44
+ nhwc_a = a_.permute(0,2,3,1).contiguous().cuda().half().requires_grad_()
45
+ nhwc_model = Bottleneck(32,8,o_channel,stride=stride,explicit_nhwc=True, use_cudnn=True).cuda().half()
46
+ for p,q in zip(model.parameters(), nhwc_model.parameters()):
47
+ # model's storage is already in nhwc, we clone and assign to explicit nhwc model
48
+ q.data.copy_(p.data.permute(0,2,3,1).contiguous())
49
+ for p,q in zip(model.buffers(), nhwc_model.buffers()):
50
+ q.data.copy_(p.data)
51
+
52
+ d = nhwc_model(nhwc_a)
53
+ d.mean().backward()
54
+ torch.cuda.synchronize()
55
+
56
+ # reset reference to cudnn channels_last permute
57
+ #c_s = c.storage().tolist()
58
+ #d_s = d.storage().tolist()
59
+ #print(max([x-y for x,y in zip(c_s,d_s)]))
60
+ c = c.contiguous(memory_format=torch.contiguous_format).permute(0,2,3,1).contiguous()
61
+ d_grad = a.grad.float().permute(0,2,3,1).contiguous()
62
+ wgrads = []
63
+ for w in model.w_conv:
64
+ wgrads.append(w.grad.float().permute(0,2,3,1).contiguous())
65
+
66
+ torch.cuda.synchronize()
67
+ print("comparing nhwc and channels_last:")
68
+ print("max error fprop:", (d-c).abs().max().item(), "max elem:", c.abs().max().item())
69
+ print("max error dgrad:", (d_grad-nhwc_a.grad.float()).abs().max().item(), "max elem:", d_grad.abs().max().item())
70
+ for i, (w, wgrad) in enumerate(zip(nhwc_model.w_conv, wgrads)):
71
+ print("max error wgrad{}:".format(i+1), (wgrad - w.grad.float()).abs().max().item(), "max elem:", wgrad.abs().max().item())
apex/apex/contrib/csrc/bottleneck/bottleneck.cpp ADDED
@@ -0,0 +1,1612 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/ATen.h>
2
+ #include <ATen/cudnn/Handle.h> // for getcudnnhandle
3
+ #include <torch/extension.h>
4
+ #include <torch/torch.h>
5
+ #include <vector>
6
+ #include <cudnn_frontend.h>
7
+
8
+ #include <iostream>
9
+
10
+ #ifdef DEBUG
11
+ #define DEBUG_MSG(str) do { std::cout << str << std::endl; } while( false )
12
+ #else
13
+ #define DEBUG_MSG(str) do { } while ( false )
14
+ #endif
15
+
16
+ #ifdef DEBUG_CUDNN
17
+ #define DEBUG_CUDNN_MSG(buf, str) do { buf << str << std::endl; } while( false )
18
+ #else
19
+ #define DEBUG_CUDNN_MSG(buf, str) do { } while ( false )
20
+ #endif
21
+
22
+ #define checkCudnnErr(...) \
23
+ do { \
24
+ int err = checkCudnnError(__VA_ARGS__, #__VA_ARGS__, __FILE__, __LINE__); \
25
+ if (err) { \
26
+ return; \
27
+ } \
28
+ } while (0)
29
+
30
+
31
+ int checkCudnnError(cudnnStatus_t code, const char* expr, const char* file, int line) {
32
+ if (code) {
33
+ printf("CUDNN error at %s:%d, code=%d (%s) in '%s'\n", file, line, (int)code, cudnnGetErrorString(code), expr);
34
+ return 1;
35
+ }
36
+ return 0;
37
+ }
38
+
39
+ void checkError(cudaError_t code, char const * func, const char *file, const int line, bool abort = true);
40
+ #define checkCUDAError(val) { checkError((val), #val, __FILE__, __LINE__); } // in-line regular function
41
+
42
+ void checkError(cudaError_t code, char const * func, const char *file, const int line, bool abort)
43
+ {
44
+ if (code != cudaSuccess)
45
+ {
46
+ const char * errorMessage = cudaGetErrorString(code);
47
+ fprintf(stderr, "CUDA error returned from \"%s\" at %s:%d, Error code: %d (%s)\n", func, file, line, code, errorMessage);
48
+ if (abort){
49
+ cudaDeviceReset();
50
+ exit(code);
51
+ }
52
+ }
53
+ }
54
+
55
+ void generateStrides(const int64_t* dimA, int64_t* strideA, int nbDims, cudnnTensorFormat_t filterFormat) {
56
+ // For INT8x4 and INT8x32 we still compute standard strides here to input
57
+ // into the cuDNN functions. We will manually scale by resizeFactor in the cpu ref.
58
+ if (filterFormat == CUDNN_TENSOR_NCHW) {
59
+ strideA[nbDims - 1] = 1;
60
+ for (int64_t d = nbDims - 2; d >= 0; d--) {
61
+ strideA[d] = strideA[d + 1] * dimA[d + 1];
62
+ }
63
+ } else {
64
+ // Here we assume that the format is CUDNN_TENSOR_NHWC
65
+ strideA[1] = 1;
66
+ strideA[nbDims - 1] = strideA[1] * dimA[1];
67
+ for (int64_t d = nbDims - 2; d >= 2; d--) {
68
+ strideA[d] = strideA[d + 1] * dimA[d + 1];
69
+ }
70
+ strideA[0] = strideA[2] * dimA[2];
71
+ }
72
+ }
73
+
74
+
75
+ int getFwdConvDilatedFilterDim(int filterDim, int dilation) {
76
+ return ((filterDim - 1) * dilation) + 1;
77
+ }
78
+
79
+ int getFwdConvPaddedImageDim(int tensorDim, int pad) {
80
+ return tensorDim + (2 * pad);
81
+ }
82
+
83
+ int getFwdConvOutputDim(
84
+ int tensorDim,
85
+ int pad,
86
+ int filterDim,
87
+ int stride,
88
+ int dilation)
89
+ {
90
+ int p = (getFwdConvPaddedImageDim(tensorDim, pad) - getFwdConvDilatedFilterDim(filterDim, dilation)) / stride + 1;
91
+ return (p);
92
+ }
93
+
94
+ enum {
95
+ X_TENSOR,
96
+ Y_TENSOR,
97
+ W_TENSOR,
98
+ Z_TENSOR,
99
+ B_TENSOR,
100
+ AFTERADD_TENSOR,
101
+ AFTERBIAS_TENSOR,
102
+ AFTERCONV_TENSOR,
103
+ OPTIONAL,
104
+ AFTEROPT_TENSOR,
105
+ };
106
+
107
+ using common_conv_descriptors =
108
+ std::tuple<cudnn_frontend::Tensor, cudnn_frontend::Tensor, cudnn_frontend::Tensor, cudnn_frontend::ConvDesc>;
109
+
110
+
111
+ common_conv_descriptors
112
+ create_common_descriptors(int64_t* x_dim_padded,
113
+ int64_t* padA,
114
+ int64_t* convstrideA,
115
+ int64_t* dilationA,
116
+ int64_t* w_dim_padded,
117
+ int64_t* y_dim_padded,
118
+ cudnnDataType_t dataType,
119
+ cudnnConvolutionMode_t mode) {
120
+ const int convDim = 2;
121
+
122
+ int64_t strideA_padded[4];
123
+ int64_t outstrideA_padded[4];
124
+ int64_t filterstrideA_padded[4];
125
+
126
+ generateStrides(w_dim_padded, filterstrideA_padded, 4, CUDNN_TENSOR_NHWC);
127
+ generateStrides(x_dim_padded, strideA_padded, 4, CUDNN_TENSOR_NHWC);
128
+ generateStrides(y_dim_padded, outstrideA_padded, 4, CUDNN_TENSOR_NHWC);
129
+
130
+ return common_conv_descriptors(cudnn_frontend::TensorBuilder()
131
+ .setDim(4, x_dim_padded)
132
+ .setStrides(4, strideA_padded)
133
+ .setId('x')
134
+ .setAlignment(16)
135
+ .setDataType(dataType)
136
+ .build(),
137
+ cudnn_frontend::TensorBuilder()
138
+ .setDim(4, y_dim_padded)
139
+ .setStrides(4, outstrideA_padded)
140
+ .setId('y')
141
+ .setAlignment(16)
142
+ .setDataType(dataType)
143
+ .build(),
144
+ cudnn_frontend::TensorBuilder()
145
+ .setDim(4, w_dim_padded)
146
+ .setStrides(4, filterstrideA_padded)
147
+ .setId('w')
148
+ .setAlignment(16)
149
+ .setDataType(dataType)
150
+ .build(),
151
+ cudnn_frontend::ConvDescBuilder()
152
+ .setDataType(CUDNN_DATA_FLOAT)
153
+ .setMathMode(mode)
154
+ .setNDims(convDim)
155
+ .setStrides(convDim, convstrideA)
156
+ .setPrePadding(convDim, padA)
157
+ .setPostPadding(convDim, padA)
158
+ .setDilation(convDim, dilationA)
159
+ .build());
160
+ }
161
+
162
+ using common_convbias_descriptors = std::tuple<cudnn_frontend::Tensor,
163
+ cudnn_frontend::Tensor,
164
+ cudnn_frontend::Tensor,
165
+ cudnn_frontend::Tensor,
166
+ cudnn_frontend::Tensor,
167
+ cudnn_frontend::Tensor,
168
+ cudnn_frontend::Tensor,
169
+ cudnn_frontend::Tensor,
170
+ cudnn_frontend::Tensor,
171
+ cudnn_frontend::Tensor>;
172
+
173
+ common_convbias_descriptors
174
+ create_conv_bias_add_act_descriptors(int64_t* x_dim_padded,
175
+ int64_t* padA,
176
+ int64_t* convstrideA,
177
+ int64_t* dilationA,
178
+ int64_t* w_dim_padded,
179
+ int64_t* y_dim_padded,
180
+ cudnnDataType_t dataType) {
181
+ const int convDim = 2;
182
+
183
+ int64_t b_dim_padded[4];
184
+ b_dim_padded[0] = 1;
185
+ b_dim_padded[1] = y_dim_padded[1];
186
+ b_dim_padded[2] = 1;
187
+ b_dim_padded[3] = 1;
188
+
189
+ int64_t x_stride_padded[4];
190
+ int64_t y_stride_padded[4];
191
+ int64_t w_stride_padded[4];
192
+ int64_t b_stride_padded[4];
193
+
194
+ generateStrides(w_dim_padded, w_stride_padded, 4, CUDNN_TENSOR_NHWC);
195
+ generateStrides(x_dim_padded, x_stride_padded, 4, CUDNN_TENSOR_NHWC);
196
+ generateStrides(y_dim_padded, y_stride_padded, 4, CUDNN_TENSOR_NHWC);
197
+ generateStrides(b_dim_padded, b_stride_padded, 4, CUDNN_TENSOR_NHWC);
198
+
199
+ return common_convbias_descriptors(cudnn_frontend::TensorBuilder()
200
+ .setDim(4, x_dim_padded)
201
+ .setStrides(4, x_stride_padded)
202
+ .setId('x')
203
+ .setAlignment(16)
204
+ .setDataType(dataType)
205
+ .build(),
206
+ cudnn_frontend::TensorBuilder()
207
+ .setDim(4, y_dim_padded)
208
+ .setStrides(4, y_stride_padded)
209
+ .setId('y')
210
+ .setAlignment(16)
211
+ .setDataType(dataType)
212
+ .build(),
213
+ cudnn_frontend::TensorBuilder()
214
+ .setDim(4, w_dim_padded)
215
+ .setStrides(4, w_stride_padded)
216
+ .setId('w')
217
+ .setAlignment(16)
218
+ .setDataType(dataType)
219
+ .build(),
220
+ cudnn_frontend::TensorBuilder()
221
+ .setDim(4, b_dim_padded)
222
+ .setStrides(4, b_stride_padded)
223
+ .setId('z')
224
+ .setAlignment(16)
225
+ .setDataType(dataType)
226
+ .build(),
227
+ cudnn_frontend::TensorBuilder()
228
+ .setDim(4, b_dim_padded)
229
+ .setStrides(4, b_stride_padded)
230
+ .setId('b')
231
+ .setAlignment(16)
232
+ .setDataType(dataType)
233
+ .build(),
234
+ cudnn_frontend::TensorBuilder()
235
+ .setDim(4, y_dim_padded)
236
+ .setStrides(4, y_stride_padded)
237
+ .setVirtual()
238
+ .setId('A') // after add
239
+ .setAlignment(16)
240
+ .setDataType(dataType)
241
+ .build(),
242
+ cudnn_frontend::TensorBuilder()
243
+ .setDim(4, y_dim_padded)
244
+ .setStrides(4, y_stride_padded)
245
+ .setVirtual()
246
+ .setId('B') // after bias
247
+ .setAlignment(16)
248
+ .setDataType(dataType)
249
+ .build(),
250
+ cudnn_frontend::TensorBuilder()
251
+ .setDim(4, y_dim_padded)
252
+ .setStrides(4, y_stride_padded)
253
+ .setId('C') // after conv
254
+ .setAlignment(16)
255
+ .setVirtual()
256
+ .setDataType(dataType)
257
+ .build(),
258
+ cudnn_frontend::TensorBuilder()
259
+ .setDim(4, y_dim_padded)
260
+ .setStrides(4, y_stride_padded)
261
+ .setId('i')
262
+ .setAlignment(16)
263
+ .setDataType(dataType)
264
+ .build(),
265
+ cudnn_frontend::TensorBuilder()
266
+ .setDim(4, y_dim_padded)
267
+ .setStrides(4, y_stride_padded)
268
+ .setId('D') // after optional add
269
+ .setAlignment(16)
270
+ .setVirtual()
271
+ .setDataType(dataType)
272
+ .build());
273
+ }
274
+
275
+ // tensor descriptors used for dgrad
276
+ enum {
277
+ X_OR_DX_TENSOR,
278
+ DY_TENSOR,
279
+ W_OR_DW_TENSOR,
280
+ SCALE_TENSOR,
281
+ RELU_TENSOR,
282
+ AFTER_DCONV_TENSOR,
283
+ AFTER_DRELU_TENSOR,
284
+ };
285
+
286
+ using dconv_descriptors = std::tuple<cudnn_frontend::Tensor,
287
+ cudnn_frontend::Tensor,
288
+ cudnn_frontend::Tensor,
289
+ cudnn_frontend::Tensor,
290
+ cudnn_frontend::Tensor,
291
+ cudnn_frontend::Tensor,
292
+ cudnn_frontend::Tensor>;
293
+
294
+ dconv_descriptors
295
+ create_dconv_descriptors(int64_t* x_dim_padded,
296
+ int64_t* padA,
297
+ int64_t* convstrideA,
298
+ int64_t* dilationA,
299
+ int64_t* w_dim_padded,
300
+ int64_t* y_dim_padded,
301
+ cudnnDataType_t dataType) {
302
+ const int convDim = 2;
303
+
304
+ int64_t b_dim_padded[4];
305
+ b_dim_padded[0] = 1;
306
+ b_dim_padded[1] = x_dim_padded[1];
307
+ b_dim_padded[2] = 1;
308
+ b_dim_padded[3] = 1;
309
+
310
+ int64_t x_stride_padded[4];
311
+ int64_t y_stride_padded[4];
312
+ int64_t w_stride_padded[4];
313
+ int64_t b_stride_padded[4];
314
+
315
+ generateStrides(w_dim_padded, w_stride_padded, 4, CUDNN_TENSOR_NHWC);
316
+ generateStrides(x_dim_padded, x_stride_padded, 4, CUDNN_TENSOR_NHWC);
317
+ generateStrides(y_dim_padded, y_stride_padded, 4, CUDNN_TENSOR_NHWC);
318
+ generateStrides(b_dim_padded, b_stride_padded, 4, CUDNN_TENSOR_NHWC);
319
+
320
+ return dconv_descriptors(cudnn_frontend::TensorBuilder()
321
+ .setDim(4, x_dim_padded)
322
+ .setStrides(4, x_stride_padded)
323
+ .setId('x')
324
+ .setAlignment(16)
325
+ .setDataType(dataType)
326
+ .build(),
327
+ cudnn_frontend::TensorBuilder()
328
+ .setDim(4, y_dim_padded)
329
+ .setStrides(4, y_stride_padded)
330
+ .setId('y')
331
+ .setAlignment(16)
332
+ .setDataType(dataType)
333
+ .build(),
334
+ cudnn_frontend::TensorBuilder()
335
+ .setDim(4, w_dim_padded)
336
+ .setStrides(4, w_stride_padded)
337
+ .setId('w')
338
+ .setAlignment(16)
339
+ .setDataType(dataType)
340
+ .build(),
341
+ cudnn_frontend::TensorBuilder()
342
+ .setDim(4, b_dim_padded)
343
+ .setStrides(4, b_stride_padded)
344
+ .setId('s')
345
+ .setAlignment(16)
346
+ .setDataType(dataType)
347
+ .build(),
348
+ cudnn_frontend::TensorBuilder()
349
+ .setDim(4, x_dim_padded)
350
+ .setStrides(4, x_stride_padded)
351
+ .setId('r')
352
+ .setAlignment(16)
353
+ .setDataType(dataType)
354
+ .build(),
355
+ cudnn_frontend::TensorBuilder()
356
+ .setDim(4, x_dim_padded)
357
+ .setStrides(4, x_stride_padded)
358
+ .setVirtual()
359
+ .setId('A') // after dconv
360
+ .setAlignment(16)
361
+ .setDataType(dataType)
362
+ .build(),
363
+ cudnn_frontend::TensorBuilder()
364
+ .setDim(4, x_dim_padded)
365
+ .setStrides(4, x_stride_padded)
366
+ .setVirtual()
367
+ .setId('B') // after drelu
368
+ .setAlignment(16)
369
+ .setDataType(dataType)
370
+ .build());
371
+ }
372
+
373
+ // create a cache for plan
374
+ std::unordered_map<std::string, cudnn_frontend::ExecutionPlan> plan_cache;
375
+
376
+ // TODO: better name
377
+ std::string getConvFusionString(int64_t* x_dim_padded,
378
+ int64_t* padA,
379
+ int64_t* convstrideA,
380
+ int64_t* dilationA,
381
+ int64_t* w_dim_padded,
382
+ cudnnDataType_t dataType,
383
+ std::string fusion_string) {
384
+
385
+ for(int i=0;i<4;i++) {
386
+ fusion_string += 'X';
387
+ fusion_string += std::to_string(x_dim_padded[i]);
388
+ }
389
+ for(int i=0;i<4;i++) {
390
+ fusion_string += 'W';
391
+ fusion_string += std::to_string(w_dim_padded[i]);
392
+ }
393
+ for(int i=0;i<2;i++) {
394
+ fusion_string += 'P';
395
+ fusion_string += std::to_string(padA[i]);
396
+ }
397
+ for(int i=0;i<2;i++) {
398
+ fusion_string += 'S';
399
+ fusion_string += std::to_string(convstrideA[i]);
400
+ }
401
+ for(int i=0;i<2;i++) {
402
+ fusion_string += 'D';
403
+ fusion_string += std::to_string(dilationA[i]);
404
+ }
405
+ fusion_string += 'T';
406
+ fusion_string += std::to_string(dataType);
407
+ return fusion_string;
408
+ }
409
+
410
+ cudnn_frontend::ExecutionPlan& getOrCreatePlan(cudnnHandle_t handle_,
411
+ std::stringstream& log_buf,
412
+ cudnn_frontend::OperationGraph& opGraph,
413
+ std::string cache_string,
414
+ bool use_heuristic = true){
415
+ auto it = plan_cache.find(cache_string);
416
+ if (it != plan_cache.end()) {
417
+ DEBUG_CUDNN_MSG(log_buf, "Found plan in cache");
418
+ return it->second;
419
+ } else {
420
+ if (use_heuristic){
421
+ // TODO: confirm which mode to use
422
+ auto heuristics = cudnn_frontend::EngineHeuristicsBuilder()
423
+ .setOperationGraph(opGraph)
424
+ .setHeurMode(CUDNN_HEUR_MODE_INSTANT)
425
+ .build();
426
+ // try 3 times for now as WAR for no heuristic training
427
+ int max_tries = 3, count = 0;
428
+ auto& engine_configs = heuristics.getEngineConfig(max_tries);
429
+ while(true) {
430
+ try {
431
+ plan_cache.emplace(cache_string, std::move(cudnn_frontend::ExecutionPlanBuilder()
432
+ .setHandle(handle_)
433
+ .setEngineConfig(engine_configs[count], opGraph.getTag())
434
+ .build()));
435
+ break;
436
+ } catch (cudnn_frontend::cudnnException e) {
437
+ if (++count == max_tries) throw e;
438
+ }
439
+ }
440
+ }else{
441
+ DEBUG_CUDNN_MSG(log_buf, "No plan in cache");
442
+ // How many engines support this operation graph ?
443
+ auto total_engines = opGraph.getEngineCount();
444
+ DEBUG_CUDNN_MSG(log_buf, opGraph.describe() << " has " << total_engines << " engines.");
445
+ // We have to randomly pick one engine from [0, total_engines)
446
+ // Selecting "0" by default
447
+ auto engine = cudnn_frontend::EngineBuilder().setGlobalEngineIdx(0).setOperationGraph(opGraph).build();
448
+ DEBUG_CUDNN_MSG(log_buf, engine.describe());
449
+ auto& knobs = engine.getSupportedKnobs();
450
+ for (auto it = std::begin(knobs); it != std::end(knobs); ++it) {
451
+ DEBUG_CUDNN_MSG(log_buf, it->describe());
452
+ }
453
+ if (knobs.begin() != knobs.end()) {
454
+ DEBUG_CUDNN_MSG(log_buf, "Updated knob choice");
455
+ knobs.begin()->setChoice(knobs.begin()->getMinValue() + 1);
456
+ DEBUG_CUDNN_MSG(log_buf, knobs.begin()->describe());
457
+ }
458
+
459
+ // Createmplacee the requisite engine config
460
+ auto engine_config = cudnn_frontend::EngineConfigBuilder().setEngine(engine).build();
461
+ DEBUG_CUDNN_MSG(log_buf, engine_config.describe());
462
+ plan_cache.emplace(cache_string, std::move(cudnn_frontend::ExecutionPlanBuilder().setHandle(handle_).setEngineConfig(engine_config).build()));
463
+ }
464
+
465
+ return plan_cache.find(cache_string)->second;
466
+ }
467
+ }
468
+
469
+ void
470
+ run_conv_scale_bias_add_activation(int64_t* x_dim_padded,
471
+ int64_t* pad,
472
+ int64_t* convstride,
473
+ int64_t* dilation,
474
+ int64_t* w_dim_padded,
475
+ int64_t* y_dim_padded,
476
+ cudnnDataType_t dataType,
477
+ at::Half* devPtrX,
478
+ at::Half* devPtrW,
479
+ at::Half* devPtrY,
480
+ at::Half* devPtrZ,
481
+ at::Half* devPtrB,
482
+ at::Half* devPtrI) {
483
+ cudnnHandle_t handle_ = torch::native::getCudnnHandle();
484
+ std::stringstream log_buf;
485
+ try {
486
+ int convDim = 2;
487
+
488
+ // Creates the necessary tensor descriptors
489
+ common_convbias_descriptors tensors = create_conv_bias_add_act_descriptors(
490
+ x_dim_padded, pad, convstride, dilation, w_dim_padded, y_dim_padded, dataType);
491
+ DEBUG_CUDNN_MSG(log_buf, std::get<X_TENSOR>(tensors).describe());
492
+ DEBUG_CUDNN_MSG(log_buf, std::get<Y_TENSOR>(tensors).describe());
493
+ DEBUG_CUDNN_MSG(log_buf, std::get<W_TENSOR>(tensors).describe());
494
+ DEBUG_CUDNN_MSG(log_buf, std::get<Z_TENSOR>(tensors).describe());
495
+ DEBUG_CUDNN_MSG(log_buf, std::get<B_TENSOR>(tensors).describe());
496
+ DEBUG_CUDNN_MSG(log_buf, std::get<AFTERADD_TENSOR>(tensors).describe());
497
+ DEBUG_CUDNN_MSG(log_buf, std::get<AFTERBIAS_TENSOR>(tensors).describe());
498
+ DEBUG_CUDNN_MSG(log_buf, std::get<AFTERCONV_TENSOR>(tensors).describe());
499
+ DEBUG_CUDNN_MSG(log_buf, std::get<OPTIONAL>(tensors).describe());
500
+
501
+ // Define the add operation
502
+ auto scaleDesc = cudnn_frontend::PointWiseDescBuilder()
503
+ .setMode(CUDNN_POINTWISE_MUL)
504
+ .setMathPrecision(CUDNN_DATA_FLOAT)
505
+ .build();
506
+ DEBUG_CUDNN_MSG(log_buf, scaleDesc.describe());
507
+
508
+ // Define the bias operation
509
+ auto biasDesc = cudnn_frontend::PointWiseDescBuilder()
510
+ .setMode(CUDNN_POINTWISE_ADD)
511
+ .setMathPrecision(CUDNN_DATA_FLOAT)
512
+ .build();
513
+ DEBUG_CUDNN_MSG(log_buf, biasDesc.describe());
514
+
515
+ // optional add
516
+ auto addDesc = cudnn_frontend::PointWiseDescBuilder()
517
+ .setMode(CUDNN_POINTWISE_ADD)
518
+ .setMathPrecision(CUDNN_DATA_FLOAT)
519
+ .build();
520
+ DEBUG_CUDNN_MSG(log_buf, addDesc.describe());
521
+
522
+ // Define the activation operation
523
+ auto actDesc = cudnn_frontend::PointWiseDescBuilder()
524
+ .setMode(CUDNN_POINTWISE_RELU_FWD)
525
+ .setMathPrecision(CUDNN_DATA_FLOAT)
526
+ .build();
527
+ DEBUG_CUDNN_MSG(log_buf, actDesc.describe());
528
+
529
+ // Define the convolution problem
530
+ auto convDesc = cudnn_frontend::ConvDescBuilder()
531
+ .setDataType(CUDNN_DATA_FLOAT)
532
+ .setMathMode(CUDNN_CROSS_CORRELATION)
533
+ .setNDims(convDim)
534
+ .setStrides(convDim, convstride)
535
+ .setPrePadding(convDim, pad)
536
+ .setPostPadding(convDim, pad)
537
+ .setDilation(convDim, dilation)
538
+ .build();
539
+ DEBUG_CUDNN_MSG(log_buf, convDesc.describe());
540
+
541
+ float alpha = 1.0f;
542
+ float beta = 0.0f;
543
+
544
+ // Create a convolution Node
545
+ auto conv_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_CONVOLUTION_FORWARD_DESCRIPTOR)
546
+ .setxDesc(std::get<X_TENSOR>(tensors))
547
+ .setwDesc(std::get<W_TENSOR>(tensors))
548
+ .setyDesc(std::get<AFTERCONV_TENSOR>(tensors))
549
+ .setcDesc(convDesc)
550
+ .setAlpha(alpha)
551
+ .setBeta(beta)
552
+ .build();
553
+ DEBUG_CUDNN_MSG(log_buf, conv_op.describe());
554
+
555
+ // Create a Add Node with scaling parameters.
556
+ auto scale_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR)
557
+ .setxDesc(conv_op.getOutputTensor())
558
+ .setbDesc(std::get<Z_TENSOR>(tensors))
559
+ .setyDesc(std::get<AFTERADD_TENSOR>(tensors))
560
+ .setpwDesc(scaleDesc)
561
+ .build();
562
+ DEBUG_CUDNN_MSG(log_buf, scale_op.describe());
563
+
564
+ // Create a Bias Node.
565
+ auto bias_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR)
566
+ .setxDesc(scale_op.getOutputTensor())
567
+ .setbDesc(std::get<B_TENSOR>(tensors))
568
+ .setyDesc(std::get<AFTERBIAS_TENSOR>(tensors))
569
+ .setpwDesc(biasDesc)
570
+ .build();
571
+ DEBUG_CUDNN_MSG(log_buf, bias_op.describe());
572
+
573
+ // Create a optional add Node.
574
+ auto add_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR)
575
+ .setxDesc(bias_op.getOutputTensor())
576
+ .setbDesc(std::get<OPTIONAL>(tensors))
577
+ .setyDesc(std::get<AFTEROPT_TENSOR>(tensors))
578
+ .setpwDesc(addDesc)
579
+ .build();
580
+ DEBUG_CUDNN_MSG(log_buf, add_op.describe());
581
+
582
+
583
+ // Create an Activation Node.
584
+ auto act_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR)
585
+ .setxDesc(devPtrI ? add_op.getOutputTensor() : bias_op.getOutputTensor())
586
+ .setyDesc(std::get<Y_TENSOR>(tensors))
587
+ .setpwDesc(actDesc)
588
+ .build();
589
+ DEBUG_CUDNN_MSG(log_buf, act_op.describe());
590
+
591
+ // Create an Operation Graph. In this case it is convolution add bias activation
592
+ std::array<cudnn_frontend::Operation const*, 5> ops = {&conv_op, &scale_op, &bias_op, devPtrI ? &add_op : &act_op, &act_op};
593
+
594
+ auto opGraph = cudnn_frontend::OperationGraphBuilder()
595
+ .setHandle(handle_)
596
+ .setOperationGraph(devPtrI ? ops.size() : 4, ops.data())
597
+ .build();
598
+
599
+ // Create string encoding for plan caching
600
+ auto cache_string = getConvFusionString(x_dim_padded, pad, convstride, dilation, w_dim_padded, dataType, opGraph.getTag());
601
+ DEBUG_CUDNN_MSG(log_buf, "[convstring] " << cache_string);
602
+
603
+ auto& plan = getOrCreatePlan(handle_, log_buf, opGraph, cache_string);
604
+ DEBUG_CUDNN_MSG(log_buf, "Plan tag: " << plan.getTag());
605
+
606
+ auto workspace_size = plan.getWorkspaceSize();
607
+ DEBUG_CUDNN_MSG(log_buf, plan.describe() << " requires workspace " << workspace_size);
608
+
609
+ void* workspace_ptr = nullptr;
610
+ auto workspace_tensor = at::empty({(workspace_size+3)/4}, at::TensorOptions(at::kCUDA).dtype(at::kFloat));
611
+ if (workspace_size > 0) {
612
+ workspace_ptr = workspace_tensor.data_ptr<float>();
613
+ }
614
+ void* data_ptrs[] = {devPtrX, devPtrY, devPtrW, devPtrZ, devPtrB, devPtrI};
615
+ int64_t uids[] = {'x', 'y', 'w', 'z', 'b', 'i'};
616
+ auto variantPack = cudnn_frontend::VariantPackBuilder()
617
+ .setWorkspacePointer(workspace_ptr)
618
+ .setDataPointers(devPtrI ? 6 : 5, data_ptrs)
619
+ .setUids(devPtrI ? 6 : 5, uids)
620
+ .build();
621
+ DEBUG_CUDNN_MSG(log_buf, "variantPack " << variantPack.describe());
622
+ cudnnStatus_t status = cudnnBackendExecute(handle_, plan.get_raw_desc(), variantPack.get_raw_desc());
623
+ checkCudnnErr(status);
624
+ cudnn_frontend::throw_if([status]() { return (status != CUDNN_STATUS_SUCCESS); }, "Plan execute error");
625
+ } catch (cudnn_frontend::cudnnException e) {
626
+ std::cout << log_buf.str() << "[ERROR] Exception " << e.what() << std::endl;
627
+ }
628
+ }
629
+
630
+ void
631
+ run_conv_scale_bias(int64_t* x_dim_padded,
632
+ int64_t* pad,
633
+ int64_t* convstride,
634
+ int64_t* dilation,
635
+ int64_t* w_dim_padded,
636
+ int64_t* y_dim_padded,
637
+ cudnnDataType_t dataType,
638
+ at::Half* devPtrX,
639
+ at::Half* devPtrW,
640
+ at::Half* devPtrY,
641
+ at::Half* devPtrZ,
642
+ at::Half* devPtrB) {
643
+ cudnnHandle_t handle_ = torch::native::getCudnnHandle();
644
+ std::stringstream log_buf;
645
+ try {
646
+ int convDim = 2;
647
+
648
+ // Creates the necessary tensor descriptors
649
+ common_convbias_descriptors tensors = create_conv_bias_add_act_descriptors(
650
+ x_dim_padded, pad, convstride, dilation, w_dim_padded, y_dim_padded, dataType);
651
+ DEBUG_CUDNN_MSG(log_buf, std::get<X_TENSOR>(tensors).describe());
652
+ DEBUG_CUDNN_MSG(log_buf, std::get<Y_TENSOR>(tensors).describe());
653
+ DEBUG_CUDNN_MSG(log_buf, std::get<W_TENSOR>(tensors).describe());
654
+ DEBUG_CUDNN_MSG(log_buf, std::get<Z_TENSOR>(tensors).describe());
655
+ DEBUG_CUDNN_MSG(log_buf, std::get<B_TENSOR>(tensors).describe());
656
+ DEBUG_CUDNN_MSG(log_buf, std::get<AFTERADD_TENSOR>(tensors).describe());
657
+ DEBUG_CUDNN_MSG(log_buf, std::get<AFTERBIAS_TENSOR>(tensors).describe());
658
+ DEBUG_CUDNN_MSG(log_buf, std::get<AFTERCONV_TENSOR>(tensors).describe());
659
+ DEBUG_CUDNN_MSG(log_buf, std::get<OPTIONAL>(tensors).describe());
660
+
661
+ // Define the add operation
662
+ auto scaleDesc = cudnn_frontend::PointWiseDescBuilder()
663
+ .setMode(CUDNN_POINTWISE_MUL)
664
+ .setMathPrecision(CUDNN_DATA_FLOAT)
665
+ .build();
666
+ DEBUG_CUDNN_MSG(log_buf, scaleDesc.describe());
667
+
668
+ // Define the bias operation
669
+ auto addDesc = cudnn_frontend::PointWiseDescBuilder()
670
+ .setMode(CUDNN_POINTWISE_ADD)
671
+ .setMathPrecision(CUDNN_DATA_FLOAT)
672
+ .build();
673
+ DEBUG_CUDNN_MSG(log_buf, addDesc.describe());
674
+
675
+ // Define the convolution problem
676
+ auto convDesc = cudnn_frontend::ConvDescBuilder()
677
+ .setDataType(CUDNN_DATA_FLOAT)
678
+ .setMathMode(CUDNN_CROSS_CORRELATION)
679
+ .setNDims(convDim)
680
+ .setStrides(convDim, convstride)
681
+ .setPrePadding(convDim, pad)
682
+ .setPostPadding(convDim, pad)
683
+ .setDilation(convDim, dilation)
684
+ .build();
685
+ DEBUG_CUDNN_MSG(log_buf, convDesc.describe());
686
+
687
+ float alpha = 1.0f;
688
+ float beta = 0.0f;
689
+
690
+ // Create a convolution Node
691
+ auto conv_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_CONVOLUTION_FORWARD_DESCRIPTOR)
692
+ .setxDesc(std::get<X_TENSOR>(tensors))
693
+ .setwDesc(std::get<W_TENSOR>(tensors))
694
+ .setyDesc(std::get<AFTERCONV_TENSOR>(tensors))
695
+ .setcDesc(convDesc)
696
+ .setAlpha(alpha)
697
+ .setBeta(beta)
698
+ .build();
699
+ DEBUG_CUDNN_MSG(log_buf, conv_op.describe());
700
+
701
+ // Create a Add Node with scaling parameters.
702
+ auto scale_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR)
703
+ .setxDesc(conv_op.getOutputTensor())
704
+ .setbDesc(std::get<Z_TENSOR>(tensors))
705
+ .setyDesc(std::get<AFTERADD_TENSOR>(tensors)) // TODO: change enum to aftermul
706
+ .setpwDesc(scaleDesc)
707
+ .build();
708
+ DEBUG_CUDNN_MSG(log_buf, scale_op.describe());
709
+
710
+ // Create a Bias Node.
711
+ auto add_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR)
712
+ .setxDesc(scale_op.getOutputTensor())
713
+ .setbDesc(std::get<B_TENSOR>(tensors))
714
+ .setyDesc(std::get<Y_TENSOR>(tensors))
715
+ .setpwDesc(addDesc)
716
+ .build();
717
+ DEBUG_CUDNN_MSG(log_buf, add_op.describe());
718
+
719
+ // Create an Operation Graph. In this case it is convolution add bias activation
720
+ std::array<cudnn_frontend::Operation const*, 3> ops = {&conv_op, &scale_op, &add_op};
721
+
722
+ auto opGraph = cudnn_frontend::OperationGraphBuilder()
723
+ .setHandle(handle_)
724
+ .setOperationGraph(ops.size(), ops.data())
725
+ .build();
726
+
727
+ // Create string encoding for plan caching
728
+ auto cache_string = getConvFusionString(x_dim_padded, pad, convstride, dilation, w_dim_padded, dataType, opGraph.getTag());
729
+ DEBUG_CUDNN_MSG(log_buf, "[convstring] " << cache_string);
730
+
731
+ auto& plan = getOrCreatePlan(handle_, log_buf, opGraph, cache_string);
732
+ DEBUG_CUDNN_MSG(log_buf, "Plan tag: " << plan.getTag());
733
+
734
+ auto workspace_size = plan.getWorkspaceSize();
735
+ DEBUG_CUDNN_MSG(log_buf, plan.describe() << " requires workspace " << workspace_size);
736
+
737
+ void* workspace_ptr = nullptr;
738
+ auto workspace_tensor = at::empty({(workspace_size+3)/4}, at::TensorOptions(at::kCUDA).dtype(at::kFloat));
739
+ if (workspace_size > 0) {
740
+ workspace_ptr = workspace_tensor.data_ptr<float>();
741
+ }
742
+ void* data_ptrs[] = {devPtrX, devPtrY, devPtrW, devPtrZ, devPtrB};
743
+ int64_t uids[] = {'x', 'y', 'w', 'z', 'b'};
744
+ auto variantPack = cudnn_frontend::VariantPackBuilder()
745
+ .setWorkspacePointer(workspace_ptr)
746
+ .setDataPointers(5, data_ptrs)
747
+ .setUids(5, uids)
748
+ .build();
749
+ DEBUG_CUDNN_MSG(log_buf, "variantPack " << variantPack.describe());
750
+ cudnnStatus_t status = cudnnBackendExecute(handle_, plan.get_raw_desc(), variantPack.get_raw_desc());
751
+ checkCudnnErr(status);
752
+ cudnn_frontend::throw_if([status]() { return (status != CUDNN_STATUS_SUCCESS); }, "Plan execute error");
753
+ } catch (cudnn_frontend::cudnnException e) {
754
+ std::cout << log_buf.str() << "[ERROR] Exception " << e.what() << std::endl;
755
+ }
756
+ }
757
+
758
+
759
+ void
760
+ run_dconv_drelu_dscale(int64_t* x_dim_padded,
761
+ int64_t* pad,
762
+ int64_t* convstride,
763
+ int64_t* dilation,
764
+ int64_t* w_dim_padded,
765
+ int64_t* y_dim_padded,
766
+ cudnnDataType_t dataType,
767
+ at::Half* devPtrX,
768
+ at::Half* devPtrW,
769
+ at::Half* devPtrY,
770
+ at::Half* devPtrZ,
771
+ at::Half* devPtrR) {
772
+ cudnnHandle_t handle_ = torch::native::getCudnnHandle();
773
+ std::stringstream log_buf;
774
+ try {
775
+ int convDim = 2;
776
+
777
+ // Creates the necessary tensor descriptors
778
+ dconv_descriptors tensors = create_dconv_descriptors(
779
+ x_dim_padded, pad, convstride, dilation, w_dim_padded, y_dim_padded, dataType);
780
+ DEBUG_CUDNN_MSG(log_buf, std::get<X_OR_DX_TENSOR>(tensors).describe());
781
+ DEBUG_CUDNN_MSG(log_buf, std::get<DY_TENSOR>(tensors).describe());
782
+ DEBUG_CUDNN_MSG(log_buf, std::get<W_OR_DW_TENSOR>(tensors).describe());
783
+ DEBUG_CUDNN_MSG(log_buf, std::get<SCALE_TENSOR>(tensors).describe());
784
+ DEBUG_CUDNN_MSG(log_buf, std::get<RELU_TENSOR>(tensors).describe());
785
+ DEBUG_CUDNN_MSG(log_buf, std::get<AFTER_DCONV_TENSOR>(tensors).describe());
786
+ DEBUG_CUDNN_MSG(log_buf, std::get<AFTER_DRELU_TENSOR>(tensors).describe());
787
+
788
+ // Define the convolution problem
789
+ auto convDesc = cudnn_frontend::ConvDescBuilder()
790
+ .setDataType(CUDNN_DATA_FLOAT)
791
+ .setMathMode(CUDNN_CROSS_CORRELATION)
792
+ .setNDims(convDim)
793
+ .setStrides(convDim, convstride)
794
+ .setPrePadding(convDim, pad)
795
+ .setPostPadding(convDim, pad)
796
+ .setDilation(convDim, dilation)
797
+ .build();
798
+ DEBUG_CUDNN_MSG(log_buf, convDesc.describe());
799
+
800
+ // Define the activation backward operation
801
+ auto actDesc = cudnn_frontend::PointWiseDescBuilder()
802
+ .setMode(CUDNN_POINTWISE_RELU_BWD)
803
+ .setMathPrecision(CUDNN_DATA_FLOAT)
804
+ .build();
805
+ DEBUG_CUDNN_MSG(log_buf, actDesc.describe());
806
+
807
+ // Define the scale backward operation
808
+ auto scaleDesc = cudnn_frontend::PointWiseDescBuilder()
809
+ .setMode(CUDNN_POINTWISE_MUL)
810
+ .setMathPrecision(CUDNN_DATA_FLOAT)
811
+ .build();
812
+ DEBUG_CUDNN_MSG(log_buf, scaleDesc.describe());
813
+
814
+ float alpha = 1.0f;
815
+ float beta = 0.0f;
816
+
817
+ // Create a convolution Node
818
+ auto conv_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR)
819
+ .setdxDesc(std::get<AFTER_DCONV_TENSOR>(tensors))
820
+ .setwDesc(std::get<W_OR_DW_TENSOR>(tensors))
821
+ .setdyDesc(std::get<DY_TENSOR>(tensors))
822
+ .setcDesc(convDesc)
823
+ .setAlpha(alpha)
824
+ .setBeta(beta)
825
+ .build();
826
+ DEBUG_CUDNN_MSG(log_buf, conv_op.describe());
827
+
828
+ // TODO: do we need getOutputTensor(), and what it returns in backward case?
829
+ // Create an relu backward Node.
830
+ auto act_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR)
831
+ .setdyDesc(std::get<AFTER_DCONV_TENSOR>(tensors))
832
+ .setxDesc(std::get<RELU_TENSOR>(tensors))
833
+ .setdxDesc(std::get<AFTER_DRELU_TENSOR>(tensors))
834
+ .setpwDesc(actDesc)
835
+ .build();
836
+ DEBUG_CUDNN_MSG(log_buf, act_op.describe());
837
+
838
+ // Create a Scale Node.
839
+ auto scale_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR)
840
+ .setxDesc(std::get<AFTER_DRELU_TENSOR>(tensors))
841
+ .setbDesc(std::get<SCALE_TENSOR>(tensors))
842
+ .setyDesc(std::get<X_OR_DX_TENSOR>(tensors))
843
+ .setpwDesc(scaleDesc)
844
+ .build();
845
+ DEBUG_CUDNN_MSG(log_buf, scale_op.describe());
846
+
847
+ // Create an Operation Graph. In this case it is convolution add bias activation
848
+ std::array<cudnn_frontend::Operation const*, 3> ops = {&conv_op, &act_op, &scale_op};
849
+
850
+ auto opGraph = cudnn_frontend::OperationGraphBuilder()
851
+ .setHandle(handle_)
852
+ .setOperationGraph(ops.size(), ops.data())
853
+ .build();
854
+
855
+ // Create string encoding for plan caching
856
+ auto cache_string = getConvFusionString(x_dim_padded, pad, convstride, dilation, w_dim_padded, dataType, opGraph.getTag());
857
+ DEBUG_CUDNN_MSG(log_buf, "[convstring] " << cache_string);
858
+
859
+ auto& plan = getOrCreatePlan(handle_, log_buf, opGraph, cache_string);
860
+ DEBUG_CUDNN_MSG(log_buf, "Plan tag: " << plan.getTag());
861
+
862
+ auto workspace_size = plan.getWorkspaceSize();
863
+ DEBUG_CUDNN_MSG(log_buf, plan.describe() << " requires workspace " << workspace_size);
864
+
865
+ void* workspace_ptr = nullptr;
866
+ auto workspace_tensor = at::empty({(workspace_size+3)/4}, at::TensorOptions(at::kCUDA).dtype(at::kFloat));
867
+ if (workspace_size > 0) {
868
+ workspace_ptr = workspace_tensor.data_ptr<float>();
869
+ }
870
+ void* data_ptrs[] = {devPtrX, devPtrY, devPtrW, devPtrZ, devPtrR};
871
+ int64_t uids[] = {'x', 'y', 'w', 's', 'r'};
872
+ auto variantPack = cudnn_frontend::VariantPackBuilder()
873
+ .setWorkspacePointer(workspace_ptr)
874
+ .setDataPointers(5, data_ptrs)
875
+ .setUids(5, uids)
876
+ .build();
877
+ DEBUG_CUDNN_MSG(log_buf, "variantPack " << variantPack.describe());
878
+ cudnnStatus_t status = cudnnBackendExecute(handle_, plan.get_raw_desc(), variantPack.get_raw_desc());
879
+ checkCudnnErr(status);
880
+ cudnn_frontend::throw_if([status]() { return (status != CUDNN_STATUS_SUCCESS); }, "Plan execute error");
881
+ } catch (cudnn_frontend::cudnnException e) {
882
+ std::cout << log_buf.str() << "[ERROR] Exception " << e.what() << std::endl;
883
+ }
884
+ }
885
+
886
+ void
887
+ run_dconv(int64_t* x_dim_padded,
888
+ int64_t* pad,
889
+ int64_t* convstride,
890
+ int64_t* dilation,
891
+ int64_t* w_dim_padded,
892
+ int64_t* y_dim_padded,
893
+ cudnnDataType_t dataType,
894
+ at::Half* devPtrX,
895
+ at::Half* devPtrW,
896
+ at::Half* devPtrY,
897
+ cudnnBackendDescriptorType_t mode) {
898
+ cudnnHandle_t handle_ = torch::native::getCudnnHandle();
899
+ std::stringstream log_buf;
900
+ try {
901
+ int convDim = 2;
902
+
903
+ // Creates the necessary tensor descriptors
904
+ dconv_descriptors tensors = create_dconv_descriptors(
905
+ x_dim_padded, pad, convstride, dilation, w_dim_padded, y_dim_padded, dataType);
906
+ DEBUG_CUDNN_MSG(log_buf, std::get<X_OR_DX_TENSOR>(tensors).describe());
907
+ DEBUG_CUDNN_MSG(log_buf, std::get<DY_TENSOR>(tensors).describe());
908
+ DEBUG_CUDNN_MSG(log_buf, std::get<W_OR_DW_TENSOR>(tensors).describe());
909
+ DEBUG_CUDNN_MSG(log_buf, std::get<SCALE_TENSOR>(tensors).describe());
910
+ DEBUG_CUDNN_MSG(log_buf, std::get<RELU_TENSOR>(tensors).describe());
911
+ DEBUG_CUDNN_MSG(log_buf, std::get<AFTER_DCONV_TENSOR>(tensors).describe());
912
+ DEBUG_CUDNN_MSG(log_buf, std::get<AFTER_DRELU_TENSOR>(tensors).describe());
913
+
914
+ // Define the convolution problem
915
+ auto convDesc = cudnn_frontend::ConvDescBuilder()
916
+ .setDataType(CUDNN_DATA_FLOAT)
917
+ .setMathMode(CUDNN_CROSS_CORRELATION)
918
+ .setNDims(convDim)
919
+ .setStrides(convDim, convstride)
920
+ .setPrePadding(convDim, pad)
921
+ .setPostPadding(convDim, pad)
922
+ .setDilation(convDim, dilation)
923
+ .build();
924
+ DEBUG_CUDNN_MSG(log_buf, convDesc.describe());
925
+
926
+ float alpha = 1.0f;
927
+ float beta = 0.0f;
928
+
929
+ // Create a convolution Node
930
+ // mode should be one of following
931
+ // CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR
932
+ // CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR
933
+ auto conv_op_builder = cudnn_frontend::OperationBuilder(mode);
934
+ if (mode == CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR) {
935
+ conv_op_builder.setdxDesc(std::get<X_OR_DX_TENSOR>(tensors))
936
+ .setwDesc(std::get<W_OR_DW_TENSOR>(tensors))
937
+ .setdyDesc(std::get<DY_TENSOR>(tensors))
938
+ .setcDesc(convDesc)
939
+ .setAlpha(alpha)
940
+ .setBeta(beta);
941
+ }
942
+ else {
943
+ conv_op_builder.setxDesc(std::get<X_OR_DX_TENSOR>(tensors))
944
+ .setdwDesc(std::get<W_OR_DW_TENSOR>(tensors))
945
+ .setdyDesc(std::get<DY_TENSOR>(tensors))
946
+ .setcDesc(convDesc)
947
+ .setAlpha(alpha)
948
+ .setBeta(beta);
949
+ }
950
+ auto conv_op = conv_op_builder.build();
951
+ DEBUG_CUDNN_MSG(log_buf, conv_op.describe());
952
+
953
+ // Create an Operation Graph. In this case it is convolution add bias activation
954
+ std::array<cudnn_frontend::Operation const*, 1> ops = {&conv_op};
955
+
956
+ auto opGraph = cudnn_frontend::OperationGraphBuilder()
957
+ .setHandle(handle_)
958
+ .setOperationGraph(ops.size(), ops.data())
959
+ .build();
960
+
961
+ // Create string encoding for plan caching
962
+ auto cache_string = getConvFusionString(x_dim_padded, pad, convstride, dilation, w_dim_padded, dataType, opGraph.getTag());
963
+ DEBUG_CUDNN_MSG(log_buf, "[convstring] " << cache_string);
964
+
965
+ auto& plan = getOrCreatePlan(handle_, log_buf, opGraph, cache_string);
966
+ DEBUG_CUDNN_MSG(log_buf, "Plan tag: " << plan.getTag());
967
+
968
+ auto workspace_size = plan.getWorkspaceSize();
969
+ DEBUG_CUDNN_MSG(log_buf, plan.describe() << " requires workspace " << workspace_size);
970
+
971
+ void* workspace_ptr = nullptr;
972
+ auto workspace_tensor = at::empty({(workspace_size+3)/4}, at::TensorOptions(at::kCUDA).dtype(at::kFloat));
973
+ if (workspace_size > 0) {
974
+ workspace_ptr = workspace_tensor.data_ptr<float>();
975
+ }
976
+ void* data_ptrs[] = {devPtrX, devPtrY, devPtrW};
977
+ int64_t uids[] = {'x', 'y', 'w'};
978
+ auto variantPack = cudnn_frontend::VariantPackBuilder()
979
+ .setWorkspacePointer(workspace_ptr)
980
+ .setDataPointers(3, data_ptrs)
981
+ .setUids(3, uids)
982
+ .build();
983
+ DEBUG_CUDNN_MSG(log_buf, "variantPack " << variantPack.describe());
984
+ cudnnStatus_t status = cudnnBackendExecute(handle_, plan.get_raw_desc(), variantPack.get_raw_desc());
985
+ checkCudnnErr(status);
986
+ cudnn_frontend::throw_if([status]() { return (status != CUDNN_STATUS_SUCCESS); }, "Plan execute error");
987
+ } catch (cudnn_frontend::cudnnException e) {
988
+ std::cout << log_buf.str() << "[ERROR] Exception " << e.what() << std::endl;
989
+ }
990
+ }
991
+
992
+ void
993
+ run_dconv_add(int64_t* x_dim_padded,
994
+ int64_t* pad,
995
+ int64_t* convstride,
996
+ int64_t* dilation,
997
+ int64_t* w_dim_padded,
998
+ int64_t* y_dim_padded,
999
+ cudnnDataType_t dataType,
1000
+ at::Half* devPtrX,
1001
+ at::Half* devPtrW,
1002
+ at::Half* devPtrY,
1003
+ at::Half* devPtrR) {
1004
+ cudnnHandle_t handle_ = torch::native::getCudnnHandle();
1005
+ std::stringstream log_buf;
1006
+ try {
1007
+ int convDim = 2;
1008
+
1009
+ // Creates the necessary tensor descriptors
1010
+ dconv_descriptors tensors = create_dconv_descriptors(
1011
+ x_dim_padded, pad, convstride, dilation, w_dim_padded, y_dim_padded, dataType);
1012
+ DEBUG_CUDNN_MSG(log_buf, std::get<X_OR_DX_TENSOR>(tensors).describe());
1013
+ DEBUG_CUDNN_MSG(log_buf, std::get<DY_TENSOR>(tensors).describe());
1014
+ DEBUG_CUDNN_MSG(log_buf, std::get<W_OR_DW_TENSOR>(tensors).describe());
1015
+ DEBUG_CUDNN_MSG(log_buf, std::get<SCALE_TENSOR>(tensors).describe());
1016
+ DEBUG_CUDNN_MSG(log_buf, std::get<RELU_TENSOR>(tensors).describe());
1017
+ DEBUG_CUDNN_MSG(log_buf, std::get<AFTER_DCONV_TENSOR>(tensors).describe());
1018
+ DEBUG_CUDNN_MSG(log_buf, std::get<AFTER_DRELU_TENSOR>(tensors).describe());
1019
+
1020
+ // Define the convolution problem
1021
+ auto convDesc = cudnn_frontend::ConvDescBuilder()
1022
+ .setDataType(CUDNN_DATA_FLOAT)
1023
+ .setMathMode(CUDNN_CROSS_CORRELATION)
1024
+ .setNDims(convDim)
1025
+ .setStrides(convDim, convstride)
1026
+ .setPrePadding(convDim, pad)
1027
+ .setPostPadding(convDim, pad)
1028
+ .setDilation(convDim, dilation)
1029
+ .build();
1030
+ DEBUG_CUDNN_MSG(log_buf, convDesc.describe());
1031
+
1032
+ // Define the add backward operation
1033
+ auto addDesc = cudnn_frontend::PointWiseDescBuilder()
1034
+ .setMode(CUDNN_POINTWISE_ADD)
1035
+ .setMathPrecision(CUDNN_DATA_FLOAT)
1036
+ .build();
1037
+ DEBUG_CUDNN_MSG(log_buf, addDesc.describe());
1038
+
1039
+ float alpha = 1.0f;
1040
+ float beta = 0.0f;
1041
+
1042
+ // Create a convolution Node
1043
+ auto conv_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR)
1044
+ .setdxDesc(std::get<AFTER_DCONV_TENSOR>(tensors))
1045
+ .setwDesc(std::get<W_OR_DW_TENSOR>(tensors))
1046
+ .setdyDesc(std::get<DY_TENSOR>(tensors))
1047
+ .setcDesc(convDesc)
1048
+ .setAlpha(alpha)
1049
+ .setBeta(beta)
1050
+ .build();
1051
+ DEBUG_CUDNN_MSG(log_buf, conv_op.describe());
1052
+
1053
+ // TODO: do we need getOutputTensor(), and what it returns in backward case?
1054
+ // Create add Node.
1055
+ auto add_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR)
1056
+ .setxDesc(std::get<AFTER_DCONV_TENSOR>(tensors))
1057
+ .setbDesc(std::get<RELU_TENSOR>(tensors))
1058
+ .setyDesc(std::get<X_OR_DX_TENSOR>(tensors))
1059
+ .setpwDesc(addDesc)
1060
+ .build();
1061
+ DEBUG_CUDNN_MSG(log_buf, add_op.describe());
1062
+
1063
+ // Create an Operation Graph. In this case it is convolution add bias activation
1064
+ std::array<cudnn_frontend::Operation const*, 2> ops = {&conv_op, &add_op};
1065
+
1066
+ auto opGraph = cudnn_frontend::OperationGraphBuilder()
1067
+ .setHandle(handle_)
1068
+ .setOperationGraph(ops.size(), ops.data())
1069
+ .build();
1070
+
1071
+ // Create string encoding for plan caching
1072
+ auto cache_string = getConvFusionString(x_dim_padded, pad, convstride, dilation, w_dim_padded, dataType, opGraph.getTag());
1073
+ DEBUG_CUDNN_MSG(log_buf, "[convstring] " << cache_string);
1074
+
1075
+ auto& plan = getOrCreatePlan(handle_, log_buf, opGraph, cache_string);
1076
+ DEBUG_CUDNN_MSG(log_buf, "Plan tag: " << plan.getTag());
1077
+
1078
+ auto workspace_size = plan.getWorkspaceSize();
1079
+ DEBUG_CUDNN_MSG(log_buf, plan.describe() << " requires workspace " << workspace_size);
1080
+
1081
+ void* workspace_ptr = nullptr;
1082
+ auto workspace_tensor = at::empty({(workspace_size+3)/4}, at::TensorOptions(at::kCUDA).dtype(at::kFloat));
1083
+ if (workspace_size > 0) {
1084
+ workspace_ptr = workspace_tensor.data_ptr<float>();
1085
+ }
1086
+ void* data_ptrs[] = {devPtrX, devPtrY, devPtrW, devPtrR};
1087
+ int64_t uids[] = {'x', 'y', 'w', 'r'};
1088
+ auto variantPack = cudnn_frontend::VariantPackBuilder()
1089
+ .setWorkspacePointer(workspace_ptr)
1090
+ .setDataPointers(4, data_ptrs)
1091
+ .setUids(4, uids)
1092
+ .build();
1093
+ DEBUG_CUDNN_MSG(log_buf, "variantPack " << variantPack.describe());
1094
+ cudnnStatus_t status = cudnnBackendExecute(handle_, plan.get_raw_desc(), variantPack.get_raw_desc());
1095
+ checkCudnnErr(status);
1096
+ cudnn_frontend::throw_if([status]() { return (status != CUDNN_STATUS_SUCCESS); }, "Plan execute error");
1097
+ } catch (cudnn_frontend::cudnnException e) {
1098
+ std::cout << log_buf.str() << "[ERROR] Exception " << e.what() << std::endl;
1099
+ }
1100
+ }
1101
+
1102
+
1103
+ // inputs contains x,w,z,b,(i)
1104
+ std::vector<at::Tensor> bottleneck_forward(bool explicit_nhwc, int stride_1X1, std::vector<at::Tensor> inputs) {
1105
+
1106
+ std::cout << std::fixed;
1107
+ // create output vector
1108
+ std::vector<at::Tensor> outputs;
1109
+ auto output_format = explicit_nhwc ? at::MemoryFormat::Contiguous : at::MemoryFormat::ChannelsLast;
1110
+
1111
+ // setup dimensions
1112
+ int64_t dimA[] = {0, 0, 0, 0};
1113
+ int64_t filterdimA1[] = {0, 0, 0, 0};
1114
+ int64_t filterdimA2[] = {0, 0, 0, 0};
1115
+ int64_t filterdimA3[] = {0, 0, 0, 0};
1116
+ int64_t filterdimA4[] = {0, 0, 0, 0};
1117
+
1118
+ // All dim calculation after this order of n,c,h,w
1119
+ int axis[] {0,1,2,3};
1120
+ if (explicit_nhwc) {
1121
+ axis[0] = 0;
1122
+ axis[1] = 3;
1123
+ axis[2] = 1;
1124
+ axis[3] = 2;
1125
+ }
1126
+ for (int dim=0;dim<4;dim++) {
1127
+ dimA[dim] = inputs[0].size(axis[dim]);
1128
+ filterdimA1[dim] = inputs[1].size(axis[dim]);
1129
+ filterdimA2[dim] = inputs[2].size(axis[dim]);
1130
+ filterdimA3[dim] = inputs[3].size(axis[dim]);
1131
+ }
1132
+ if (stride_1X1 != 1 || filterdimA3[0] != dimA[1]) {
1133
+ for (int dim=0;dim<4;dim++) {
1134
+ filterdimA4[dim] = inputs[10].size(axis[dim]);
1135
+ }
1136
+ }
1137
+
1138
+ // output dim in n,c,h,w used by backend
1139
+ int64_t outdimA1[] = {0, 0, 0, 0}; // Computed Below
1140
+ int64_t outdimA2[] = {0, 0, 0, 0}; // Computed Below
1141
+ int64_t outdimA3[] = {0, 0, 0, 0}; // Computed Below
1142
+
1143
+ // use these fixed value for test run
1144
+ int64_t padA[] = {0, 0};
1145
+ int64_t padA1[] = {1, 1};
1146
+ int64_t dilationA[] = {1, 1};
1147
+ int64_t convstrideA[] = {1, 1};
1148
+ int64_t convstride1X1[] = {stride_1X1, stride_1X1};
1149
+
1150
+ // compute output from pad/stride/dilation
1151
+ outdimA1[0] = dimA[0];
1152
+ outdimA1[1] = filterdimA1[0];
1153
+ for (int dim = 0; dim < 2; dim++) {
1154
+ outdimA1[dim + 2] = getFwdConvOutputDim(dimA[dim + 2], padA[dim], filterdimA1[dim + 2], convstride1X1[dim], dilationA[dim]);
1155
+ }
1156
+
1157
+ outdimA2[0] = outdimA1[0];
1158
+ outdimA2[1] = filterdimA2[0];
1159
+ for (int dim = 0; dim < 2; dim++) {
1160
+ outdimA2[dim + 2] = getFwdConvOutputDim(outdimA1[dim + 2], padA1[dim], filterdimA2[dim + 2], convstrideA[dim], dilationA[dim]);
1161
+ }
1162
+
1163
+ outdimA3[0] = outdimA2[0];
1164
+ outdimA3[1] = filterdimA3[0];
1165
+ for (int dim = 0; dim < 2; dim++) {
1166
+ outdimA3[dim + 2] = getFwdConvOutputDim(outdimA2[dim + 2], padA[dim], filterdimA3[dim + 2], convstrideA[dim], dilationA[dim]);
1167
+ }
1168
+
1169
+ // Create output tensor in the correct shape in pytorch's view
1170
+ int64_t outdim1[] = {0, 0, 0, 0};
1171
+ int64_t outdim2[] = {0, 0, 0, 0};
1172
+ int64_t outdim3[] = {0, 0, 0, 0};
1173
+ if (explicit_nhwc) {
1174
+ axis[0] = 0;
1175
+ axis[1] = 2;
1176
+ axis[2] = 3;
1177
+ axis[3] = 1;
1178
+ }
1179
+ for (int dim=0;dim<4;dim++) {
1180
+ outdim1[dim] = outdimA1[axis[dim]];
1181
+ outdim2[dim] = outdimA2[axis[dim]];
1182
+ outdim3[dim] = outdimA3[axis[dim]];
1183
+ }
1184
+
1185
+ // run
1186
+ at::Half* x = inputs[0].data_ptr<at::Half>();
1187
+ at::Half* w = inputs[1].data_ptr<at::Half>();
1188
+ at::Half* z = inputs[4].data_ptr<at::Half>();
1189
+ at::Half* b = inputs[7].data_ptr<at::Half>();
1190
+ auto out1 = at::empty(outdim1, inputs[0].type(), output_format);
1191
+ at::Half* y1 = out1.data_ptr<at::Half>();
1192
+
1193
+ run_conv_scale_bias_add_activation(dimA,
1194
+ padA,
1195
+ convstride1X1,
1196
+ dilationA,
1197
+ filterdimA1,
1198
+ outdimA1,
1199
+ CUDNN_DATA_HALF,
1200
+ x,
1201
+ w,
1202
+ y1,
1203
+ z,
1204
+ b,
1205
+ nullptr);
1206
+
1207
+ DEBUG_MSG("[DEBUG] new relu1 : " << out1.to(at::kFloat).sum().item<float>());
1208
+
1209
+ w = inputs[2].data_ptr<at::Half>();
1210
+ z = inputs[5].data_ptr<at::Half>();
1211
+ b = inputs[8].data_ptr<at::Half>();
1212
+ auto out2 = at::empty(outdim2, inputs[0].type(), output_format);
1213
+ at::Half* y2 = out2.data_ptr<at::Half>();
1214
+
1215
+ run_conv_scale_bias_add_activation(outdimA1,
1216
+ padA1,
1217
+ convstrideA,
1218
+ dilationA,
1219
+ filterdimA2,
1220
+ outdimA2,
1221
+ CUDNN_DATA_HALF,
1222
+ y1,
1223
+ w,
1224
+ y2,
1225
+ z,
1226
+ b,
1227
+ nullptr);
1228
+ DEBUG_MSG("[DEBUG] new relu2 : " << out2.to(at::kFloat).sum().item<float>());
1229
+
1230
+ // create output of conv3
1231
+ auto out3 = at::empty(outdim3, inputs[0].type(), output_format);
1232
+ at::Half* y3 = out3.data_ptr<at::Half>();
1233
+
1234
+ // create output of conv4 that may exist
1235
+ auto identity = at::empty_like(out3);
1236
+ at::Half* yi = identity.data_ptr<at::Half>();
1237
+
1238
+ if (stride_1X1 != 1 || filterdimA3[0] != dimA[1]){
1239
+
1240
+ w = inputs[10].data_ptr<at::Half>();
1241
+ z = inputs[11].data_ptr<at::Half>();
1242
+ b = inputs[12].data_ptr<at::Half>();
1243
+ run_conv_scale_bias(dimA,
1244
+ padA,
1245
+ convstride1X1,
1246
+ dilationA,
1247
+ filterdimA4,
1248
+ outdimA3,
1249
+ CUDNN_DATA_HALF,
1250
+ x,
1251
+ w,
1252
+ yi,
1253
+ z,
1254
+ b);
1255
+ DEBUG_MSG("[DEBUG] new downsample : " << identity.to(at::kFloat).sum().item<float>());
1256
+ }
1257
+ else {
1258
+ yi = x;
1259
+ }
1260
+
1261
+ w = inputs[3].data_ptr<at::Half>();
1262
+ z = inputs[6].data_ptr<at::Half>();
1263
+ b = inputs[9].data_ptr<at::Half>();
1264
+
1265
+ run_conv_scale_bias_add_activation(outdimA2,
1266
+ padA,
1267
+ convstrideA,
1268
+ dilationA,
1269
+ filterdimA3,
1270
+ outdimA3,
1271
+ CUDNN_DATA_HALF,
1272
+ y2,
1273
+ w,
1274
+ y3,
1275
+ z,
1276
+ b,
1277
+ yi);
1278
+ DEBUG_MSG("[DEBUG] new relu3 : " << out3.to(at::kFloat).sum().item<float>());
1279
+
1280
+ outputs.push_back(out1);
1281
+ outputs.push_back(out2);
1282
+ outputs.push_back(out3);
1283
+
1284
+ return outputs;
1285
+ }
1286
+
1287
+ std::vector<at::Tensor> bottleneck_backward(bool explicit_nhwc, int stride_1X1, std::vector<at::Tensor> inputs) {
1288
+
1289
+ bool requires_grad = inputs[0].requires_grad();
1290
+
1291
+ std::cout << std::fixed;
1292
+ // create output vector
1293
+ std::vector<at::Tensor> outputs;
1294
+ auto output_format = explicit_nhwc ? at::MemoryFormat::Contiguous : at::MemoryFormat::ChannelsLast;
1295
+
1296
+ // setup dimensions
1297
+ int64_t dimA[] = {0, 0, 0, 0};
1298
+ int64_t filterdimA1[] = {0, 0, 0, 0};
1299
+ int64_t filterdimA2[] = {0, 0, 0, 0};
1300
+ int64_t filterdimA3[] = {0, 0, 0, 0};
1301
+ int64_t filterdimA4[] = {0, 0, 0, 0};
1302
+
1303
+ // All dim calculation after this order of n,c,h,w
1304
+ int axis[] {0,1,2,3};
1305
+ if (explicit_nhwc) {
1306
+ axis[0] = 0;
1307
+ axis[1] = 3;
1308
+ axis[2] = 1;
1309
+ axis[3] = 2;
1310
+ }
1311
+ for (int dim=0;dim<4;dim++) {
1312
+ dimA[dim] = inputs[0].size(axis[dim]);
1313
+ filterdimA1[dim] = inputs[1].size(axis[dim]);
1314
+ filterdimA2[dim] = inputs[2].size(axis[dim]);
1315
+ filterdimA3[dim] = inputs[3].size(axis[dim]);
1316
+ }
1317
+ if (stride_1X1 != 1 || filterdimA3[0] != dimA[1]) {
1318
+ for (int dim=0;dim<4;dim++) {
1319
+ filterdimA4[dim] = inputs[14].size(axis[dim]);
1320
+ }
1321
+ }
1322
+
1323
+ // output dim in n,c,h,w used by backend
1324
+ int64_t outdimA1[] = {0, 0, 0, 0}; // Computed Below
1325
+ int64_t outdimA2[] = {0, 0, 0, 0}; // Computed Below
1326
+ int64_t outdimA3[] = {0, 0, 0, 0}; // Computed Below
1327
+
1328
+ // use these fixed value for test run
1329
+ int64_t padA[] = {0, 0};
1330
+ int64_t padA1[] = {1, 1};
1331
+ int64_t dilationA[] = {1, 1};
1332
+ int64_t convstrideA[] = {1, 1};
1333
+ int64_t convstride1X1[] = {stride_1X1, stride_1X1};
1334
+
1335
+ // compute output from pad/stride/dilation
1336
+ outdimA1[0] = dimA[0];
1337
+ outdimA1[1] = filterdimA1[0];
1338
+ for (int dim = 0; dim < 2; dim++) {
1339
+ outdimA1[dim + 2] = getFwdConvOutputDim(dimA[dim + 2], padA[dim], filterdimA1[dim + 2], convstride1X1[dim], dilationA[dim]);
1340
+ }
1341
+
1342
+ outdimA2[0] = outdimA1[0];
1343
+ outdimA2[1] = filterdimA2[0];
1344
+ for (int dim = 0; dim < 2; dim++) {
1345
+ outdimA2[dim + 2] = getFwdConvOutputDim(outdimA1[dim + 2], padA1[dim], filterdimA2[dim + 2], convstrideA[dim], dilationA[dim]);
1346
+ }
1347
+
1348
+ outdimA3[0] = outdimA2[0];
1349
+ outdimA3[1] = filterdimA3[0];
1350
+ for (int dim = 0; dim < 2; dim++) {
1351
+ outdimA3[dim + 2] = getFwdConvOutputDim(outdimA2[dim + 2], padA[dim], filterdimA3[dim + 2], convstrideA[dim], dilationA[dim]);
1352
+ }
1353
+
1354
+ // Create output tensor in the correct shape in pytorch's view
1355
+ int64_t outdim1[] = {0, 0, 0, 0};
1356
+ int64_t outdim2[] = {0, 0, 0, 0};
1357
+ int64_t outdim3[] = {0, 0, 0, 0};
1358
+ if (explicit_nhwc) {
1359
+ axis[0] = 0;
1360
+ axis[1] = 2;
1361
+ axis[2] = 3;
1362
+ axis[3] = 1;
1363
+ }
1364
+ for (int dim=0;dim<4;dim++) {
1365
+ outdim1[dim] = outdimA1[axis[dim]];
1366
+ outdim2[dim] = outdimA2[axis[dim]];
1367
+ outdim3[dim] = outdimA3[axis[dim]];
1368
+ }
1369
+
1370
+ // dconv3+drelu2+dscale2
1371
+ at::Half* conv_in = inputs[13].data_ptr<at::Half>();
1372
+ at::Half* dy3 = inputs[10].data_ptr<at::Half>();
1373
+
1374
+ DEBUG_MSG("[DEBUG] new dconv3 : " << inputs[10].to(at::kFloat).sum().item<float>());
1375
+
1376
+ // wgrad
1377
+ auto wgrad3 = at::empty_like(inputs[3]);
1378
+ at::Half* dw3 = wgrad3.data_ptr<at::Half>();
1379
+ run_dconv(outdimA2,
1380
+ padA,
1381
+ convstrideA,
1382
+ dilationA,
1383
+ filterdimA3,
1384
+ outdimA3,
1385
+ CUDNN_DATA_HALF,
1386
+ conv_in,
1387
+ dw3,
1388
+ dy3,
1389
+ CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR);
1390
+
1391
+ // dgrad
1392
+ auto grad_out2 = at::empty(outdim2, inputs[0].type(), output_format);
1393
+ at::Half* dy2 = grad_out2.data_ptr<at::Half>();
1394
+ at::Half* w = inputs[3].data_ptr<at::Half>();
1395
+ at::Half* z = inputs[5].data_ptr<at::Half>();
1396
+
1397
+ at::Half* relu2 = inputs[13].data_ptr<at::Half>();
1398
+
1399
+ run_dconv_drelu_dscale(outdimA2,
1400
+ padA,
1401
+ convstrideA,
1402
+ dilationA,
1403
+ filterdimA3,
1404
+ outdimA3,
1405
+ CUDNN_DATA_HALF,
1406
+ dy2,
1407
+ w,
1408
+ dy3,
1409
+ z,
1410
+ relu2);
1411
+
1412
+ DEBUG_MSG("[DEBUG] new dconv2 : " << grad_out2.to(at::kFloat).sum().item<float>());
1413
+
1414
+ // dconv2+drelu1+dscale1
1415
+ conv_in = inputs[12].data_ptr<at::Half>();
1416
+
1417
+ // wgrad
1418
+ auto wgrad2 = at::empty_like(inputs[2]);
1419
+ at::Half* dw2 = wgrad2.data_ptr<at::Half>();
1420
+ run_dconv(outdimA1,
1421
+ padA1,
1422
+ convstrideA,
1423
+ dilationA,
1424
+ filterdimA2,
1425
+ outdimA2,
1426
+ CUDNN_DATA_HALF,
1427
+ conv_in,
1428
+ dw2,
1429
+ dy2,
1430
+ CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR);
1431
+
1432
+ // dgrad
1433
+ auto grad_out1 = at::empty(outdim1, inputs[0].type(), output_format);
1434
+ at::Half* dy1 = grad_out1.data_ptr<at::Half>();
1435
+ w = inputs[2].data_ptr<at::Half>();
1436
+ z = inputs[4].data_ptr<at::Half>();
1437
+
1438
+ at::Half* relu1 = inputs[12].data_ptr<at::Half>();
1439
+ // fused dgrad
1440
+ run_dconv_drelu_dscale(outdimA1,
1441
+ padA1,
1442
+ convstrideA,
1443
+ dilationA,
1444
+ filterdimA2,
1445
+ outdimA2,
1446
+ CUDNN_DATA_HALF,
1447
+ dy1,
1448
+ w,
1449
+ dy2,
1450
+ z,
1451
+ relu1);
1452
+
1453
+ /*
1454
+ // backward strided conv cannot be fused
1455
+ // if stride == 1 but channel changes, we can fuse here
1456
+ if (stride_1X1 != 1){
1457
+ // dgrad
1458
+ run_dconv(outdimA1,
1459
+ padA1,
1460
+ convstride1X1,
1461
+ dilationA,
1462
+ filterdimA2,
1463
+ outdimA2,
1464
+ CUDNN_DATA_HALF,
1465
+ dy1,
1466
+ w,
1467
+ dy2,
1468
+ CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR);
1469
+
1470
+ // mul fused mask
1471
+ grad_out1.mul_(inputs[15]);
1472
+ }
1473
+ else {
1474
+ at::Half* relu1 = inputs[12].data_ptr<at::Half>();
1475
+ // fused dgrad
1476
+ run_dconv_drelu_dscale(outdimA1,
1477
+ padA1,
1478
+ convstride1X1,
1479
+ dilationA,
1480
+ filterdimA2,
1481
+ outdimA2,
1482
+ CUDNN_DATA_HALF,
1483
+ dy1,
1484
+ w,
1485
+ dy2,
1486
+ z,
1487
+ relu1);
1488
+ }
1489
+ */
1490
+ DEBUG_MSG("[DEBUG] new dconv1 : " << grad_out1.to(at::kFloat).sum().item<float>());
1491
+
1492
+ // create grads of conv4 that may exist
1493
+ auto grad_x_conv4 = at::empty_like(inputs[0]);
1494
+ at::Half* dx_conv4 = grad_x_conv4.data_ptr<at::Half>();
1495
+ at::Tensor wgrad4;
1496
+
1497
+ // x used for dconv1 and dconv4 wgrad
1498
+ at::Half* x = inputs[0].data_ptr<at::Half>();
1499
+
1500
+ if (stride_1X1 != 1 || filterdimA3[0] != dimA[1]){
1501
+ w = inputs[14].data_ptr<at::Half>();
1502
+ at::Half* dy_conv4 = inputs[11].data_ptr<at::Half>();
1503
+ if (requires_grad) {
1504
+ run_dconv(dimA,
1505
+ padA,
1506
+ convstride1X1,
1507
+ dilationA,
1508
+ filterdimA4,
1509
+ outdimA3,
1510
+ CUDNN_DATA_HALF,
1511
+ dx_conv4,
1512
+ w,
1513
+ dy_conv4,
1514
+ CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR);
1515
+ // we don't print here since we can't hook out this grad in pytorch alone to compare, due to addition with dx
1516
+ // DEBUG_MSG("[DEBUG] new dx_identity : " << grad_x_conv4.to(at::kFloat).sum().item<float>());
1517
+ }
1518
+ // wgrad
1519
+ wgrad4 = at::empty_like(inputs[14]);
1520
+ at::Half* dw4 = wgrad4.data_ptr<at::Half>();
1521
+ run_dconv(dimA,
1522
+ padA,
1523
+ convstride1X1,
1524
+ dilationA,
1525
+ filterdimA4,
1526
+ outdimA3,
1527
+ CUDNN_DATA_HALF,
1528
+ x,
1529
+ dw4,
1530
+ dy_conv4,
1531
+ CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR);
1532
+ }
1533
+ else {
1534
+ // if there is no downsample, dx_conv4 is fork of drelu3
1535
+ dx_conv4 = inputs[11].data_ptr<at::Half>();
1536
+ }
1537
+
1538
+ // dconv1+add
1539
+ // wgrad
1540
+ auto wgrad1 = at::empty_like(inputs[1]);
1541
+ at::Half* dw1 = wgrad1.data_ptr<at::Half>();
1542
+ run_dconv(dimA,
1543
+ padA,
1544
+ convstride1X1,
1545
+ dilationA,
1546
+ filterdimA1,
1547
+ outdimA1,
1548
+ CUDNN_DATA_HALF,
1549
+ x,
1550
+ dw1,
1551
+ dy1,
1552
+ CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR);
1553
+
1554
+ // dgrad
1555
+ w = inputs[1].data_ptr<at::Half>();
1556
+ auto grad_x = at::empty_like(inputs[0]);
1557
+ at::Half* dx = grad_x.data_ptr<at::Half>();
1558
+
1559
+ // backward strided conv cannot be fused
1560
+ // if stride == 1 but channel changes, we can fuse here
1561
+ if (requires_grad){
1562
+ if (stride_1X1 != 1){
1563
+ run_dconv(dimA,
1564
+ padA,
1565
+ convstride1X1,
1566
+ dilationA,
1567
+ filterdimA1,
1568
+ outdimA1,
1569
+ CUDNN_DATA_HALF,
1570
+ dx,
1571
+ w,
1572
+ dy1,
1573
+ CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR);
1574
+ // add 2 together
1575
+ grad_x.add_(grad_x_conv4);
1576
+ }
1577
+ else {
1578
+ run_dconv_add(dimA,
1579
+ padA,
1580
+ convstride1X1,
1581
+ dilationA,
1582
+ filterdimA1,
1583
+ outdimA1,
1584
+ CUDNN_DATA_HALF,
1585
+ dx,
1586
+ w,
1587
+ dy1,
1588
+ dx_conv4);
1589
+ }
1590
+ }
1591
+
1592
+ DEBUG_MSG("[DEBUG] new dx : " << grad_x.to(at::kFloat).sum().item<float>());
1593
+ DEBUG_MSG("[DEBUG] new wgrad1 : " << wgrad1.to(at::kFloat).sum().item<float>());
1594
+ DEBUG_MSG("[DEBUG] new wgrad2 : " << wgrad2.to(at::kFloat).sum().item<float>());
1595
+ DEBUG_MSG("[DEBUG] new wgrad3 : " << wgrad3.to(at::kFloat).sum().item<float>());
1596
+ outputs.push_back(grad_x);
1597
+ outputs.push_back(wgrad1);
1598
+ outputs.push_back(wgrad2);
1599
+ outputs.push_back(wgrad3);
1600
+
1601
+ if (stride_1X1 != 1 || filterdimA3[0] != dimA[1]) {
1602
+ DEBUG_MSG("[DEBUG] new wgrad4 : " << wgrad4.to(at::kFloat).sum().item<float>());
1603
+ outputs.push_back(wgrad4);
1604
+ }
1605
+
1606
+ return outputs;
1607
+ }
1608
+
1609
+ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
1610
+ m.def("forward", &bottleneck_forward, "Bottleneck block forward");
1611
+ m.def("backward", &bottleneck_backward, "Bottleneck block backward");
1612
+ }
apex/apex/contrib/csrc/fmha/fmha_api.cpp ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /******************************************************************************
2
+ * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved.
3
+ *
4
+ * Redistribution and use in source and binary forms, with or without
5
+ * modification, are permitted provided that the following conditions are met:
6
+ * * Redistributions of source code must retain the above copyright
7
+ * notice, this list of conditions and the following disclaimer.
8
+ * * Redistributions in binary form must reproduce the above copyright
9
+ * notice, this list of conditions and the following disclaimer in the
10
+ * documentation and/or other materials provided with the distribution.
11
+ * * Neither the name of the NVIDIA CORPORATION nor the
12
+ * names of its contributors may be used to endorse or promote products
13
+ * derived from this software without specific prior written permission.
14
+ *
15
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
16
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18
+ * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
19
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
21
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
22
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
24
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25
+ *
26
+ ******************************************************************************/
27
+
28
+ #include <torch/extension.h>
29
+ #include <ATen/cuda/CUDAContext.h>
30
+
31
+ #include "fmha.h"
32
+
33
+ void run_fmha_fp16_128_64_sm80(const Fused_multihead_attention_fprop_params &params,
34
+ bool is_training,
35
+ cudaStream_t stream);
36
+ void run_fmha_fp16_256_64_sm80(const Fused_multihead_attention_fprop_params &params,
37
+ bool is_training,
38
+ cudaStream_t stream);
39
+ void run_fmha_fp16_384_64_sm80(const Fused_multihead_attention_fprop_params &params,
40
+ bool is_training,
41
+ cudaStream_t stream);
42
+ void run_fmha_fp16_512_64_sm80(const Fused_multihead_attention_fprop_params &params,
43
+ bool is_training,
44
+ cudaStream_t stream);
45
+
46
+ void run_fmha_dgrad_fp16_128_64_sm80(const Fused_multihead_attention_fprop_params &params,
47
+ cudaStream_t stream);
48
+ void run_fmha_dgrad_fp16_256_64_sm80(const Fused_multihead_attention_fprop_params &params,
49
+ cudaStream_t stream);
50
+ void run_fmha_dgrad_fp16_384_64_sm80(const Fused_multihead_attention_fprop_params &params,
51
+ cudaStream_t stream);
52
+ void run_fmha_dgrad_fp16_512_64_sm80(const Fused_multihead_attention_fprop_params &params,
53
+ cudaStream_t stream);
54
+
55
+ void set_params(Fused_multihead_attention_fprop_params &params,
56
+ // sizes
57
+ const size_t b,
58
+ const size_t s,
59
+ const size_t h,
60
+ const size_t d,
61
+ // device pointers
62
+ void *qkv_packed_d,
63
+ void *cu_seqlens_d,
64
+ void *seqlens_d,
65
+ void *o_packed_d,
66
+ void *s_d,
67
+ float p_dropout) {
68
+
69
+ Data_type acc_type = DATA_TYPE_FP32;
70
+ Data_type data_type = DATA_TYPE_FP16;
71
+
72
+ // Reset the parameters
73
+ memset(&params, 0, sizeof(params));
74
+
75
+ // Set the pointers and strides.
76
+ params.qkv_ptr = qkv_packed_d;
77
+ params.qkv_stride_in_bytes = get_size_in_bytes(h * 3 * d, data_type);
78
+ params.o_ptr = o_packed_d;
79
+ params.o_stride_in_bytes = get_size_in_bytes(h * d, data_type);
80
+
81
+ params.cu_seqlens = static_cast<int *>(cu_seqlens_d);
82
+ params.seqlens = static_cast<int *>(seqlens_d);
83
+
84
+ // S = softmax(P)
85
+ params.s_ptr = s_d;
86
+ params.s_stride_in_bytes = get_size_in_bytes(b * h * s, data_type);
87
+
88
+ // Set the dimensions.
89
+ params.b = b;
90
+ params.h = h;
91
+ params.s = s;
92
+ params.d = d;
93
+
94
+ // Set the different scale values.
95
+ const float scale_bmm1 = 1.f / sqrtf(d);
96
+ constexpr float scale_softmax = 1.f;
97
+ constexpr float scale_bmm2 = 1.f;
98
+
99
+ set_alpha(params.scale_bmm1, scale_bmm1, acc_type);
100
+ set_alpha(params.scale_softmax, scale_softmax, acc_type);
101
+ set_alpha(params.scale_bmm2, scale_bmm2, data_type);
102
+
103
+ // Set this to probability of keeping an element to simplify things.
104
+ params.p_dropout = 1.f - p_dropout;
105
+ params.rp_dropout = 1.f / params.p_dropout;
106
+ TORCH_CHECK(p_dropout < 1.f);
107
+ set_alpha(params.scale_dropout, params.rp_dropout, data_type);
108
+ }
109
+
110
+ constexpr uint32_t NUM_HEADS_DIM = 2;
111
+ constexpr uint32_t THREE_DIM = 1;
112
+
113
+ std::vector<at::Tensor>
114
+ mha_fwd(const at::Tensor &qkv, // total x num_heads x 3 x head_size, total := \sum_{i=0}^{b} s_i
115
+ const at::Tensor &cu_seqlens, // b+1
116
+ const at::Tensor &seqlens, // b
117
+ const float p_dropout,
118
+ const int max_seq_len,
119
+ const bool is_training,
120
+ c10::optional<at::Generator> gen_) {
121
+ auto dprops = at::cuda::getCurrentDeviceProperties();
122
+ TORCH_CHECK(dprops->major == 8 && dprops->minor == 0);
123
+ int seq_len = 512;
124
+ auto launch = &run_fmha_fp16_512_64_sm80;
125
+ if( max_seq_len <= 128 ) {
126
+ seq_len = 128;
127
+ launch = &run_fmha_fp16_128_64_sm80;
128
+ } else if( max_seq_len <= 256 ) {
129
+ seq_len = 256;
130
+ launch = &run_fmha_fp16_256_64_sm80;
131
+ } else if( max_seq_len <= 384 ) {
132
+ seq_len = 384;
133
+ launch = &run_fmha_fp16_384_64_sm80;
134
+ } else if( max_seq_len <= 512 ) {
135
+ seq_len = 512;
136
+ launch = &run_fmha_fp16_512_64_sm80;
137
+ } else {
138
+ TORCH_CHECK(false);
139
+ }
140
+
141
+ constexpr int warps_m = 1;
142
+ constexpr int warps_n = 4; // this leads to an upper bound
143
+ const int mmas_m = seq_len / 16 / warps_m;
144
+ const int mmas_n = seq_len / 16 / warps_n;
145
+
146
+ const int elts_per_thread = 8 * mmas_m * mmas_n;
147
+
148
+ auto stream = at::cuda::getCurrentCUDAStream().stream();
149
+
150
+ TORCH_CHECK(qkv.dtype() == torch::kFloat16);
151
+ TORCH_CHECK(cu_seqlens.dtype() == torch::kInt32);
152
+ TORCH_CHECK(seqlens.dtype() == torch::kInt32);
153
+
154
+ TORCH_CHECK(qkv.is_cuda())
155
+ TORCH_CHECK(cu_seqlens.is_cuda())
156
+
157
+ TORCH_CHECK(qkv.is_contiguous())
158
+ TORCH_CHECK(cu_seqlens.is_contiguous())
159
+ TORCH_CHECK(seqlens.is_contiguous())
160
+
161
+ TORCH_CHECK(cu_seqlens.dim() == 1);
162
+ TORCH_CHECK(seqlens.dim() == 1);
163
+ TORCH_CHECK(qkv.dim() == 4);
164
+
165
+ const auto sizes = qkv.sizes();
166
+
167
+ TORCH_CHECK(sizes[THREE_DIM] == 3);
168
+
169
+ const int batch_size = cu_seqlens.numel() - 1;
170
+ TORCH_CHECK(seqlens.numel() == batch_size);
171
+ const int total = sizes[0];
172
+ const int num_heads = sizes[NUM_HEADS_DIM];
173
+ const int head_size = sizes[3];
174
+ TORCH_CHECK(batch_size > 0);
175
+ TORCH_CHECK(head_size == 64);
176
+ auto opts = qkv.options();
177
+
178
+ auto ctx = torch::empty({ total, num_heads, head_size }, opts);
179
+
180
+ auto s = torch::empty({ batch_size, num_heads, seq_len, seq_len }, opts);
181
+
182
+ auto gen = at::get_generator_or_default<at::CUDAGeneratorImpl>(
183
+ gen_, at::cuda::detail::getDefaultCUDAGenerator());
184
+
185
+ Fused_multihead_attention_fprop_params params;
186
+
187
+ set_params(params,
188
+ batch_size,
189
+ seq_len,
190
+ num_heads,
191
+ head_size,
192
+ qkv.data_ptr(),
193
+ cu_seqlens.data_ptr(),
194
+ seqlens.data_ptr(),
195
+ ctx.data_ptr(),
196
+ s.data_ptr(),
197
+ p_dropout);
198
+
199
+ // number of times random will be generated per thread, to offset philox counter in thc random
200
+ // state
201
+ int64_t counter_offset = elts_per_thread;
202
+ at::PhiloxCudaState rng_engine_inputs;
203
+
204
+ if( is_training ) {
205
+ // See Note [Acquire lock when using random generators]
206
+ std::lock_guard<std::mutex> lock(gen->mutex_);
207
+ params.philox_args = gen->philox_cuda_state(counter_offset);
208
+ }
209
+
210
+ launch(params, is_training, stream);
211
+
212
+ return { ctx, s };
213
+ }
214
+
215
+ std::vector<at::Tensor>
216
+ mha_bwd(const at::Tensor &dout, // total x num_heads, x head_size
217
+ const at::Tensor &qkv, // total x num_heads x 3 x head_size, total := \sum_{i=0}^{b} s_i
218
+ at::Tensor &softmax, // b x h x s x s softmax and dmask - will be overwritten with dP
219
+ const at::Tensor &cu_seqlens, // b+1
220
+ const at::Tensor &seqlens, // b
221
+ const float p_dropout, // probability to drop
222
+ const int max_seq_len // max sequence length to choose the kernel
223
+ ) {
224
+ auto dprops = at::cuda::getCurrentDeviceProperties();
225
+ TORCH_CHECK(dprops->major == 8 && dprops->minor == 0);
226
+ int seq_len = 512;
227
+ auto launch = &run_fmha_dgrad_fp16_512_64_sm80;
228
+ if( max_seq_len <= 128 ) {
229
+ seq_len = 128;
230
+ launch = &run_fmha_dgrad_fp16_128_64_sm80;
231
+ } else if( max_seq_len <= 256 ) {
232
+ seq_len = 256;
233
+ launch = &run_fmha_dgrad_fp16_256_64_sm80;
234
+ } else if( max_seq_len <= 384 ) {
235
+ seq_len = 384;
236
+ launch = &run_fmha_dgrad_fp16_384_64_sm80;
237
+ } else if( max_seq_len <= 512 ) {
238
+ seq_len = 512;
239
+ launch = &run_fmha_dgrad_fp16_512_64_sm80;
240
+ } else {
241
+ TORCH_CHECK(false);
242
+ }
243
+
244
+ auto stream = at::cuda::getCurrentCUDAStream().stream();
245
+
246
+ TORCH_CHECK(qkv.dtype() == torch::kFloat16);
247
+ TORCH_CHECK(dout.dtype() == torch::kFloat16);
248
+ TORCH_CHECK(softmax.dtype() == torch::kFloat16);
249
+ TORCH_CHECK(cu_seqlens.dtype() == torch::kInt32);
250
+ TORCH_CHECK(seqlens.dtype() == torch::kInt32);
251
+
252
+ TORCH_CHECK(qkv.is_cuda());
253
+ TORCH_CHECK(cu_seqlens.is_cuda());
254
+
255
+ TORCH_CHECK(qkv.is_contiguous());
256
+ TORCH_CHECK(cu_seqlens.is_contiguous());
257
+ TORCH_CHECK(seqlens.is_contiguous());
258
+
259
+ TORCH_CHECK(cu_seqlens.dim() == 1);
260
+ TORCH_CHECK(seqlens.dim() == 1);
261
+ TORCH_CHECK(qkv.dim() == 4);
262
+
263
+ const auto sizes = qkv.sizes();
264
+
265
+ TORCH_CHECK(sizes[THREE_DIM] == 3);
266
+
267
+ const int batch_size = cu_seqlens.numel() - 1;
268
+ TORCH_CHECK(seqlens.numel() == batch_size);
269
+ const int num_heads = sizes[NUM_HEADS_DIM];
270
+ const int head_size = sizes[3];
271
+ TORCH_CHECK(batch_size > 0);
272
+ TORCH_CHECK(head_size == 64);
273
+
274
+ auto dqkv = torch::empty_like(qkv);
275
+
276
+ Fused_multihead_attention_fprop_params params;
277
+
278
+ set_params(params,
279
+ batch_size,
280
+ seq_len,
281
+ num_heads,
282
+ head_size,
283
+ qkv.data_ptr(),
284
+ cu_seqlens.data_ptr(),
285
+ seqlens.data_ptr(),
286
+ dout.data_ptr(), // we set o_ptr to dout
287
+ softmax.data_ptr(), // softmax gets overwritten by dP!
288
+ p_dropout);
289
+
290
+ // we're re-using these scales scales
291
+ Data_type acc_type = DATA_TYPE_FP32;
292
+ set_alpha(params.scale_bmm1, 1.f, acc_type);
293
+ set_alpha(params.scale_softmax, 1.f / sqrtf(head_size), acc_type);
294
+ set_alpha(params.scale_bmm2, 1.f, DATA_TYPE_FP16);
295
+ params.dqkv_ptr = dqkv.data_ptr();
296
+
297
+ launch(params, stream);
298
+ return { dqkv, softmax };
299
+ }
300
+
301
+ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
302
+ m.doc() = "Fused Multi-head Self-attention for BERT";
303
+ m.def("fwd", &mha_fwd, "Forward pass");
304
+ m.def("bwd", &mha_bwd, "Backward pass");
305
+ }
apex/apex/contrib/csrc/fmha/src/fmha.h ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /******************************************************************************
2
+ * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved.
3
+ *
4
+ * Redistribution and use in source and binary forms, with or without
5
+ * modification, are permitted provided that the following conditions are met:
6
+ * * Redistributions of source code must retain the above copyright
7
+ * notice, this list of conditions and the following disclaimer.
8
+ * * Redistributions in binary form must reproduce the above copyright
9
+ * notice, this list of conditions and the following disclaimer in the
10
+ * documentation and/or other materials provided with the distribution.
11
+ * * Neither the name of the NVIDIA CORPORATION nor the
12
+ * names of its contributors may be used to endorse or promote products
13
+ * derived from this software without specific prior written permission.
14
+ *
15
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
16
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18
+ * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
19
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
21
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
22
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
24
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25
+ *
26
+ ******************************************************************************/
27
+
28
+ #pragma once
29
+
30
+ #include <cuda.h>
31
+ #include <vector>
32
+
33
+ #include <ATen/CUDAGeneratorImpl.h>
34
+ #include <ATen/cuda/CUDAGraphsUtils.cuh>
35
+
36
+ #include <fmha_utils.h>
37
+
38
+ ////////////////////////////////////////////////////////////////////////////////////////////////////
39
+
40
+ struct Qkv_params {
41
+ // The QKV matrices.
42
+ void *qkv_ptr;
43
+
44
+ // The stride between rows of the Q, K and V matrices.
45
+ size_t qkv_stride_in_bytes;
46
+ };
47
+
48
+ ////////////////////////////////////////////////////////////////////////////////////////////////////
49
+
50
+ struct Fused_multihead_attention_fprop_params : public Qkv_params {
51
+
52
+ // The dQKV matrices.
53
+ void *dqkv_ptr;
54
+
55
+ // The O matrix (output).
56
+ void *o_ptr;
57
+
58
+ // The stride between rows of O.
59
+ int64_t o_stride_in_bytes;
60
+
61
+ // The pointer to the S matrix, overwritten by the dP matrix (bwd).
62
+ void *s_ptr;
63
+ // The stride between rows of the S matrix.
64
+ int64_t s_stride_in_bytes;
65
+
66
+ // The dimensions.
67
+ int b, h, s, d;
68
+
69
+ // The scaling factors for the kernel.
70
+ uint32_t scale_bmm1, scale_softmax, scale_bmm2;
71
+
72
+ // array of length b+1 holding starting offset of each sequence.
73
+ int *cu_seqlens;
74
+
75
+ // array of length b holding the actual sequence lenghts.
76
+ int *seqlens;
77
+
78
+ // The dropout probability (probability of keeping an activation).
79
+ float p_dropout;
80
+
81
+ // Scale factor of 1 / (1 - p_dropout).
82
+ float rp_dropout;
83
+
84
+ // Scale factor of 1 / (1 - p_dropout), in half2.
85
+ uint32_t scale_dropout;
86
+
87
+ // Random state.
88
+ at::PhiloxCudaState philox_args;
89
+ };
90
+
91
+ ////////////////////////////////////////////////////////////////////////////////////////////////////
92
+
apex/apex/contrib/csrc/fmha/src/fmha/gemm.h ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /******************************************************************************
2
+ * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved.
3
+ *
4
+ * Redistribution and use in source and binary forms, with or without
5
+ * modification, are permitted provided that the following conditions are met:
6
+ * * Redistributions of source code must retain the above copyright
7
+ * notice, this list of conditions and the following disclaimer.
8
+ * * Redistributions in binary form must reproduce the above copyright
9
+ * notice, this list of conditions and the following disclaimer in the
10
+ * documentation and/or other materials provided with the distribution.
11
+ * * Neither the name of the NVIDIA CORPORATION nor the
12
+ * names of its contributors may be used to endorse or promote products
13
+ * derived from this software without specific prior written permission.
14
+ *
15
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
16
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18
+ * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
19
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
21
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
22
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
24
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25
+ *
26
+ ******************************************************************************/
27
+
28
+ #pragma once
29
+
30
+ #include <fmha/utils.h>
31
+
32
+ #define FMHA_DIV_UP(m, n) (((m) + (n)-1) / (n))
33
+
34
+ namespace fmha {
35
+
36
+ ////////////////////////////////////////////////////////////////////////////////////////////////////
37
+
38
+ template< typename Data_type_, int NUM_ELTS_, int BITS_PER_ELT_, int ALIGNMENT_ >
39
+ struct Fragment_base_ {
40
+
41
+ // The data type.
42
+ using Data_type = Data_type_;
43
+ // default input type
44
+ using Input_type_ = Data_type_;
45
+ // Does it store the array of elements.
46
+ enum { HAS_ELTS = BITS_PER_ELT_ >= 8 };
47
+ // The number of elements.
48
+ enum { NUM_ELTS = NUM_ELTS_ };
49
+ // The size of element in bits.
50
+ enum { BITS_PER_ELT = BITS_PER_ELT_ };
51
+ // The size of byte of a single register.
52
+ enum { BYTES_PER_REG = 4 };
53
+ // The size in bits.
54
+ enum { BITS_PER_REG = BYTES_PER_REG * 8 };
55
+ // The number of registers needed to store the fragment.
56
+ enum { NUM_REGS = Div_up<NUM_ELTS * BITS_PER_ELT, BITS_PER_REG>::VALUE };
57
+ // The size in bytes (as returned by sizeof(Fragment_base<>).
58
+ enum { SIZE_IN_BYTES = NUM_REGS * BYTES_PER_REG };
59
+ // The alignment.
60
+ enum { ALIGNMENT = ALIGNMENT_ > 0 ? ALIGNMENT_ : Min<NUM_REGS * BYTES_PER_REG, 16>::VALUE };
61
+ };
62
+
63
+ ////////////////////////////////////////////////////////////////////////////////////////////////////
64
+
65
+ template<
66
+ // The type of the elements.
67
+ typename Data_type_,
68
+ // The number of elements.
69
+ int NUM_ELTS_,
70
+ // The alignment if you want to force a value -- use 0 otherwise.
71
+ int ALIGNMENT_ = 0,
72
+ // The base class.
73
+ typename Base_ = Fragment_base_<Data_type_, NUM_ELTS_, 8 * sizeof(Data_type_), ALIGNMENT_>
74
+ >
75
+ struct alignas(static_cast<int>(Base_::ALIGNMENT)) Fragment : public Base_ {
76
+
77
+ // The size of a load/store.
78
+ enum { BYTES_PER_LOAD_STORE = Base_::NUM_REGS * sizeof(uint32_t) };
79
+
80
+ // Clear the fragment. Using PTX in that code seems to produce better SASS...
81
+ inline __device__ void clear() {
82
+ #pragma unroll
83
+ for( int ii = 0; ii < Base_::NUM_REGS; ++ii ) {
84
+ asm volatile("mov.u32 %0, 0; \n" : "=r"(this->reg(ii)) : );
85
+ }
86
+ }
87
+
88
+ // Immutable access to a register.
89
+ inline __device__ const uint32_t& reg(int ii) const {
90
+ return this->regs_[ii];
91
+ }
92
+
93
+ // Mutable access to a register.
94
+ inline __device__ uint32_t& reg(int ii) {
95
+ return this->regs_[ii];
96
+ }
97
+
98
+ uint32_t regs_[Base_::NUM_REGS];
99
+
100
+ // Immutable access to the elements.
101
+ inline __device__ const Data_type_& elt(int ii) const {
102
+ return reinterpret_cast<const Data_type_*>(&this->regs_[0])[ii];
103
+ }
104
+
105
+ // Mutable access to the elements.
106
+ inline __device__ Data_type_& elt(int ii) {
107
+ return reinterpret_cast<Data_type_*>(&this->regs_[0])[ii];
108
+ }
109
+
110
+ // Immutable access to the elements with a cast.
111
+ template< typename Cast_type >
112
+ inline __device__ const Cast_type& elt_as(int ii) const {
113
+ return reinterpret_cast<const Cast_type*>(&this->regs_[0])[ii];
114
+ }
115
+
116
+ // Mutable access to the elements.
117
+ template< typename Cast_type >
118
+ inline __device__ Cast_type& elt_as(int ii) {
119
+ return reinterpret_cast<Cast_type*>(&this->regs_[0])[ii];
120
+ }
121
+
122
+ // Add another fragment.
123
+ inline __device__ void add(const Fragment &other) {
124
+ #pragma unroll
125
+ for( int ii = 0; ii < NUM_ELTS_; ++ii ) {
126
+ this->elt(ii) += other.elt(ii);
127
+ }
128
+ }
129
+ };
130
+
131
+ ////////////////////////////////////////////////////////////////////////////////////////////////////
132
+
133
+ template< typename Layout >
134
+ struct Fragment_a : public Fragment<uint16_t, 8> {
135
+ };
136
+
137
+ ////////////////////////////////////////////////////////////////////////////////////////////////////
138
+
139
+ template< typename Layout >
140
+ struct Fragment_b : public Fragment<uint16_t, 8> {
141
+ };
142
+
143
+ ////////////////////////////////////////////////////////////////////////////////////////////////////
144
+
145
+ struct Fragment_accumulator : public Fragment<float, 8> {
146
+
147
+ // The base class.
148
+ using Base = Fragment<float, 8>;
149
+
150
+ // Add two fragments.
151
+ template< typename Other_fragment_ >
152
+ inline __device__ void add(const Other_fragment_ &other) {
153
+ for( int ii = 0; ii < Base::NUM_ELTS; ++ii ) {
154
+ this->elt(ii) = this->elt(ii) + other.elt(ii);
155
+ }
156
+ }
157
+
158
+ // Do the HMMA.
159
+ template< typename Layout_a, typename Layout_b >
160
+ inline __device__ void mma(const Fragment_a<Layout_a> &a,
161
+ const Fragment_b<Layout_b> &b) {
162
+ asm volatile( \
163
+ "mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 \n" \
164
+ " {%0, %1, %2, %3}, \n" \
165
+ " {%4, %5, %6, %7}, \n" \
166
+ " {%8, %9}, \n" \
167
+ " {%0, %1, %2, %3}; \n" \
168
+ : "+f"( elt(0)), "+f"( elt(1)), "+f"( elt(2)), "+f"( elt(3))
169
+ : "r"(a.reg(0)), "r"(a.reg(1)), "r"(a.reg(2)), "r"(a.reg(3))
170
+ , "r"(b.reg(0)), "r"(b.reg(1)));
171
+ asm volatile( \
172
+ "mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 \n" \
173
+ " {%0, %1, %2, %3}, \n" \
174
+ " {%4, %5, %6, %7}, \n" \
175
+ " {%8, %9}, \n" \
176
+ " {%0, %1, %2, %3}; \n" \
177
+ : "+f"( elt(4)), "+f"( elt(5)), "+f"( elt(6)), "+f"( elt(7))
178
+ : "r"(a.reg(0)), "r"(a.reg(1)), "r"(a.reg(2)), "r"(a.reg(3))
179
+ , "r"(b.reg(2)), "r"(b.reg(3)));
180
+ }
181
+
182
+ };
183
+
184
+ ////////////////////////////////////////////////////////////////////////////////////////////////////
185
+
186
+ template< typename Fragment, int M, int N >
187
+ inline __device__ void clear(Fragment (&frag)[M][N]) {
188
+ #pragma unroll
189
+ for( int mi = 0; mi < M; ++mi ) {
190
+ #pragma unroll
191
+ for( int ni = 0; ni < N; ++ni ) {
192
+ frag[mi][ni].clear();
193
+ }
194
+ }
195
+ }
196
+
197
+ ////////////////////////////////////////////////////////////////////////////////////////////////////
198
+
199
+ template< typename Accumulator_type, int WARPS_K >
200
+ struct Clear_accumulator {
201
+ };
202
+
203
+ ////////////////////////////////////////////////////////////////////////////////////////////////////
204
+
205
+ template< int WARPS_K >
206
+ struct Clear_accumulator<float, WARPS_K> {
207
+ template< typename Acc, int M, int N >
208
+ static inline __device__ void apply(Acc (&acc)[M][N], bool = false) {
209
+ fmha::clear(acc);
210
+ }
211
+ };
212
+
213
+ ////////////////////////////////////////////////////////////////////////////////////////////////////
214
+
215
+
216
+ ////////////////////////////////////////////////////////////////////////////////////////////////////
217
+
218
+ template<typename Acc, typename A, typename B, int M, int N>
219
+ inline __device__ void gemm(Acc (&acc)[M][N], const A (&a)[M], const B (&b)[N]) {
220
+
221
+ #pragma unroll
222
+ for( int mi = 0; mi < M; ++mi ) {
223
+ #pragma unroll
224
+ for( int ni = 0; ni < N; ++ni ) {
225
+ acc[mi][ni].mma(a[mi], b[ni]);
226
+ }
227
+ }
228
+ }
229
+
230
+ ////////////////////////////////////////////////////////////////////////////////////////////////////
231
+
232
+ template<
233
+ // The number of rows in the CTA tile.
234
+ int M_,
235
+ // The number of cols in the CTA tile.
236
+ int N_,
237
+ // The number of elements in the the K dimension of the GEMM loop.
238
+ int K_,
239
+ // The number of rows of warps.
240
+ int WARPS_M_,
241
+ // The number of cols of warps.
242
+ int WARPS_N_,
243
+ // The number of warps in the K dimension of the GEMM loop.
244
+ int WARPS_K_>
245
+ struct Cta_tile_ {
246
+
247
+ enum { M = M_, N = N_, K = K_ };
248
+ // The number of warps.
249
+ enum { WARPS_M = WARPS_M_, WARPS_N = WARPS_N_, WARPS_K = WARPS_K_ };
250
+ // The number of warps per CTA.
251
+ enum { WARPS_PER_CTA = WARPS_M * WARPS_N * WARPS_K };
252
+ // The number of threads per warp.
253
+ enum { THREADS_PER_WARP = 32 };
254
+ // The number of threads per CTA.
255
+ enum { THREADS_PER_CTA = WARPS_PER_CTA * THREADS_PER_WARP };
256
+ };
257
+
258
+ ////////////////////////////////////////////////////////////////////////////////////////////////////
259
+
260
+ template<typename Cta_tile>
261
+ struct Hmma_tile {
262
+ // The number of elements computed with a single warp-MMA.
263
+ enum { M_PER_MMA = 16, N_PER_MMA = 16, K_PER_MMA = 16 };
264
+
265
+ // The number of elements computed with a single CTA-MMA.
266
+ enum {
267
+ M_PER_MMA_PER_CTA = M_PER_MMA * Cta_tile::WARPS_M,
268
+ N_PER_MMA_PER_CTA = N_PER_MMA * Cta_tile::WARPS_N,
269
+ K_PER_MMA_PER_CTA = K_PER_MMA * Cta_tile::WARPS_K
270
+ };
271
+
272
+ // The number of MMAs needed to compute the GEMM.
273
+ enum {
274
+ MMAS_M = Div_up<Cta_tile::M, M_PER_MMA_PER_CTA>::VALUE,
275
+ MMAS_N = Div_up<Cta_tile::N, N_PER_MMA_PER_CTA>::VALUE,
276
+ MMAS_K = Div_up<Cta_tile::K, K_PER_MMA_PER_CTA>::VALUE,
277
+ };
278
+
279
+ // The number of elements computed per warp.
280
+ enum {
281
+ M_PER_WARP = MMAS_M * M_PER_MMA,
282
+ N_PER_WARP = MMAS_N * N_PER_MMA,
283
+ K_PER_WARP = MMAS_K * K_PER_MMA,
284
+ };
285
+
286
+ };
287
+
288
+ ////////////////////////////////////////////////////////////////////////////////////////////////////
289
+
290
+ using A_type = uint16_t;
291
+ using B_type = uint16_t;
292
+ using C_type = uint16_t;
293
+ using Accumulator_type = float;
294
+ using Epilogue_type = float;
295
+
296
+ constexpr int BITS_PER_ELEMENT_A = sizeof(A_type) * 8;
297
+ constexpr int BITS_PER_ELEMENT_B = sizeof(B_type) * 8;
298
+ constexpr int BITS_PER_ELEMENT_C = sizeof(C_type) * 8;
299
+
300
+ ////////////////////////////////////////////////////////////////////////////////////////////////////
301
+
302
+ template<int M, int N, int K, int WARPS_M, int WARPS_N, int WARPS_K>
303
+ using Cta_tile_extd = Cta_tile_<M, N, K, WARPS_M, WARPS_N, WARPS_K>;
304
+
305
+ ////////////////////////////////////////////////////////////////////////////////////////////////////
306
+
307
+ template<typename Cta_tile_>
308
+ using Cta_tile_with_k_with_padding = Cta_tile_extd<Cta_tile_::M,
309
+ Cta_tile_::N,
310
+ Next_power_of_two<Cta_tile_::K>::VALUE,
311
+ Cta_tile_::WARPS_M,
312
+ Cta_tile_::WARPS_N,
313
+ Cta_tile_::WARPS_K>;
314
+
315
+ ////////////////////////////////////////////////////////////////////////////////////////////////////
316
+
317
+ } // namespace fmha