-
Notifications
You must be signed in to change notification settings - Fork 177
/
float8_scaling_utils.py
307 lines (274 loc) · 8.96 KB
/
float8_scaling_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD 3-Clause license found in the
# LICENSE file in the root directory of this source tree.
"""
Utilities for scaling high precision tensors to float8.
"""
from typing import Optional
import torch
from torchao.float8.config import ScalingGranularity
from torchao.float8.float8_tensor import (
Float8Tensor,
GemmInputRole,
LinearMMConfig,
hp_tensor_and_scale_to_float8,
tensor_already_casted_to_fp8,
)
from torchao.float8.float8_utils import (
amax_history_to_scale,
e5m2_dtype,
tensor_to_amax,
tensor_to_scale,
)
def hp_tensor_to_float8_dynamic(
hp_tensor: torch.Tensor,
float8_dtype: torch.dtype,
linear_mm_config: LinearMMConfig,
reduce_amax: bool = False,
gemm_input_role: GemmInputRole = GemmInputRole.INPUT,
device_mesh=None,
scaling_granularity: ScalingGranularity = ScalingGranularity.TENSORWISE,
axiswise_dim: Optional[int] = None,
) -> Float8Tensor:
"""
Given a high precision tensor `hp_tensor`,
scales `hp_tensor` dynamically and returns a `Float8Tensor` of the result.
Args:
hp_tensor: the tensor to convert
float8_dtype: the float8 dtype to use
linear_mm_config: Defines the configuration for the scaled_mm for
the 3 fwd/bwd gemms of linear
reduce_amax: whether to reduce the max(abs(hp_tensor)) value across distributed ranks
gemm_input_role: Defines the role of this tensor (input, weight or grad_output) in
the 3 fwd/bwd gemms of linear
scaling_granularity: Defines the scaling granularity
axiswise_dim: if axiswise granularity is used, defines the dim to scale across
"""
if tensor_already_casted_to_fp8(hp_tensor):
return hp_tensor
scale = tensor_to_scale(
hp_tensor,
float8_dtype,
reduce_amax,
device_mesh,
scaling_granularity,
axiswise_dim,
)
return hp_tensor_and_scale_to_float8(
hp_tensor,
scale,
float8_dtype,
linear_mm_config,
gemm_input_role,
axiswise_dim,
)
def hp_tensor_to_float8_delayed(
hp_tensor: torch.Tensor,
s: torch.Tensor,
float8_dtype: torch.dtype,
amax_buffer: torch.Tensor,
linear_mm_config: Optional[LinearMMConfig] = None,
gemm_input_role: Optional[GemmInputRole] = GemmInputRole.INPUT,
) -> Float8Tensor:
"""
Given a high precision tensor `hp_tensor` and relevant metadata, scales it using
delayed scaling and returns a `Float8Tensor` of the result. Specifically:
1. calculates max(abs(hp_tensor)) and stores the result in `amax_buffer`, inplace
2. scales `hp_tensor` by `s` and returns the result wrapped in Float8Tensor
Args:
hp_tensor: the tensor to convert
s: the scale to use to convert the tensor
float8_dtype: the float8 dtype to use
amax_buffer: the buffer to modify inplace with max(abs(hp_tensor))
linear_mm_config: Defines the configuration for the scaled_mm for
the 3 fwd/bwd gemms of linear
gemm_input_role: Defines the role of this tensor (input, weight or grad_output) in
the 3 fwd/bwd gemms of linear
"""
amax_buffer.fill_(tensor_to_amax(hp_tensor))
return hp_tensor_and_scale_to_float8(
hp_tensor,
s,
float8_dtype,
linear_mm_config,
gemm_input_role,
)
def hp_tensor_to_float8_static(
hp_tensor: torch.Tensor,
scale: torch.Tensor,
float8_dtype: torch.dtype,
linear_mm_config: LinearMMConfig,
gemm_input_role: GemmInputRole = GemmInputRole.INPUT,
) -> Float8Tensor:
"""
Given a high precision tensor `hp_tensor` and a scale,
scales `hp_tensor` returns a `Float8Tensor` of the result.
Args:
hp_tensor: the tensor to convert
scale: the scale to use
float8_dtype: the float8 dtype to use
linear_mm_config: Defines the configuration for the scaled_mm for
the 3 fwd/bwd gemms of linear
gemm_input_role: Defines the role of this tensor (input, weight or grad_output) in
the 3 fwd/bwd gemms of linear
"""
if tensor_already_casted_to_fp8(hp_tensor):
return hp_tensor
return hp_tensor_and_scale_to_float8(
hp_tensor,
scale,
float8_dtype,
linear_mm_config,
gemm_input_role,
)
def get_maybe_axiswise_dim(
axiswise_dim: int,
scaling_granularity: ScalingGranularity,
) -> Optional[int]:
"""
Convenience function which takes in an axiswise dim which is only relevant
for axiswise scaing, and a scaling type. The output is pass-through
if scaling type is axiswise, and None otherwise. This is done to keep the
logic from choosing the axiswise dim out of the scaling function.
"""
if scaling_granularity is ScalingGranularity.AXISWISE:
return axiswise_dim
return None
def _maybe_initialize_amaxes_scales_for_float8_cast(
x,
cur_amax,
amax_history,
scale,
scale_fn_name,
float8_dtype,
is_initialized,
reduce_amax,
):
"""
If x is about to be cast to `float8` and the amax buffers are not initialized,
initializes them inplace.
"""
if is_initialized:
return
with torch.no_grad():
# Note: we need to enable distributed reduction here in order
# to match numerics between single GPU and multi GPU code for
# activations and gradients
new_amax = tensor_to_amax(x, reduce_amax=reduce_amax)
cur_amax.fill_(new_amax)
amax_history[0] = new_amax
new_scale = amax_history_to_scale(
amax_history, float8_dtype, x.dtype, scale_fn_name
)
scale.copy_(new_scale)
@torch._dynamo.allow_in_graph
class NoopFwToFloat8E5M2BwDelayed(torch.autograd.Function):
"""
Forward: no-op
Backward: convert to float8_e5m2 with delayed scaling, initialize if needed
"""
@staticmethod
def forward(
ctx,
tensor,
fp8_amax_grad_output,
fp8_amax_history_grad_output,
fp8_scale_grad_output,
scale_fn_name,
is_amax_initialized,
linear_mm_config: LinearMMConfig,
):
ctx.save_for_backward(
fp8_amax_grad_output, fp8_amax_history_grad_output, fp8_scale_grad_output
)
ctx.scale_fn_name = scale_fn_name
ctx.is_amax_initialized = is_amax_initialized
ctx.linear_mm_config = linear_mm_config
return tensor
@staticmethod
def backward(ctx, go):
(
fp8_amax_grad_output,
fp8_amax_history_grad_output,
fp8_scale_grad_output,
) = ctx.saved_tensors
scale_fn_name = ctx.scale_fn_name
is_amax_initialized = ctx.is_amax_initialized
_maybe_initialize_amaxes_scales_for_float8_cast(
go,
fp8_amax_grad_output,
fp8_amax_history_grad_output,
fp8_scale_grad_output,
scale_fn_name,
e5m2_dtype,
is_amax_initialized,
reduce_amax=True,
)
fp8_amax_grad_output.fill_(tensor_to_amax(go))
res = hp_tensor_and_scale_to_float8(
go,
fp8_scale_grad_output,
e5m2_dtype,
ctx.linear_mm_config,
GemmInputRole.GRAD_OUTPUT,
)
empty_grads = None, None, None, None, None, None
return res, *empty_grads
@torch._dynamo.allow_in_graph
class NoopFwToFloat8E5M2BwDynamic(torch.autograd.Function):
"""
Forward: no-op
Backward: convert to float8_e5m2 with dynamic scaling
"""
@staticmethod
def forward(
ctx,
tensor,
linear_mm_config: LinearMMConfig,
):
ctx.linear_mm_config = linear_mm_config
return tensor
@staticmethod
def backward(ctx, gradY):
if tensor_already_casted_to_fp8(gradY):
return gradY, None
gradY_scale = tensor_to_scale(gradY, e5m2_dtype)
fp8_tensor = hp_tensor_and_scale_to_float8(
gradY,
gradY_scale,
e5m2_dtype,
ctx.linear_mm_config,
GemmInputRole.GRAD_OUTPUT,
)
return fp8_tensor, None
@torch._dynamo.allow_in_graph
class NoopFwToFloat8E5M2BwStatic(torch.autograd.Function):
"""
Forward: no-op
Backward: convert to float8_e5m2 with static scaling
"""
@staticmethod
def forward(
ctx,
tensor,
scale,
linear_mm_config: LinearMMConfig,
):
ctx.save_for_backward(scale)
ctx.linear_mm_config = linear_mm_config
return tensor
@staticmethod
def backward(ctx, gradY):
if tensor_already_casted_to_fp8(gradY):
return gradY, None
(gradY_scale,) = ctx.saved_tensors
fp8_tensor = hp_tensor_and_scale_to_float8(
gradY,
gradY_scale,
e5m2_dtype,
ctx.linear_mm_config,
GemmInputRole.GRAD_OUTPUT,
)
return fp8_tensor, None, None